Should I use accessors for field values ​​that will never change?

Take this class as an example:

public class Student{
    private String name;
    private String id;

    public Student(String name, String id){
        this.name = name;
        this.id = id;
    }

    ... getters and setters for both fields

and compare it with this:

public class Student{
    public final String name;
    public final String id;

    public Student(String name, String id){
        this.name = name;
        this.id = id;
    }
 }

In my opinion, there is no need for accessories.
Would this be considered a poor OO design?

+5
source share
8 answers

This is a busy question.

Unfortunately, a good (or bad) design is 100% dependent on how it will be used.

It is generally recommended that you keep member variables private so that the object model controls their access. This means that the first approach is better.

BUT

if the values ​​never change, what point? Why write screenwriters if they will never be used?

, ? , , . , . , "".

, , , :

public class Student{
    private final String name;
    private final String id;

    public Student(String name, String id){
        this.name = name;
        this.id = id;
    }

  ... getters ONLY for both fields

, , " " . , , - , .

+7

. : , , , .

: immutable .

. .

+6

Getter Setter API . , , . . , API. , . , , , , , . , , . , .

ThePragmaticProgrammer , . http://c2.com/cgi/wiki?AccessorsAreEvil , .

+2

, , , .

, , , .

0

final, /. , .

0

. / , "getters", .

, Student java.util.Date.

public final Date dateOfBirth;

Argh, Student . .

private final Date dateOfBirth;
...
public Date dateOfBirth() {
     return new Date(dateOfBirth.getTime()); // Awful API.
}

, () ( ). , , , . Getters . ( "get" - ( ) Java, , , tell-don't-ask. "get", extra "()" .)

0

, , // , .

. AOP - pointcuts , ( ) AOP -, . , , . Spring :

Spring AOP ( Spring beans). , Spring AOP API. , , AspectJ.

0

I do not think this is a bad idea.

If they are not changed, make sure you mark the fields with the appropriate keywords, for example Final.

It would also be nice to make immutable values ​​differently. for example, constants in Java are usually executed in all caps.

-1
source

All Articles