Friday, 31 October 2014


At work we have taken great care to limit access to a Set of values, as elements of the set have constraints between each other, that need to be sustained.

So any call to retrieve a set, is always done using Collections.unmodifiableSet.

public Set<T> getCycles() 
  return Collections.unmodifiableSet(cycles);

I would have been much more at ease, if we had also decided to make the elements of the set Immutable Objects, but alas, this is the status quo.

As it is right now, it's possible to change the attributes of the individual elements, and so break the constraints between them.


Imagine the surprise of my colleague, when, out of nowhere, he found the following method:
public abstract SortedSet<T> getAsModifableSet();

The typo in the name is actually in the code, I swear! My grasp of the intricacies of spelling is beyond reproach.

And it returns a very implementation-specific Set as well.

And it's public too.

I'm sure there are always good reasons for these things, but sometimes I'd like to run my head into a wall.

Sunday, 26 October 2014

Covariant return type

“In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass.”

Since JDK 5.0 it is possible to provide covariant return types in methods of subclasses.[2] Before this release, the Java programming language was invariant with regard to method return types.

Unfortunately, covariance is not possible with method parameters. If you wish to use that, reference [1] has a good explanation of how to do this using Generics.



In Scala all three are possible, contravariant, covariant and invariant for both method parameters as well as method return types. It is used fairly frequently.

For more information, the blog in [3] has some excellent explanation.


[1] Covariant Parameter Types
[2] Wikipedia - Covariant return type
[3] Atlassian Blogs - Covariance and Contravariance in Scala