(no title)
Proleps | 11 years ago
public final class Article{
public final String title;
public final String author;
public final List<String> tags;
public Article(String title, String author, List<String> tags) {
this.title = title;
this.author = author;
this.tags = tags;
}
}
Getters don't seem very useful on an immutable object.
organsnyder|11 years ago
For instance, let's say that you don't want to store the author's name as a string anymore, and want to store a reference to an Author object. If you have a getAuthor() method, you can change it from a simple getter to instead call author.getName(), preserving your public-facing API.
TheLoneWolfling|11 years ago
And their justification fails. Sure, currently if you read x.foo you know that no code is being executed - but you never see x.foo because everything has getters and setters. So all it does in practice is make things (even) more verbose.
virmundi|11 years ago
I'm sure that library/framework people need to worry about that. Most normal developers do not. For many cases Java objects like Article are just structs. They are static maps. Sure, in the example on the site there was a getTags that added some logic, but still, pretty much a struct.
Switching to either public accessor for mutable or immutable objects actually will stream line code. You might say that public mutators are bad; encapsulation and all that. For the most part little is actually gained in the majority of getter/setter code to necessitate their weight.
Heck, as per the JavaBean spec (a spec for making components to create drag and drop UIs by the way), you can't even have fluent APIs where the setter returns "this". It has to be void.
API stability has value. If you're a library, you probably want to do this just to be safe. But really for most imperative Java code it's just a lot of fluff for little value.
V-2|11 years ago
It would be nice to have some syntax sugar for defining properties more tersely though, like in C#.
thescrewdriver|11 years ago
Proleps|11 years ago
Then it wouldn't be immutable, if I can change the implementation I can also create a mutable version.
Edit example
thescrewdriver|11 years ago
Scala version of your code:
V-2|11 years ago
Properly implemented getTags should create a copy of tags so that fiddling with the returned value doesn't affect the object.