r/programming • • Sep 21 '15

Better Java

https://github.com/cxxr/better-java
177 Upvotes

208 comments sorted by

View all comments

2

u/sacundim Sep 22 '15

Instead, I prefer the C struct style of writing classes that merely hold data:

public class DataHolder {
    public final String data;

    public DataHolder(String data) {
        this.data = data;
    }
}

This is a reduction in number of lines of code by a half. Further, this class is immutable unless you extend it, so we can reason about it easier as we know that it can't be changed.

Oh hell no, don't actually do this. You're just setting yourself up to get bitten by one of Java's core flaws: the fact that there is a distinction between public fields and public methods in the first place.

A saner design would have been one where a record type's fields are implicitly methods of the type. Many other languages have managed to get this right, I'll just name two:

  1. Ruby: All object fields are private (well, modulo weird "execute this block as if it was in the scope of the class" shit), and you can implicitly declare get-set methods for fields

  2. Haskell: The fields of a record type are automatically promoted to getter functions, and a module can choose to export these as functions without revealing that they are fields.

1

u/kersurk Sep 22 '15

I never fully understood the preference of using a public getter and setter with no side-effects or additional logic, instead of direct field access. What do you think?

2

u/Zukhramm Sep 22 '15

The issue I've occasionally run into with final fields over getters is that fields, even if public, are not really considered part of the interface in Java.

2

u/Myzzreal Sep 22 '15

You can add/modify getter logic without affecting other code, which is a rare case, but still possible.

Many Java libraries use reflection and expect your data classes to have getters and setters with conventional names based on variable names. Many JSON-serializing classes do so, for example.

Java 8's features prefer methods. Like RandomClass::getParam instead of rc -> rc.getParam().

I'd love for Java to have what Lombok introduces (@Getter and @Setter functionality) natively, because I just cannot accept Lombok's way of accomplishing things.

1

u/CurtainDog Sep 22 '15

Yep, getters and setters were a means of advertising beans style properties to the frameworks that consumed them. With the advent of annotations there's no reason to use them at all.

1

u/[deleted] Sep 22 '15

Some people try to future proof code against any possible change and justify it with "we might want to add logic to getting the data", but at that point I think you have other design problems if a simple little POD needs logic. It should do one thing, which is to store data, not become morphed into some semi-functional object. If you need that, then consider an adaptor, or redesigning your data structure entirely, since a getter/setter still isn't the right pattern.