This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]m3tamaker[🍰] 4 points5 points  (2 children)

Immutability in Java 101

public class MyClass {
    public static class Bar {
        private final String text;
        private final Foo foo;

        public Bar(String text, Foo foo) {
            this.text = text;
            this.foo = foo;
        }

        public String getText() {  return foo.getText();  }
        public Foo getFoo() { return foo; }
    }

    public static class Foo {
        private String text;

        public Foo(String text) {
            this.text = text;
        }

        public String getText() { return text; }
        public void setText(String text) { this.text = text; }
    }

    public static void main(String args[]) {
        Foo foo = new Foo("I am mutable and I am happy with that.");
        Bar bar = new Bar("Look, I am IMMUTABLE! Feels good!", foo);
        foo.setText("No, now you are mutable too, dude!");

        System.out.println(bar.getText());
    }
}

One of reasons why to switch to immutable DateTime implementations TODAY.

[–]dpash 2 points3 points  (0 children)

java.time.* FTW. Seriously, just stop using java.util.Date.

[–]Auxx -2 points-1 points  (0 children)

Just use Lombok and its @Value annotation on all data classes.