Friday, 31 October 2014

getAsModifableSet()

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.

Surprise

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.

Example

Scala

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.

References

[1] Covariant Parameter Types
http://www.java-tips.org/java-se-tips/java.lang/covariant-parameter-types-2.html
[2] Wikipedia - Covariant return type
http://en.wikipedia.org/wiki/Covariant_return_type
[3] Atlassian Blogs - Covariance and Contravariance in Scala
http://blogs.atlassian.com/2013/01/covariance-and-contravariance-in-scala/