java
java

Reputation: 1339

Is there ever a correct time to use a public variable?

Is there a situation were using a public variable would be beneficial? If not, why do they even exist?

Also I am specifically talking about Java, but if they have use in another language perhaps that would give reason to their existence.

Upvotes: 0

Views: 92

Answers (3)

intermat
intermat

Reputation: 19

Global variables (when the language allows), can cause major problems especially in complex systems, where a piece of code can change its value at any time. Besides creating a coupling between places that should not have.

so avoid

In java I usually use public final constants in a single centralized source.

Upvotes: 0

tilpner
tilpner

Reputation: 4328

Yes, I use them for my representation of a vector.

public class Vec3f {

    public final float x, y, z;

    // the methods

}

Note that because these are final primitives it is safe to expose them. This is shorter in code and uses less method calls (none).

In general, they are viable to use in value-objects (let's use that name) if made final. I define value-objects as possibly immutable, possibly short-lived objects holding just data, yielding new objects on mutation.

You shouldn't use public non-final variables in your public API though...

Upvotes: 3

DaveH
DaveH

Reputation: 7335

public static final variables are a common and handy way of defining constants

Public member variables are a little harder to justify, but I have seen a massive number of bean type objects with a load of private member variables and a corresponding set of getters and setters that do nothing but return or set the private variables. In those cases, there is an argument to make those variables public as the data is hardly "encapsulated" by the class - the user can set it to whatever they like, and they retrieve whatever the variable is set to without any modification.

I don't do it personally, but I'm not 100% against it either.

Upvotes: 0

Related Questions