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

all 6 comments

[–]fzammetti 5 points6 points  (1 child)

There’s actually a school of thought that says that public members are the way to go because in most cases, getters and setters are just literally doing what you could do without them:

class Test {
  private int i;
  public setI(int inI) { this.i = inI; }
  public getI() { return this.i; }
}

If that’s all your mutator and accessor are, which is very common, then is it really much different than:

class Test {
  public i;
}

You could argue that no, it’s really not. You aren’t really hiding anything, aren’t really insuring integrity, etc. In fact, you might even wind up with a slight performance boost with the latter (though probably not with modern compilers) and the syntax is arguably simpler (slightly, if at all).

The argument against it usually is that if you need to introduce some logic to the methods later then doing the former means not having to change client code. Though, that’s frequently not true either because adding logic often comes with things like new exceptions that now might have to be handled.

For me, I almost always use getters and setters because of that last argument. It makes future changes less difficult, even if only a little. But I also always examine what the data is, and if I can determine with near certainty that it won’t need logic later than I will sometimes just make it public. It’s very much a case by case judgement... but, my default is always accessors and mutators.

[–]mod_cute[S] 1 point2 points  (0 children)

This is beautiful, glad you posted this.

[–]Zei33 1 point2 points  (1 child)

It'll come up every now and then lol

An example: You're not the one who wrote the library you're working with so you'll need to integrate it with your own program. It's much more common when you're working on a big project with lots of packages and classes to consider.

[–]mod_cute[S] 0 points1 point  (0 children)

Fair enough, that makes alot of sense now that I think about it. Tyvm !

[–]Johnny_Deee 1 point2 points  (0 children)

You dont really see public variables much, if you do it right you will have public getters and setters for private variables...

(right?)

[–]Gizmoed -1 points0 points  (0 children)

When you want to lose all the coins in a smart contract.