Wednesday, December 28, 2011

When is it ok to use method overloading in Java ?

In his excellent book Efficient Java Programming, Joshua Bloch has an item titled:
Item 41: Use overloading judiciously
Because I'm going to use method overloading in my NullObjectProxy implementation I will give some additional information about when it is ok to use method overloading. I highly recommend that you read Item 41 but here is a little extra graphic help and also a relaxation of Joshua Bloch's criteria. To simplify the presentation I will assume that the return type of all methods here is void and I will not include the return type in the examples. For a method m(t1 x1, t2 x2, ..., tn xn) where t1 to tn are the n parameter types it is safe to create an overloaded version m(t'1 x1, t'2 x2, ..., t'n xn) if for each type ti (i=1 to n), t'i is not a subtype or supertype of t.
Lets look at a few examples. We will base those examples on the set of classes illustrated here
We will use a one parameter method as our existing method to overload: m(Class-X x1)
The following overloaded versions would be ok:
m(Class-Y x1)
m(Class-Z x1)
The following would not be ok:
m(Class-A x1)
m(Class-d x1)
Had the original method been m(Class-A x1) there would have been no safe way to overload using the types in the diagram.
Had the original method been m(Class-d x1) then the following overloaded versions would have been ok:
m(Class-Y x1)
m(Class-Z x1)
But m(Class-A x1) or m(Class-X x1) would not be safe.
You get the idea.

Saturday, December 24, 2011

Learning from experience

Since my last post I have had several occasions of using my NullObjectProxy class in practice. I learned a lot from that. The first thing I realized was that I needed to allow defining behavior for the Object class methods (hashCode, equals, toString). Used in the confined environment of unit tests this was not obvious but used in real code it really became evident that this was needed. In fact I decided that I needed to provide a default coherent behavior for those methods.
I also realized that I needed to provide a more sophisticated method of defining return value even for a Null object.
The result of all this was that I modified my initial code quite a bit. So in my next post I am going to start over on the NullObjectProxy and used the updated more sophisticated version of this class.