Why shouldn't I use immutable POJOs instead of JavaBeans?

前端 未结 7 1324
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 06:27

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

相关标签:
7条回答
  • 2020-12-04 06:48

    Well it depends on what you're 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.

    0 讨论(0)
  • 2020-12-04 06:48

    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.

    0 讨论(0)
  • 2020-12-04 06:55

    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.

    0 讨论(0)
  • 2020-12-04 06:55

    Immutable in terms of programming in Java : Something that once created should never have change of state , both expected or unexpected!

    This technique is useful in defensive programming where another entity cannot induce change in the state.

    Examples where you don't expect change : External systems(single or multi threaded) which gets reference from your layer and operates upon the object and knowingly or unknowingly change it. Now it could be a POJO or an collection or an object reference and you don't expect a change in it or you want to protect the data. You would definitely make the object immutable as defensive technique

    Examples where you expect change : Really don't need immutability as it will obstruct in right programming procedures.

    0 讨论(0)
  • 2020-12-04 06:56

    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"
    0 讨论(0)
  • 2020-12-04 07:06

    From Java 7 you can have immutable beans, the best of both worlds. Use the annotation @ConstructorProperties on your constructor.

    public class Person {
        private final String name;
        private final Place birthPlace;
    
        @ConstructorProperties({"name", "birthPlace"})
        public Person(String name, Place birthPlace) {
            this.name = name;
            this.birthPlace = birthPlace;
        }
    
        public String getName() {
            return name;
        }
    
        public Place getBirthPlace() {
            return birthPlace;
        }
    }
    
    0 讨论(0)
提交回复
热议问题