getters and setters vs public vars

The only exception I have to using setters and getters is when I am able to wholly separate some functionality into the mutable and immutable components. The intent is, in part, to help with concurrency issues. I got the idea from reading about functional programming. But that doesn’t mean I’m implementing it correctly. In this case, the class with the variables only has variables and no functions whatsoever.

I almost always use getters and setters, even for final variables unless they’re static. However, don’t assume using methods for set / get requires you to use JavaBean conventions. Sometimes a fluent API can be more legible and less verbose.

eg. the audio coding API in Praxis LIVE uses setter / getter methods like -


Osc frequency(double hz) {
  // validate value or invalidate cached data !!
  this.hz = hz;
  return this;
}
double frequency() {
  return this.hz;
}

Which allows for code like -


osc.waveform(SAW).frequency(440).gain(0.4);

If you’re doing a lot of updating based on the existing value, you could even override the setter with a method that accepts a function -


osc.frequency(hz -> hz*2);

Thanks for all these points…

That has made me decide that it would be better, on the long term, to implement getters and setters, and refactor what I’m working on… the arguments make sense to prefer get/set over public, in that things will be cleaner.

It is somewhat less intuitive, when it comes to implementing the same logic, and while some classes are easier. it raises a secondary question:

In order to have a collision detection “object”, you would need to pass the parent object at minimum (in order to loop through all objects, NPC’s and the player (on the screen, at least), and cast the objects, and then, doesn’t that somewhat defeat the purpose, because you give one object almost total control over a secondary object??

Somewhat a pain in the arse, but I guess, better to get into this practice now, than in 2 months, where instead of hours of work would be days or weeks worth of work. Luckily, all I’ve really got working is collision detection logic, and player controls… and it turns out that making this conversion will make adding enemies of various types much simpler of a process in the long run.

The bad habits I had picked up with simple games like tetris are apparently haunting me, with a platform game (with polygon objects like terrain, ladders, moving and jump through platforms, and more), that is alot more complex, but I’m already too committed to go back to something simpler…
The changeover requires a different way of thinking about problems, but even since the answers started coming in, and making the effort, it seems that overall its led to less code to accomplish the same amount.

@nsigma :
I think those are called builder classes, I’ve tried to make some of those before I dropped box2d, and with libgdx, that’s how the Vector2 class was made… allows for multiple operations to be performed on single lines of code. Never had much luck making those types of classes myself.

No, they’re not builder classes, although builder classes usually use a similar fluent API (see https://en.wikipedia.org/wiki/Fluent_interface ) Unlike builders, these methods are used to modify an existing object rather than create a new one - they’re still getters and setters. My point was that you don’t have to follow the JavaBean conventions. I use the same principle for animations too -


property.to(5, 0.75).in(3, 1.5).easing(easeIn, easeOut);

Thanks for the correction… I’m still learning, but keep making breakthroughs on getting better working on this project that is well above my skills.

Its like when I was learning trade work when I was younger, the second I became a journeyman, I thought I could just skip all the annoying things my boss made me do. First job in I realized WHY you do all that annoying stuff, and it really does just make things easier longer term.

That looks also similar to the tween engine, which I will likely implement in the near future.

Here let me add on.

public class WindowManager {

private final Window window;

public WindowManager(Window window) {
this.window = window;
}


public Window getWindow() { // manage your object outside of class? or delete this and have WindowManager do it?
return window;
}

}

That depends on what you are making.
If you are making a library I recommend Getters and Setters.
It is not required what’s however.

Using public variables you are writing a little less code.

Performance
It doesn’t really affect the performance, on a really large scale public vars could be faster.

Don’t 100% agree, if you think as methods being actions then you could “rename” your setters to something more meaningful like:



speed.accelerate(10);

speed.brake(5)



That just gives issues, and increases method count, thereby increasing the code size. And on android, there is a limit of 64k methods, it’s just not worth it.

In my opinion, this is actually a very nice way of keeping your code clean and keeping your data encapsulated.
It defines an interface between your class and its users based on methods whose behaviour can be specified/documented and best of all, those methods/behaviour can be “contained” within this class. It is far better than changing variables all over the place (either via direct field accesses or via setters). This is especially crucial if the action of “accelerating” or “braking” contains more actions than just changing a single field. You can then “contain” those actions within a single method which is part of the interface of the class. This is a very good thing indeed!

I didn’t know there was a 64k methods in android? Is there a way to check where you’re at?

That seems a strange way to limit things, because some methods might be 1-2 lines, where other methods are hundreds of lines…

64k is a Java VM spec limitation.

Cas :slight_smile:

well… somehow I doubt I would ever need that much anyway, but good to know.

Its 65k per class file, I think if you are approaching this limit you might want to refactor your code a bit!

This seems appropriate place for a question…

In the setup I have now, I’ve followed the advice on why to remain strict with private / protected members…

So, I now have an “entity” class, that gets implemented as each type of entity; terrain, bullets, player, enemies, etc…

now, I use the entity motion for collision detection and noticed that I have full access to protected members of implemented objects, I did not anticipate that protected would allow this access, where private member access would not allow the sub type to easily use the parent variables.

Is this unusual? Why? and in this situation should I use the getters / setters in spite of this access?

A setter/getter construction ensures that every time the information is accessed, it goes through a single, centralized set of rules established by the instance of the class itself. These rules can even be written to reflect state changes of the class instance which would complicate the coding needed from classes that access these variables.

Also, it allows you to freely change what is behind that wall or api without having to track down every instance in which you access that class from other classes. Suppose you do something simple like change from doubles to ints or vice versa. The setter/getter can allow the input and output to stay the same (perhaps employing a cast) while the innards change. Then, you don’t have to find and change every instance where the method is being called and change each one.

(The nature of external classes is that they tend to multiply in quantity, and it can become increasingly hard or annoying to track down every place where the direct access is made.)

Using setters/getters is a looser form of coupling between classes than allowing direct access. Loose coupling between classes can be a big benefit, especially when getting into multiple-thread programming.

In general, I’d recommend only using direct access to variables if:

  • they are in a private inner class or an additional class on a class and are only accessed directly by the outer or main class on that file;
  • they are a class that consists only of fields and values, where instances serve as arguments to a more “functional” class or method and are tightly managed.

But maybe, since you are curious and skeptical, it would be good to just go ahead and do it (skip the setters/getters) and see what sort of trouble you get into (or don’t get into) down the road. Sometimes the only way to understand is to do and grapple with the consequences.

I mostly agree with philfrei, except that in my experience it is not hard tracking down the usages of a method or public variable. Aside from the excellent support for this in my IDE, it can as simple as changing the return type / variable type, and then working through all the compiler errors.