Over a million developers have joined DZone.

Diving Deeper Into the Java Transient Modifier

In this post we take a closer look at Java's transient modifier to see how it's used and why it should be used. Read on for more information.

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Nothing is tied forever. Neither are transient variables.

Last week, I published an article to help you understand how references work in Java. It was well-received, and I got a lot of constructive feedback. That is why I love the software community.

Today, I want to present you another article diving into a topic that it is not widely talked about: the transient modifier. Personally, when I started using it, I recall that I was able to quickly grasp the theoretical aspect of it, but applying was a different problem. Let's take a closer look:

A transient modifier applied to a field tells Java that this attribute should be excluded when the object is being serialized. When the object is being deserialized, the field will be initialized with its default value (this will typically be a null value for a reference type, or zero/ false if the object is a primitive type).

You very well might agree with me: The theory is easy, but we initially fail to see the practical aspect. Where should we apply a transient modifier? When will it be useful? It's hard to come up with a good example unless you have used it before. Like a dog chasing its tail, we fail to find a use case and therefore cannot apply practice to the theory.

My intention with this article is to help you break this vicious cycle. Let's check a few practical examples.

Think of a User object. This User contains, among all its properties, login, email, and password. When the data is being serialized and transmitted through the network, we can think of a few security reasons why we would not like to send the field password together with the entire object. In this case, marking the field as transient will solve this security problem. How would this look in code?

@Data    
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

    private static final long serialVersionUID = 123456789L;

    private String login;
    private String email;
    private transient String password;

    public void printInfo() {
        System.out.println("Login is: " + login);
        System.out.println("Email is: " + email);
        System.out.println("Password is: " + password);
    }
}

Note that this object is implementing the Interface Serializable, which is compulsory when you intend to serialize an object. If this interface is not implemented, you will receive a NotSerializableException. Note as well the declared field serialVersionUID. If you use any of the major Development Environments or Eclipse, it will generally be recreated automatically.

Now, if you serialize and then deserialize an object of type User, the value password will be null afterwards because it has been marked as transient.

See the annotations @Data, @NoArgsConstructor and @AllArgsConstructor? They are provided by Lombok, a Java library that makes things easier. Although in 2016 Lombok is not as useful as it was before (now languages like Kotlin generate setters and getters automatically, and you can do it with two clicks in any major Development Environment and Eclipse) I still like to use it in certain domains to keep a clean collection of Domain Models.

There is another use case I can think of when using transient modifiers: when an object is being derived from another. In that case, we can make our code more efficient by making the derived field transient.

Let's take a look at this piece of code:

@Data    
@NoArgsConstructor
@AllArgsConstructor
public class GalleryImage implements Serializable {
    private static final long serialVersionUID = 123456789L;

    private Image image;
    private transient Image thumbnailImage;

    private void generateThumbnail() {
        // This method will derive the thumbnail from the main image
    }

    private void readObject(ObjectInputStream inputStream)
            throws IOException, ClassNotFoundException {
        inputStream.defaultReadObject();
        generateThumbnail();
    }    
}
    private static final long serialVersionUID = 123456789L;

    private Image image;
    private transient Image thumbnailImage;

    private void generateThumbnail() {
        // This method will derive the thumbnail from the main image
    }

    private void readObject(ObjectInputStream inputStream)
            throws IOException, ClassNotFoundException {
        inputStream.defaultReadObject();
        generateThumbnail();
    }    
}
    private static final long serialVersionUID = 123456789L;

    private Image image;
    private transient Image thumbnailImage;

    private void generateThumbnail() {
        // This method will derive the thumbnail from the main image
    }

    private void readObject(ObjectInputStream inputStream)
            throws IOException, ClassNotFoundException {
        inputStream.defaultReadObject();
        generateThumbnail();
    }    
}

In summary: Use transient when an object contains sensitive data that you do not want to transmit, or when it contains data that you can derive from other elements. Static fields are implicitly transient.

I write my thoughts about Software Engineering and life in general on my Twitter account. If you have liked this article or it did help you, feel free to share and/or leave a comment. This is the currency that fuels amateur writers.

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
java ,transient ,modifier

Published at DZone with permission of Enrique Lopez Manas, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}