Friday, July 6, 2012

Four interesting questions - Part I

This series of posts discusses about four interesting IT technical questions, that I have come across. For some of you these will be not so interesting but for me they have all have a significance. When I first came across them, all of a sudden and needed to solve them (with out the aid of Internet). But later when doing general reading I found interesting further explanations.

01. What should a constructor of a immutable Java class do when it receives a reference argument (another object)? (The question was not that direct it contained a small code segment. This was a interview question.)

First a bit of background. A immutable object is a object that cannot be modified after it is created. A class defining such a class is a immutable class. Why do we need to create immutable objects in first place? Is there a valid reason for it. Such a object is costly, and we need to recreate if it needs a change. But immutable classes offer certain advantages over mutable ones the main one being the ease in how we can handle synchronization in multi threaded programs.

The point here is if we strait away assign the reference into a internal variable it leads to potential problems. If the passed object is not immutable, and we change it (this is possible since we have a reference for it) the compound object is changed. So we should consider creating a private copy for the object of such references so that we can be sure that we had not leaked a reference out.

It sounds simple, but this is not the only point we can get wrong. There are a good number of pitfalls when writing immutable classes. (Making every thing member private and final, not exposing mutator methods, stop inheriting from the class.. etc) This really applies to library quality code and if you really care about your code quality. A respected authority in Java, Joshua Bloch has dedicated a section in his famous book Effective Java on writing such classes (Item 15).

No comments:

Post a Comment