views:

423

answers:

6

I have implemented a few Java applications now, only desktop applications so far. I prefer to use immutable objects for passing the data around in the application instead of using objects with mutators (setters and getters), also called JavaBeans.

But in the Java world, it seems to be much more common to use JavaBeans, and I can't understand why I should use them instead. Personally the code looks better if it only deals with immutable objects instead of mutate the state all the time.

Immutable objects are also recommended in Item 15: Minimize mutability, Effective Java 2ed.

If I have an object Person implemented as a JavaBean it would look like:

public class Person {
    private String name;
    private Place birthPlace;

    public Person() {}

    public setName(String name) {
        this.name = name;
    }

    public setBirthPlace(Place birthPlace) {
        this.birthPlace = birthPlace;
    }

    public String getName() {
        return name;
    }

    public Place getBirthPlace() {
        return birthPlace;
    }
}

And the same Person implemented as an immutable object:

public class Person {
    private final String name;
    private final Place birthPlace;

    public Person(String name, Place birthPlace) {
        this.name = name;
        this.birthPlace = birthPlace;
    }

    public String getName() {
        return name;
    }

    public Place getBirthPlace() {
        return birthPlace;
    }
}

Or closer to an struct in C:

public class Person {
    public final String name;
    public final Place birthPlace;

    public Person(String name, Place birthPlace) {
        this.name = name;
        this.birthPlace = birthPlace;
    }
}

I could also have getters in the immutable object to hide the implementation details. But since I only use it as a struct I prefer to skip the "getters", and keep it simple.

Simply, I don't understand why it's better to use JavaBeans, or if I can and should keep going with my immutable POJOs?

Many of the Java libraries seem to have better support for JavaBeans, but maybe more support for immutable POJOs gets more popular over time?

+4  A: 

I don't think immutable objects will get all that popular, to be honest.

I do see the advantages, but frameworks like Hibernate and Spring are currently very much in vogue (and for a good reason too), and they really work best with beans.

So I don't think immutability is bad, but it would certainly limit your integration options with current frameworks.

EDIT The comments prompt me to clarify my answer a bit.

There most certainly are problem areas where immutability is very useful, and is indeed used. But I think the current default seems to be mutable as that is what is mostly expected, and only immutable if that has a clear advantage.

And though it is indeed possible to use constructors with arguments in Spring it seems to be intended as a way to use legacy and/or third party code with you beautiful brand-new Spring code. At least that's what I picked up from the documentation.

extraneon
The idea of IoC/DI is based on setting/injecting state, this is why immutability is not so popular in Spring. However Joda-Time is a good example of immutability done right.
lunohodov
You can use constructor args to inject dependencies with spring as well, it just seems that not many people do that (possibly because when you have a lot of dependencies, having a 10+ parameter constructor is scary).
Andrei Fierbinteanu
@lunohodov: I have used Google Guice for DI/IoC and there is no problem to do dependency injection to the constructor.
Jonas
+3  A: 

Well it depends on what your trying to do. If your working with a persistent layer, and you fetch some row from the database into a POJO, and you want to change a property and save it back, using JavaBean style would be better, especially if you have a lot of properties.

Consider that your person, has a lot of fields like, first, middle, last name, date of birth, family members, education, job, salary etc.

And that Person happens to be a female that just got married and accepted to have her last name changed, and you need to update the database.

If you're using immutable POJO, you fetch a Person object representing her, then you create a new Person object to which you pass all the properties that you didn't change as they are, and the new last name, and save it.

If it were a Java bean you can just do setLastName() and save it.

It's 'Minimize mutability' not 'never use mutable objects'. Some situations work better with mutable objects, it's really your job to decide if making an object mutable will better fit your program or not. You shouldn't always say 'must use immutable objects', instead see how many classes you can make immutable before you start hurting yourself.

Andrei Fierbinteanu
+20  A: 

Prefer JavaBeans When

  • you have to interact with environments that expect them
  • you have lots of properties for which it would be inconvenient to do all initialization on instantiation
  • you have state that is expensive or impossible to copy for some reason but requires mutation
  • you think at some point you may have to change how properties are accessed (e.g. moving from stored to calculated values, access authorization, etc.)
  • you want to conform to coding standards that mindlessly insist it is somehow more "object-oriented" to use JavaBeans

Prefer Immutable POJOs When

  • you have a small number of simple properties
  • you do not have to interact with environments assuming JavaBean conventions
  • it is easy (or at the very least possible) to copy state when cloning your object
  • you don't ever plan on cloning the object at all
  • you're pretty sure that you don't ever have to modify how properties are accessed as above
  • you don't mind listening to whining (or sneering) about how your code isn't sufficiently "object-oriented"
JUST MY correct OPINION
+1 for the listing, and almost -1 for your name :) After all, everyone knows it's *my* opinion which is correct. Everyone being defined in a Discworld sense of course.
extraneon
Bounds checking and input validation can be done in the constructor. If the input is invalid or out of bound, I don't want to create an object.
Jonas
It's a fair cop, Jonas. I'll edit the answer.
JUST MY correct OPINION
Your second point in beans is not in favour of beans, but in favour of the Builder pattern. You can still construct an immutable object.
Graham Lee
A: 

Immutable Objects, when used like in your example, are likely to lead you to an antipattern known as "Functional decomposition". Because what you are creating here are "dumb structs" without any behaviour, so the behaviour goes somewhere else.

ammoQ
Interesting point. Anyway, normal Java Beans are dumb too so behaviour goes somewhere else, too. The diference between readonly-JavaBeans and mutable-JavaBeans stresses the "I can copy by reference" argument (I can prove internal data stability without the overhead of deep-copy).
helios
I use my immutable objects to pass data, maybe `Person` was a bad example. One example where I use it is `Item` in a shop. So it's similar to JavaBeans. But I can have immutable objects with behaviuor to. A good example is `BigDecimal`.
Jonas
The difference to BigDecimal is that BigDecimal has only private fields (and static constants), whereas you expose immutable fields.
ammoQ
When you expose fields, subclasses or future versions of the class cannot change anything about that, whereas getters could, e.g. be replaced by calculations or other retrieval methods.
ammoQ
I have updated my question with an example that has getters now.
Jonas
IMO the version with Getters is perfectly OK. You should be aware that the object is immutable only if all fields are immutable. E.g. if you replace those Strings with StringBuilders (just an example, nothing any sane person would ever do) than those StringBuilder can of course change their values.
ammoQ
+8  A: 

I was surprised that the word Thread did not appear anywhere in this discussion.

One of the main benefits of immutable classes is that they are inherently more thread safe due to no mutable, shared state.

Not only does this make your coding easier, it'll also give you two performance benefits as a side effect:

  • Less need for synchronization.

  • More scope for using final variables, which can facilitate subsequent compiler optimisations.

I am really trying to move towards immutable objects rather than JavaBean style classes. Exposing the guts of objects via getters and setters should probably not be the default choice.

[...] to move towards **immutable** objects [...]?
Willi
+4  A: 

Summarizing other answers I think that:

  • Inmutability facilitates correctness (structs can be passed by reference and you know nothing will be destroyed by a faulty/malicious client) and code simplicity
  • Mutability facilitates homogeneity: Spring and other frameworks create an object with no arguments, set object properties, and voi là. Also make interfaces easier using the same class for giving data and saving modifications (you don't need get(id): Client and save(MutableClient), being MutableClient some descendant of Client.

If there were an intermediate point (create, set properties, make inmutable) maybe frameworks would encourage more an inmutable approach.

Anyway I suggest thinking in inmutable objects as "read only Java Beans" stressing the point that if you are a good boy and don't touch that dangerous setProperty method all will be fine.

helios