programing

JavaBeans 대신 변경 불가능한 POJO를 사용하면 안되는 이유는 무엇입니까?

nasanasas 2020. 10. 12. 07:36
반응형

JavaBeans 대신 변경 불가능한 POJO를 사용하면 안되는 이유는 무엇입니까?


지금까지 몇 가지 Java 응용 프로그램을 구현했지만 지금까지는 데스크톱 응용 프로그램 만 구현했습니다. 나는 JavaBeans라고도 불리는 뮤 테이터 (setters 와 getter )가있는 객체를 사용하는 대신 애플리케이션에서 데이터를 전달하기 위해 불변 객체를 사용하는 것을 선호합니다 .

그러나 Java 세계에서는 JavaBeans를 사용하는 것이 훨씬 더 일반적으로 보이며 대신 JavaBeans를 사용해야하는 이유를 이해할 수 없습니다. 개인적으로 코드는 항상 상태를 변경하는 대신 변경 불가능한 객체 만 처리하면 더 좋아 보입니다.

불변 객체는 Item 15 : Minimize mutability , Effective Java 2ed 에서도 권장됩니다 .

JavaBean으로Person 구현 된 객체가 있으면 다음과 같습니다.

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;
    }
}

불변 객체 Person로 구현 된 것과 동일 합니다.

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;
    }
}

또는 structin C :

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

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

구현 세부 정보를 숨기기 위해 변경 불가능한 개체에 게터를 사용할 수도 있습니다. 그러나 나는 그것을 단지로만 사용하기 때문에 나는 struct"getters"를 건너 뛰고 그것을 단순하게 유지 하는 것을 선호한다.

간단히 말해서, JavaBeans를 사용하는 것이 더 좋은 이유를 이해하지 못합니다. 아니면 변경 불가능한 POJO를 계속 사용할 수 있고 계속 사용해야하는지 이해하지 못합니다.

많은 Java 라이브러리가 JavaBeans를 더 잘 지원하는 것처럼 보이지만 변경 불가능한 POJO에 대한 더 많은 지원이 시간이 지남에 따라 더 인기를 얻게 될까요?


다음과 같은 경우 JavaBeans 선호

  • 기대하는 환경과 상호 작용해야합니다.
  • 인스턴스화에서 모든 초기화를 수행하는 것이 불편할 수있는 속성이 많습니다.
  • 어떤 이유로 든 복사하기가 비싸거나 불가능하지만 변형이 필요한 상태가 있습니다.
  • 어떤 시점에서 속성에 액세스하는 방법을 변경해야한다고 생각합니다 (예 : 저장된 값에서 계산 된 값으로 이동, 액세스 권한 부여 등).
  • JavaBeans를 사용하는 것이 "객체 지향적"이라고 생각하지 않고 주장하는 코딩 표준을 따르고 자합니다.

불변 POJO 선호

  • 적은 수의 간단한 속성이 있습니다.
  • JavaBean 규칙을 가정하는 환경과 상호 작용할 필요가 없습니다.
  • 객체를 복제 할 때 상태를 복사하는 것은 쉽습니다 (또는 최소한 가능).
  • 객체를 복제 할 계획이 전혀 없습니다.
  • 위와 같이 속성에 액세스하는 방법을 수정할 필요가 없습니다.
  • you don't mind listening to whining (or sneering) about how your code isn't sufficiently "object-oriented"

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.


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.


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.


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;
    }
}

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.

참고URL : https://stackoverflow.com/questions/3511120/why-shouldnt-i-use-immutable-pojos-instead-of-javabeans

반응형