|
I am always looking for ways to increase code clarity and reduce confusion and maintenance associated with "dangling methods". What's a dangling method? It's a method that is only used by another method to reduce code duplication. The scope of this method should therefore be local to only the calling function.
I tend to run into this problem when doing string manipulation. Currently I need to do a "last added character" for a CharBuffer. The only way to currently do this is to add a member function:
private char lastChar(final CharBuffer buffer)
{
// determine if there are already chars in the buffer. If
// there are none, throw.
if(buffer.position <= 0)
throw new IndexOutOfBoundsException();
/* else -- there are characters in the buffer */
// retrieve the last character placed into the buffer
// NOTE: the above check ensures that there will be a char
return buffer.get(buffer.position - 1);
}
to the class. This is no good since the scope of the method is too large. Large scope equals more time determining dependencies which equals more time to debug.
If Java allowed for nested functions, one could write:
private String normalize(final String string)
{
...
// inner function for determining the last character
// added to a buffer
char lastChar(final CharBuffer buffer)
{
...
};
...
case '/':
if(lastChar(buffer) != '/')
...
...
}
Having nested (or inner) functions in Java would help enormously. Kris Wehner brought up a Smalltalk technique which would be somewhat useful in this case. What do you think a solution to this problem would be?
|