Forum Controls
Spotlight Features

The Rich Engineering Heritage Behind Dependency Injection

Andrew McVeigh takes us on a tour of the rich heritage behind dependency injection, what it represents, and tells us why its here to stay.

Java, the OLPC, and community responsibility

The "One Laptop Per Child" project has a great device ready to ship, but there's no Java on there. Let's think about working together to put Java on OLPC!
Replies: 7 - Pages: 1  
Threads: [ Previous | Next ]
  Click to reply to this thread Reply

Sort Members

At 5:45 PM on Jan 10, 2007, Alex Blewitt DeveloperZone Top 100 wrote:

Java has a Sort Members operation, which allows you to sort the order of the fields, methods and constructors inside the source file. It seems to be under used by Eclipse developers; either because they don't know it's there, or because it's not easy to get at. It's got some usability issues -- it only works on a file-by-file basis, not a project/package, and it doesn't have a keystroke -- which makes it a little bit more difficult to use but not impossible.

(I'm working on adding the Sort Members functionality to the Clean Up page, which will make it easier both to apply and also to apply to project-wide contents, or even with the Clean Up on save option.)

So, what does the sort members do? Well, you can chose whether you want to have methods or methods+fields sorted, so that:

public class ToSort {
  int b;
  int a;
  void d() {}
  void c() {}
}


will become either

public class ToSort {
  int b;
  int a;
  void c() {}
  void d() {}
}


or

public class ToSort {
  int a;
  int b;
  void c() {}
  void d() {}
}


Why not sort fields? Well, there's cases where re-ordering the fields *may* cause initialisation problems. For example, if we had:
int b = 3;
int a = 2*b;
[code]
 
then the code would compile; but if it were sorted:
 
[code]
int a = 2*b;  // b is not defined at this point
int b = 3;


this would be a compile-time error. Fortunately, such cases are rare in Java (though not impossible) so whilst it's not guaranteed 100% safe, it's actually sufficiently rare that it makes sense to do this.

(NB it also sorts Enums as well, which if you're wanting to use the auto-numbering can be an issue.)

So, what benefit is there for sorting members? Well, like a good coding convention, if everyone follows it it makes it a lot easier to find what's going on. In addition (also like coding conventions) if you always sort members then it makes diffs with a remote server much easier to understand.

A sorted member has exactly one place where it should be inserted, and anyone who adds members and sorts will see the same behaviour. On the other hand, a large number of Java files just have methods tacked onto the end, which results in a more haphazard file. (See the contents of the average Java class library's .class files, in which the order of methods corresponds to the order in the source. They're all over the place.)

The other thing about sorting members is that it's unambiguous. None of the special cases (e.g. 'except when it's a getter/setter' or 'if they are in the same interface' or 'which delegate to another object') -- which may well overlap (e.g. what rule do you follow with methods 'a','b','c','d' when 'a' and 'c' are in one interface, 'b' and 'd' are in another interface, and 'a' and 'd' are in a third interface? And what about the ineffable equals/hashcode?

Sorting is really the only pragmatic way of ordering the methods that's clear, unambiguous, and will help with any diffs. The only real wonder is why people don't use it more; but like I hinted at the start, it's probably because it's not easy to sort members; with any luck, that will be easier soon. Fortunately, if you have to work with an unsorted file, you can select 'A-Z' on the Members toolbar to see an alphabetical list of the members.

One of the things that Mylar will help with everyone is that a Java source file isn't just a source file; it's a class definition, that contains members. If you've come from a Visual Age for Java background with its object-oriented rather than file-oriented view (and yes, obligatory Smalltalk comment where applicable), then you'll be used to thinking of a program in terms of objects and methods, not in terms of chars and files. Unfortuantely, many Java developers still think of a .java file as text instead of as a representation of an object. Mylar will force people to reconsider by having automatic hiding of irrelevant methods/fields, and hopefully encourage people to start thinking of .java files as class definitions instead of text files.

Alex.
  Click to reply to this thread Reply
1. At 1:52 PM on Jan 24, 2007, Alex Blewitt DeveloperZone Top 100 wrote:

Re: Sort Members

For those that are interested, the ability to sort members on save via the clean up code has been added in with bugs 171066 and 168954 and should be available in 3.3M5 when it's released in a couple of weeks.

Alex
  Click to reply to this thread Reply
2. At 11:59 PM on Feb 3, 2007, Dov Wasserman Javalobby Newcomers wrote:

Re: Sort Members

Interesting post, Alex. Thanks for pointing out this handy feature. A few thoughts about cases/reasons where it can make sense to not sort methods alphabetically. Here are a few ways that I have learned over the years to order methods based on their meanings. I'm sure many will look familiar.

  1. Accessibility. I'd find it confusing to see public, private and protected methods all intermingled in the code. I expect to find the class's contract -- its public methods -- defined first, followed by the internal helper methods that provide the implementation.


  2. Scope. I like the convention that public static methods should appear before instance methods, because they denote a different meaning: stateless function transformations vs. changing a particular object's state.


  3. Functionality. A class can have a few related methods which read best when bunched together, especially the private implementation methods that work on successively transformed versions of things. For example:

    • private List getUsers() { ... }

    • private List getUserIds() { ... }

    • private User getUser(String userId) { ... }

    • private UserDao lookupUser(String userId, Connection dbConn) { ... }


    You get the idea. Having these methods defined in order of their logical flow makes the code easier to comprehend, imho. It also tends to more efficient to have them together when you change some aspect of these methods which ripples through all of them, e.g., changing the returned objects from type User to Profile.


  4. Other forms of grouping or ordering are more stylistic, where we may each have our own preferences, but there's not as strong a reason to impose one particular version. For example:

    • Grouping setters and getters together (then: all getters first, or each property with get/set methods in sequence; and in which sequence)

    • Factory-style methods defined right after the constructor: clone(), makeCopy(Type), intern()/canonicalize().

    • Non-mutating methods (which don't change the object's state) before mutating ones; e.g., List.size(), isEmpty(), then remove(index).



    In summary, I like the concept you espouse of coding conventions, to remove the effort needed for the unproductive decision of how to organize things that can be organized in any of of number of ways, which also helps future maintainers know where to find things they expect. However, I think class method order is one those areas where making some semantic decisions does provide benefits of readability and ease of development.

    A very useful synthesis of all these ideas might be a project-defined method sort order, with options corresponding to the above concepts. Thats a lot more complicated, of course, but would provide the benefits you outlined for the simple alphabetic ordering. I guess I'd rather be faced with the problem of which exact method grouping and ordering to use, than be guaranteed a (generally) meaningless order by the cruel tyranny of our uncaring alphabet ;-). What are your thoughts on the feasability of such a Method Order Preferences option?
  Click to reply to this thread Reply
3. At 2:22 AM on Feb 4, 2007, !vS_ Javalobby Regulars wrote:

Re: Sort Members

Good post. Thanks
Planet Java
  Click to reply to this thread Reply
4. At 12:07 PM on Feb 4, 2007, Alex Blewitt DeveloperZone Top 100 wrote:

Re: Sort Members

A couple of things ...

The sort members preference does allow you to have some kind of control. For example, static methods do get sorted before instance methods; in fact, the overall ordering is inner classes/static fields/instance fields/static methods/constructors/instance methods (or something like that, anyway). So for the 'static' part, you can have some control.

> Accessibility. I'd find it confusing to see public, private and protected methods all
> intermingled in the code. I expect to find the class's contract -- its public methods
> -- defined first, followed by the internal helper methods that provide the
> implementation.

True, but that's just a personal interpretation based on what you're used to. It's a bit like saying it's confusing to have the open/close braces on the same (or different) line, depending on personal preference. Something that you get used to becomes your convention, and you shouldn't be afraid to change it just because it's not something you're used to.

> Functionality. A class can have a few related methods which read best when
> bunched together, especially the private implementation methods that work on
> successively transformed versions of things. For example:

Yes, but private/public methods can be grouped together for the same reason. A class might have private setters but public getters, and they may be intermixed; or some of the examples that you list may be promoted to private/protected/public or whatever as life goes on.

> Other forms of grouping or ordering are more stylistic, where we may each have
> our own preferences, but there's not as strong a reason to impose one particular
> version. For example:

I don't disagree that some people will have other ways of doing things e.g. 'get/set' next to each other, or hash/equals being next to each other (and similarly for other superclass' methods.

The problem with all of this is that it becomes very difficult to say "Does this class follow X convention", particulary in the weird cases. (Like: the interface has a getter, but no setter; yet they're both public in the implementation class. Do they get sorted together, or do you sort the interface's methods together? What happens if the same method occurs in two or more interfaces that you implement? What about when the setter goes private?)

And the thing is, it's also a lot more difficult for humans to interpret. Any time you have to answer with 'yeah, but in that case ...' you've got a system which is too hard for humans to interpret.

I don't doubt that other orderings are possible -- for example, sorting all methods and fields by length of identifier name would be one -- but the point is that any such ordering should be (a) easy to understand, and (b) unambiguous in all cases. Although you list other possible variations on that, some of them are not. For example, you prefer to have 'public methods separted from interna helper methods'. What about when a class implements an interface? Surely then, its interface is the public methods that exist in that interface only. Others may be public -- particularly in *.internal.* cases -- to merely allow other internal classes to access them, but still not be considered part of the class's contract.

The point is that it doesn't really matter *what* it is, as long as there *is* one. The same's just as true for sorting members in a class as it is for indenting in the same way. And ultimately, when using a version control system, the benefit in everyone using the same convention means that when changes occur, they are real changes and not just formatting/sorting ones.

I'll leave it to you to define a fully unambiguous grouping mechanism that you're happy with; I personally am happy with alphabetic sorting in the major groups of fields/constructors/methods etc.

Alex.
  Click to reply to this thread Reply
5. At 12:16 AM on Feb 5, 2007, !vS_ Javalobby Regulars wrote:

Re: Sort Members

interesting
Planet Java
  Click to reply to this thread Reply
6. At 12:37 AM on Mar 10, 2007, Nigel Westbury Javalobby Newcomers wrote:

Re: Sort Members

Alex supposes that the reason why not many people use this feature is because they don't know about it. There is another reason. Perhaps developers don't want their fields and methods in alphabetical order. The usual ordering conventions, as Dov described, have evolved over decades, they are used on just about every project I have known, and they work well. I am at a loss as to the problem that Alex is trying to fix when he tries to throw decades of tradition out the window.

Alex makes some arguments that are totally fallacious.

1. He says diffs work better. Actually the opposite is the case. When you put a method next to related methods, the order does not change. The order would only change if someone decided that a method really related to a different group of methods and so made a positive decision to move the method. We really don't find that happens very often.

On the other hand, method restructuring such as renames are very common. Just this morning I split a method called createAndLoadControl into two methods called createControl and loadControl. Without sorting the two methods would be left next to each other and a diff would show that the code is almost the same, just with a closing brace and a new function declaration being inserted in the middle. If the methods had been sorted, the diff would be messed up because code would be moved.

2. Code is a lot easier to read if the methods are sequenced in a meaningful order. To use the above example, I can find code a lot more easily if the loadControl method follows immediately after the createControl method. If we used this alphabetical order idea then it would be a harder to find the related methods, even if I did happen to remember the names of all the methods.

3. Alex makes a big thing about the order being unambiguous. Yet he gives no reason why there is a requirement or advantage for the order to be unambiguous. Even if there is an advantage to having an unambiguous order, and I cannot think of one, Alex's alphabetical order idea does not achieve this. That is because the rules for naming the fields and methods are not unambiguous. One developer might have called the method by one name, and another developer, had he/she added the same method, might have given a different name to the method. So, the method goes in a completely different place depending on which developer added it. So again, Alex has it backwards.

Alex uses the argument " what if the interface has a getter, but no setter; yet they're both public in the implementation class. Do they get sorted together, or do you sort the interface's methods together? What happens if the same method occurs in two or more interfaces that you implement? What about when the setter goes private"? Who cares. I have never before heard a programmer be so anal as to argue about the order of methods in such cases.

I generally enjoy reading Alex's posts, so I am particularly perplexed by this one.

- Nigel
  Click to reply to this thread Reply
7. At 1:46 PM on Mar 17, 2007, Alex Blewitt DeveloperZone Top 100 wrote:

Re: Sort Members

Each to their own. It's like trying to say that having braces on the same/next line is better than the next/same line.

Note also that what works for me is not guaranteed to work for you. However, just because it doesn't work for you doesn't mean that it therefore must not work for others too.

In any case, if you want to have a guaranteed ordering of members within a class (and don't forget, objects contain a set of methods, not an ordered set of methods) then this will give it to you. If you don't want that, don't use it :-)

Alex.

thread.rss_message