#Should class variables be public or private?
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
I was wondering, should class varaible bet set to private, and I should put methods to access them?
just to be sure, class variable = static variable ?
i assume it means any class field?
preferably private with setters/getters as that allows for greater flexibility and you can adhere to a design much better but it's up to you whatever you want to do, I've commonly done for some of my work ```java
public class Something {
public final int a;
public final int b;
public Something (int a, int b) {
this.a = a;
this.b = b;
}
...
}
Microsoft also follows a similar approach with some of their SDK's but it all depends what you're trying to achieve
static constants, often public
Unless you are in a specific case of an access limited class that only hold data and is only used by a single class, or is a class in a very small project, never do that, ever
Yep, my usecase is usually ala's former
And by default you should learn to just use private with getters
in any case
for at least some time until you are intermediate
what exactly is wrong with this one? would you elaborate on this for me please?
Also, is it a problem if I use those setters/getters internally in the class itself where they were defined?
for a static variable
for example in the main
or would this be redundant and I should just go directly for the static variable instead?
@hollow forum please answer my question
yes
depends then, usually you don't mind having public constants, and for non constants, they should be rare enough
wdym
"never do that" confused me. what exactly is wrong with his way?
i started coding a few months ago so i am quite inexperienced and love for some practical insights
i guess it breaks the encapsulation(not good to know what you not supposed to)
you cant change the implementation without changing the api of your class if you dont use getters
oh he was referring to static constants. i thought he was referring to his entire block of code. okay, yes thats clear to me. thanks!
you shouldn't have a static mutable variable, you should use static as few as possible
i only have one, and it's not me who decided about it. Still, my question stands though
you shouldn't need a getter or setter then