Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to convert ordinary mutable classes into an immutable one with Java

This tutorial will teach you the aspects to convert mutable java classes into immutable one with a real time based example.

Majority of the classes in the JDK are immutable. Example includes classes like Long, Integer, Double, and etc is all immutable. This also includes BigInteger or BigDecimal and String class.

As far as the immutable classes are concerned, they are considered to be very secure. For instance, an attacker could alter or play with the the members of your classes and do some undesired stuff with it. He could in fact subclass your classes and sends an email from one of the overridden methods with confidential data.

With the help of this article, we will try to gain the knowledge on how we can turn an ordinary mutable class into an immutable one.

A mutable class

Let us understand the entire process by a real time example. Assume that your boss comes at you and requests for a new class that corresponds to a bill for an online shop. The below code represent first example of a mutable class called Bill.

Listing 1: first example of a mutable class

import java.util.Date;
 
public class Bill {
     
    private int amount;
    private Date date;
 
    public Bill(int amount, Date date) {
        this.amount = amount;
        this.date = date;
    }
 
    public int getAmount() {
        return amount;
    }
 
    public void setAmount(int amount) {
        this.amount = amount;
    }
 
    public Date getDate() {
        return date;
    }
 
    public void setDate(Date date) {
        this.date = date;
    }
}

Now, all the members can be altered after instances of the class have been created.

An immutable class

We will make this class immutable now.

Listing 2: Immutable class

import org.joda.time.DateTime;
 
public final class Bill {
      
    private final int amount;
    private final DateTime dateTime;
  
    public Bill(int amount, DateTime dateTime) {
        this.amount = amount;
        this.dateTime = dateTime;
    }
  
    public int getAmount() {
        return amount;
    }
  
    public DateTime getDateTime() {
        return dateTime;
    }
}

We have incorporated a good number of changes in this example so as to make the class immutable:

  • The class is final and means that means no subclasses can be generated. We can again mutable a subclass of an immutable class. As can be seen above, the attacker could make use of it in order to obtain the confidential data.
  • The variables are all final and cannot be modified after construction
  • In the constructor we have used the import org.joda.time.DateTime class. This is immutable thereby making it a better version than the java.util.Date. Making use of a java.util.Date is not preferred for the reason that it is a mutable class and it is not possible to control the calling thread that may end up in modifying it.
  • There are no setter methods for the members.

This version of the Bill class is immutable. Let us assume now that your boss tells you that there is a need to come up with one more method that increased the amount of the bill post the Bill object was already created. Your boss is insisting to make this change even though you have tried a good number of times to convince him that this will going to be a close to impossible task.

Listing 3: Bill class immutable

public Bill addAmount(int amount) {
       return new Bill(this.amount + amount, dateTime));
}

We create an entirely new Bill object and return it instead of changing the internal state of the Bill objects and make use of a void method. In order to utilize the correct bill, the caller of the addAmount method will have to use this new object. This is nothing but a similar method to methods like replace of the String class. They don’t really alter the string on which you called the method, in fact return a new String object.

Utilizing immutable collections in immutable classes

Assume your boss is in again and inform you that the Bill object must also keep a list of orders. So, In order to do that, the first step would be to make an immutable Order object.

Listing 4: Making an immutable Order object

public final class Order {
     
    private final int id;
 
    public Order(int id) {
        this.id = id;
    }
 
    public int getId() {
        return id;
    }
}

Listing 5 : new version of the Bill object:

import org.joda.time.DateTime;
 
import com.google.common.collect.ImmutableList;
 
public final class Bill {
 
    private final int amount;
    private final DateTime dateTime;
    private final ImmutableList<Order> orders;
 
    public Bill(int amount, DateTime dateTime, ImmutableList<Order> orders) {
        this.amount = amount;
        this.dateTime = dateTime;
        this.orders = orders;
    }
 
    public ImmutableList<Order> getOrders() {
        return orders;
    }
 
    public int getAmount() {
        return amount;
    }
 
    public DateTime getDateTime() {
        return dateTime;
    }
 
    public Bill addAmount(int amount) {
        return new Bill(this.amount + amount, dateTime, orders);
    }
 
    public Bill addOrder(Order newOrder) {
        ImmutableList<Order> newOrderList = new ImmutableList.Builder<Order>()
                .addAll(orders).add(newOrder).build();
            return new Bill(this.amount, dateTime, newOrderList);
    }
}

The addOrder method generates a new com.google.common.collect.ImmutableList and the next step will be to create a new Bill object that would be similar to the addAmount method. The caller of the addOrder method will have to make use of the newly returned object so as to utilize the correct Bill instance.

Word of Caution: com.google.common.collect.ImmutableList executes the java.util.List interface however we have used the com.google.common.collect.ImmutableList in the type declaration to make it clear that we want this object to be immutable.

What about performance?

You may be thinking about the performance. The generation of fresh ones in the methods such as addAmount or addOrder is rather more expensive than in a mutable class. In some conditions, this seems to be a disadvantage of your immutable classes. However in majority of the projects, this won’t be making any difference. To get certain on this, it is required to profile and test your application.

Conclusion

The article was oriented to explain on the process to turn ordinary mutable java classes into a immutable class. We took the example of a real based scenario and hope you liked the same.

I hope you liked the article, see you next time.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login