Dragonborn
Dragonborn

Reputation: 1815

Should we define getters setters in most of the cases?

If I don't need to do any checks (during getters) or update something else (during setters), then having a simple public member variable should suffice?

Upvotes: 0

Views: 96

Answers (4)

Onilton Maciel
Onilton Maciel

Reputation: 3699

Notice that in scala this problem doesn't exist, since scala autogenerates getter and setter methods for you:

class Person(var name: String)

val p = new Person("Jonh")
p.name = "James"
println(p.name)             // James

Then, if you need you override the default default accessors and mutators:

class Person(private var _name: String) {
  def name = _name
  def name_=(aName: String) { _name = aName }
}

Still works:

val p2 = new Person2("Jonh")
p.name = "James"
println(p.name)             // James

This answer has a explanation on a similar (not equivalent) concept in other languages (C#, Python,...) where you can have a property: a pair of methods (getter and/or a setter).

As Elliott pointed out, when you have immutability in your class, setters doesn't make sense. And even in languages like Java, you could write a getter, but I can say you usually can get away with final public attributes since you can change their value through the constructor, although I would not exactly call it "the Java way" (lol) :

class Person {
  public final int age;

  public Person(int theage) {
    // Let's transforme age here
    // Imagine this could would go in the getter
    age = theage * 2;
  }
}

Upvotes: 1

User2709
User2709

Reputation: 573

As long as possible, you should avoid setters, and even getters when you are dealing with references. Immutability should always be preferred unless it cannot be done for some particular reason. In Java, I personally prefer to have getters even if I am not doing any check there, it just gives a bit more control.

Upvotes: 3

Mr Redstoner
Mr Redstoner

Reputation: 488

if you are doing something simple, public is the most practical.

As mentioned by Jameson, sometimes you only need getter or only setter ( String.getCharAt() and such...).

If you are doing a big project, you should do them at least for safety checks (Jameson again). Also it makes you look smart using them on correct places, but that really depends on what you do, share a piece of code maybe?

Upvotes: 0

Jameson
Jameson

Reputation: 6659

If you don't need to check the value or update it, make it private, and don't provide any other access.

My personal philosophy is to expose access functions only when they are needed, and then, not necessarily to provide set and get in a pair, even.

getters and setters are good when you need safety checks for incoming values or under what conditions the variable is read.

They are bad when you have a simple object with lots of primitives that just need a place to be bundled together. In those cases I would prefer public members.

Upvotes: 1

Related Questions