Using Sections in Java Classes
In last month’s discussion started by Martin Fowler’s article on humane interfaces, some people mentioned Smalltalk’s method categories. These categories supposedly serve to bring order to classes containing large number of methods. I wonder if something like that would work for Java. (Personally, I wouldn’t call them ‘categories’, as categories imply that you can assign multiple categories to a method as well as multiple methods to a category.) For example, you could have:
public class String { section getters { public char charAt(int index) { // ... } // ... } section testers { public int compareTo(String anotherString) { // ... } // ... } section mutators { public String replace(char oldChar, char newChar) { // ... } // ... } section finders { public int indexOf(String str) { // ... } // ... } // ... }
The section names would not be used anywhere else in the code, so you don’t use "text".finders.indexOf("e")
. Their use would be limited to sorting method names in IDEs, JavaDoc etc. So it would make sense to add JavaDoc to the sections, like this:
public class String { /** * Groups methods retrieving parts of the String object * or its attributes. */ section getters { public char charAt(int index) { // ... } // ... }
One possible functional use for sections would be to allow access modifiers to sections, so you could have a public section businessMethods
and a private section privateMethods
.
There would have to be additional rules about inheriting sections in subclasses, using sections in interfaces, having methods outside sections, naming standards for recurring types of sections and such things.
The question is: does Java need something like this? The String class isn’t that huge, doesn’t have hundreds of methods like Smalltalk classes seem to have (note to self: read Smalltalk primer). I was triggered, actually, by a comment earlier on this blog, about the DefaultOWLIndividual class. It’s an example of a Java class that does have 300+ methods. A class like that would certainly benefit from (inherited!) class sections. I’m sure there are many more examples of large classes like this one.
But even if a class is not that humongous, even if it only has 10 or 20 methods; wouldn’t it still make the interface design more clear and structured if it had sections? It could also show better the intended use of the methods in the class (business methods vs. private methods). So I think sections could be a useful addition to the Java syntax.
2006-01-02. 3 responses.