Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy shouldn't I use immutable POJOs instead of JavaBeans?
    primarykey
    data
    text
    <p>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 <em>and getters</em>), also called JavaBeans.</p> <p>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. </p> <p>Immutable objects are also recommended in <strong>Item 15: Minimize mutability</strong>, <em>Effective Java 2ed</em>.</p> <p>If I have an object <code>Person</code> implemented as a <strong>JavaBean</strong> it would look like:</p> <pre><code>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; } } </code></pre> <p>And the same <code>Person</code> implemented as an <strong>immutable</strong> object:</p> <pre><code>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; } } </code></pre> <p>Or closer to an <code>struct</code> in C:</p> <pre><code>public class Person { public final String name; public final Place birthPlace; public Person(String name, Place birthPlace) { this.name = name; this.birthPlace = birthPlace; } } </code></pre> <p>I could also have getters in the immutable object to hide the implementation details. But since I only use it as a <code>struct</code> I prefer to skip the "getters", and keep it simple.</p> <p>Simply, I don't understand why it's better to use JavaBeans, or if I can and should keep going with my immutable POJOs?</p> <p>Many of the Java libraries seem to have better support for JavaBeans, but maybe more support for immutable POJOs gets more popular over time?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload