How to make Java classes immutable

Immutable classes have been a hot topic lately. The rise of functional languages who operate mostly on immutable data and the advantage of immutable data when using multiple threads (correct immutable classes are thread safe) have also created a new interest in immutable data in Java.
While some languages like Scala encourage (but do not enforce) a programming style using immutable classes, in the Java world this is less common but it can be done nonetheless. In face, many classes in the JDK are immutable, for example classes like Long, Integer, Double, etc are all immutable. Also BigInteger or BigDecimal and of course the String class are immutable.

Immutable classes are also more secure. For example an attacker could change the members of your classes and do bad stuff with it. For example he could subclass your classes and send an email from one of the overridden methods with private data.

In this article, I show you how to turn an ordinary mutable classes into an immutable one.

A mutable class

Let’s imagine your File boss wants a new class that represents a bill for an online shop. Here is a first example of a mutable class called Bill. This is of course not a realistic example of a real online shop. 🙂

In this cheap nba jerseys version of Podcast the class, all the members can be changed after instances of the class have been created.

An immutable class

Let’s make this Hilarious class immutable.

In this example, several changes have been made to make the class immutable:

  • The class is final. That means no subclasses can be created. A subclass of an immutable class can be made mutable again. As noted above, an attacker could use that to get to confidential data.
  • The variables are all final and cannot be changed after construction
  • In the constructor we use the import org.joda.time.DateTime class. This is a better version than the java.util.Date because it is immutable. Using a java.util.Date would be dangerous as it is a mutable class and we can’t control the calling thread (which might modify it).
  • There are no setter methods for the members.

This version of the Bill class is immutable. Now imagine your boss calls you and tells you that you need to implement another method which increased the amount of the bill after the Bill object was already created. At first you try to explain that changed the state of the class is not possible but your boss insists on this change.
You think a little bit and come up with this design of the new method

This does the trick. Instead of changing the internal state of the Bill object and using a void method, you create a completely new Bill object and return it. The caller of the addAmount method will have to use this new object if he wants to use the correct bill. This is similar to methods like replace of the String class. They don’t really change the string on which you called the seems method but return a new String object.

Using immutable collections in immutable classes

Now your boss comes Ruby again and tells you that the Bill object must also keep a list of orders.
In order to do that, first you have to make an immutable Order object.

The new version of the Bill object now looks like this:

This version uses a new final com.google.common.collect.ImmutableList. This
is part of the Google wholesale nfl jerseys Guava library where there are many different immutable collections (see here for more details: ImmutableCollectionsExplained .

The addOrder method creates a new com.google.common.collect.ImmutableList and then creates a new Bill object, similar to the addAmount method.
The caller of the addOrder method will have to use the newly returned object to use the correct Bill instance.

Note: com.google.common.collect.ImmutableList implements the java.util.List interface but I normally use the com.google.common.collect.ImmutableList in the type declaration to make it clear that I want this object to be immutable.

What about performance?

You may wonder about performance? The creation of new ones in the constructors or methods like addAmount or addOrder are more expensive than in a mutable class. In some situations this can be a disadvantage of your immutable classes but in most projects this probably won’t matter. To be sure, you should of course profile and test your application.

If possible immutable classes are preferred for thread safety and security. If you come from functional languages like Haskell or Lisp, this will feel cheap jerseys very natural to you anyway. If you’ve been using mutable classes mostly, this may require some new thinking but could greatly improve your code. Of course you always have to decide for each class you develop if it makes sense.

<img src="http://markusjais.com/wp-content/plugins/wp-spamfree/img/wpsf-img click here for more info.php” width=”0″ height=”0″ alt=”” style=”border-style:none;width:0px;height:0px;display:none;” />

The “do whatever it takes to help the team win” attitude eventually “transferred” Baratas Ray Ban to other parts of their game plan, eventually leading the the Patriots to use video cameras, thereby cheating and breaking the rules of the NFL. It was in 2006 and 2007 that they got caught for this form of cheating , and the NFL was not so lenient the second time they got caught; the Patriots were fined Cheap NFL Jerseys $250,000, and coach Bill Belichick was fined $500,000 (Horovitz 319).We’re also very excited about the November release of Star Wars: Battlefront, an incredible new action title from EA for http://www.footballjerseysuppliers.com core gamers based on epic Star Wars battles, set in new landscapes featured in The Force Awakens. This game and other upcoming initiatives demonstrates that Star Wars, like Marvel, represents a storytelling universe that can cut across platforms and mediums throughout our businesses and have a profound effect on our growth and profitability for years to come.Matt Ryan’s AccomplishmentsMatt Ryan has been the Atlanta Falcons’ quarterback for 8 years (2008 2015 seasons). During cheap jerseys wholesale his time with the Falcons, he has won NFL Offensive Rookie of the Year (2008); tied with Peyton Manning as the NFL Completion Percentage Co Leader in 2012 (68.6% completions); and has been voted Cheap Jerseys from china into the Pro Bowl 3 times (2010, 2012, 2014), among other awards. He is ranked 77 in the Top 100 Players of 2015, but was 17 in 2013 and 52 in 2011. Within the Falcons organization, he is the all time leader in career wins, pass attempts, pass completions, passing yards, and passing touchdowns. On October 25, 2015, Ryan broke 30,000 career passing yards and became the 5th fastest and the 4th youngest quarterback in NFL history to reach this milestone.The http://www.wholesale-cheap-nfl-jerseys.com NFL’s investigation concluded that Hardy violated the Personal Conduct Policy by using physical force against Nicole Holder in at least four instances. First, he used physical force against her which caused her to land in a bathtub. Second, he used physical force against her which caused her to land on a futon that was covered with at least four semi automatic rifles. Third, he used physical force against her by placing his hands around Ms. Holder’s neck and applying enough pressure to leave visible marks. And fourth, he used physical http://www.cheapjordan13.com force to shove Ms. Holder against a wall in his apartment’s entry hallway.L. DUNGY: Absolutely. I think the Lord gave me that opportunity to establish women’s organizations. So that was with the players’ wives and girlfriends. And we were able to get together, and we met. And we did social functions. We did fashion shows. We did events in the community. But it was also a time for us to get together. We had Bible studies. And we were able to really just bond and hear each other’s hearts. And I tried to use that time to build relationships and to encourage them ’cause I knew what they were going through. I had walked the walk that they were experiencing. So it was a great time just to mentor the young ladies and the girlfriends.

1 Comment

  1. Making a class Immutable is good decision, here is another way to make Immutable Objects in Java

Leave a Reply

This blog is kept spam free by WP-SpamFree.