private String or public static String? - java

At my internship one of my colleagues gave me a hint. I want to know if this is good practice.
What I was doing was creating classes that are used only for the values they contain and don't have any functions that actually do something (apart from having getters, setters and a constructor). I declared my variables like this:
public class ObjectIUse{
Private String name;
public ObjectIUse(String name){
this.name = name;
}
public String getName(){
return name;
}
}
So I'm not using a setter because it should always stay the same. My colleague said that I can also do it this way:
public class ObjectIUse{
public final String name;
public ObjectIUse(String name){
this.name = name;
}
}
Because now we don't need to have any getters or setters because it is public, however it can also never be changed because it is final.
Which would be better? Or would it maybe be preferable to still make it private but also final? I mean all of the options work, obviously. I just want to know which is better and why.

Make the variable private, because by doing so you'll be encapsulating the variable in your class. This has many benefits, information hiding is among one, which you'll learn if you go to the above link.
If you want it to never change after creation, then make it final too.

This works now because a String is immutable. But what happens when you expose the reference to a mutable class and that class is not thread safe ?. You cant even return a defensive copy if you want to.
Not to mention this also breaks encapsulation. Use a private variable and getters.

The idea of not providing a setter method to a variable makes it a read-only field, that said, it means we can only read but not write, so making it a constant by the use of the final keyword summarizes it all.
I think a constant is better. final keyword improves performance. Read more here

You should definitely have a getter and make your field private. That is what we call encapsulation.
Also by making it final and so not having a setter, your object is immutable, whic is a very good thing for parallel programming.

A proper use of encapsulation principle is to make all class fields private and access them via setters and getters. Other than that, you might want to add any additional logic when you're calling getName(). While second variant is sometimes used, the first one is better. Hope this helps.

Which would be better? Or would it maybe be preferable to still make
it private but also final?
If you want to be successful developer, you should program correctly, efficiently and the most important securely. Security and performance is on the first place.
When you make it public you will break encapsulation that is very important and has many benefits. Every time you want to get property of Object, getters will become your friend.
Generally you shouldn't have direct access to properties of Object(only in extrem cases but also these can be solved in better way). Getters and Setters are designated for these purposes - preserve encapsulation and deal with objects securely.
final variables are usually used for data which are unchangeable during a time.

I guess their reasoning is that having it public keeps the code simpler. Java gets criticised for being too verbose in situations like this. Over a language such as Javascript where this would (normally) always be public.
But that simplicity is a trade-off against having secure, stable and extendable code.
To see why that's important, take a look at a large-scale Javascript project that has been written with everything as public. Each class's code might be simple... but their relationships, and the resulting architecture, end up being a nightmare to maintain.

I think it's depends. For example: if you use getter - you can override it. Sometimes it very usefull.

Related

Necessity of getter methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
This is a newbie question. Is it very much necessary to use getmethods to access property values? Once the value has been assigned, one can get the values directory. For example, in the below code, displayName() can display firstName value without the help of any getter method. Or it is a standard coding standards that one must have getter and setter method or any other methods which gives that value?
class Test{
private String firstName;
public void setName(String fname){
firstName = fname;
}
public void displayName() {
System.out.println("Your name is " + firstName);
}
}
Tell, Don't Ask is an important principle in object-oriented design. Generally you should tell objects to do things rather than ask them questions. getters/setters every where discourage this practise because you are encouraged to reach inside an object and get to the fields (or even worse reach in and poke things about in the case of setters). This breaks encapsulation and makes your code harder to reason about.
In your particular case, I'd create an object called Name that has a constructor taking the name and single method to display it.
In Your case (to display the display name) it is not neccessary to provide Getter.
But if your want use the field in another class We need to provide the Getter method.
Getter and setters are a part of the standard interface for Java Beans and many frameworks like Hibernate expect them in place. That being said it is of course up to you to decide if and when you need them and for what purpose. They provide access to your private member variables and they can even give you the chance to do more than just plain get and set.
The point of OO software is reuse. This means that other programmers, or you years from now, can use the code for other systems.
When you have private member variables, and use get/set functions, you can change the internal implementation of the function without breaking all the other code that uses it.
Do always use Getter and Setter to access your properties!
You should take a look at this article...
Having private state, encapsulation is good, and in A LOT of cases this is the right thing. Suppose that your class is suppose to be Thread Safe, having public fields you can't ensure that.
On the other hand there are cases when this is useless! Suppose that you access your object only in one package, you are sure you will never export it, then why bother?
I do not have any links to support this, but it's what I do.
I try to avoid public fields if they are not static. So I just use protected and private fields. From within the class, you can access them without get/set, that's completely fine. From outside the class, always try to use get/set.
So your example code is completely fine to me. :)
EDIT: One exception for me is if I create a struct-like container class like this
class Point4D {
public int x1, x2, x3, x4;
}
Then I think that public fields are ok. It would be still better to make them private and name the getters public int x1() etc though. As soon as some methods are introduced to this container that change the state of the instance (like changing the values of x1/x2/x3/x4), I make them private and add get/set.

What is the point of getters and setters? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
I have read books on Java, saying that it is good to create setters and getters for variables such as x and y. For example:
public int getX(){
return x;
}
public void setX(int x){
this.x = x;
}
But what is the difference from that and
...(shape.x)... // Basically getX()
and
shape.x = 90; // Basically setX()
If setters and getters are better, what practical problems would arise?
Multiple reasons:
If you allow field access like
shape.x = 90
then you cannot add any logic in future to validate the data.
say if x cannot be less than 100 you cannot do it, however if you had setters like
public void setShapeValue(int shapeValue){
if(shapeValue < 100){
//do something here like throw exception.
}
}
You cannot add something like copy on write logic (see CopyOnWriteArrayList)
Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.
Though for constants like
public final String SOMETHING = "SOMETHING";
you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.
Another scenario is when you want your Class to be immutable, if you allow field access then you are breaking the immutability of your class since values can be changed. But if you carefully design your class with getters and no setters you keep the immutability intact.
Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).
We can use the private variables in any package using getters and setters.
Using getter and setter functions allow for constraints and encapsulation. Lets say x is the radius. shape.x = -10 would not make much sense. Also, if someone tries to set an illegal value, you can print an error, set a default value, or do nothing.
It is good practice to make member variables private so they cannot be modified directly by programs using them.
Mutator functions
Encapsulation
A lot of people have mentioned encapsulating the specifics of the implementation, which to me is the biggest reason to use getters and setters in a class. With this, you also get a lot of other benefits, including the ability to throw out and replace the implementation on a whim without needing to touch every piece of code that uses your class. In a small project, that's not a big benefit, but if your code ends up as a well-used (internal or public) library, it can be a huge benefit.
One specific example: complex numbers in mathematics. Some languages have them as a language or framework feature, others don't. I will use a mutable class as an example here, but it could just as easily be immutable.
A complex number can be written on the form a + bi with real and imaginary parts, lending itself well to [gs]etRealPart and [gs]etImaginaryPart.
However, in some cases it's easier to reason about complex numbers on polar form re^(iθ), giving [gs]etRadius (r) and [gs]etAngle (θ).
You can also expose methods like [gs]etComplexNumber(realPart, imaginaryPart) and [gs]etComplexNumber(radius, angle). Depending on the argument types these may or may not need different names, but then the class' consumer can use either as fits its needs.
The two forms are interchangeable; you can fairly easily convert from one to the other, so which form the class uses for internal storage is irrelevant to consumers of that class. However, consumers may use either form. If you choose the form a+bi for internal representation, and expose that using fields rather than getters and setters, not only do you force the class consumers to use that form, you also cannot later easily change your mind and replace the internal representation with re^(iθ) because that turns out to be easier to implement in your particular scenario. You're stuck with the public API you have defined, which mandates that specifically the real and imaginary parts are exposed using specific field names.
One of the best reasons I can think of for getters and setters is the permanence of a class's API. In languages like python you can access members by their name and switch them to methods later. Because functions behave differently than members in java once you access a property thats it. Restricting its scope later breaks the client.
By providing getters and setters a programmer has the flexibility to modify members and behavior freely as long as the adhere to the contract described by the public API.
Another good reason to user getter and setter can be understand by the following example
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
}
The point of getters and setters is that only they are meant to be used to access the private variable, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.
Imagine you use name instead of its getter. Then if you want to add something like a default (say the default name is 'Guest' if it wasn't set before), then you'll have to modify both the getter and the sayName function.
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
if (this.name == null ){
setName("Guest");
}
return this.name ;
}
}
There is no requirement for getters and setter to start with get and set - they are just normal member functions. However it's a convention to do that. (especially if you use Java Beans)
Let's say, hypothetically, you find a library that does a better job of what you have been doing in your own class (YourClass). The natural thing to do at this point is to make YourClass a wrapper interface to that library. It still has a concept of "X" which your client code needs to get or set. Naturally, at this point you pretty much have to write the accessor functions.
If you neglected to use accessor functions and let your client code access YourClass.x directly, you would now have to rewrite all of your client code that ever touched YourClass.x. But if you were using YourClass.getX() and YourClass.setX() from the beginning, you will only need to rewrite YourClass.
One of the key concepts of programming, and especially object oriented programming, is hiding implementation details so that they're not used directly by code in other classes or modules. This way, if you ever change the implementation details (as in the example above), the client code doesn't know the difference and doesn't have to be modified. For all your client code knows, "x" might be a variable, or it might be a value that is calculated on the fly.
This is an oversimplification and doesn't cover all the scenarios where hiding implementation is beneficial, but it is the most obvious example. The concept of hiding implementation details is pretty strongly tied to OOP now, but you can find discussions of it going back decades before OOP was dreamed up. It goes back to one of the core concepts of software development, which is to take a big nebulous problem, and divide it into small well-defined problems which can be solved easily. Accessor functions help keep your small sub-tasks separate and well-defined: The less your classes know about each other's internals, the better.
There are lots of reasons. Here are just a few.
Accessors, getters in particular, often appear in interfaces. You can't stipulate a member variable in an interface.
Once you expose this member variable, you can't change your mind about how it's implemented. For example, if you see a need later to switch to a pattern like aggregation, where you want the "x" property to actually come from some nested object, you end up having to copy that value and try to keep it in sync. Not good.
Most of the time you are much better off not exposing the setter. You can't do that with public fields like x.
Before get into the answer, we gotta know something prior...! "JavaBeans".
JavaBeans are java classes that have properties. For our purpose, think of properties as private instance variables. since they're private, the only way they can be accessed
from outside of their class is through 'methods'in the class.
The methods that change a propertiy's value are called setter methods, and the methods that retrieve a property's value are called getter methods.
I would say that neither the getters/setters nor the public members are good Object Oriented design. They both break OOP Encapsulation by exposing an objects data to the world that probably shouldn't be accessing the properties of the object in the first place.
This is done by applying the encapsulation principle of OOP.
A language mechanism for restricting access to some of the object's components.
This means, you must define the visibility for the attributes and methods of your classes. There are 3 common visibilities:
Private: Only the class can see and use the attributes/methods.
Protected: Only the class and its children can see and use the attributes/methods.
Public: Every class can see and use the attributes/methods.
When you declare private/protected attributes, you are encouraged to create methods to obtain the value (get) and change the value (set). One example about visibility is the [ArrayList][2] class: it has a size property to know the actual size of the inner array. Only the class must change its value, so the code is something like
public class ArrayList<E> {
private int size;
private Object[] array;
public getSize() {
return this.size;
}
public void add(E element) {
//logic to add the element in the array...
this.size++;
}
}
In this example, you can see that the size value can change only inside the class methods, and you can get the actual size by calling it in your code (not mutating it):
public void someMethod() {
List<String> ls = new ArrayList<String>();
//adding values
ls.add("Hello");
ls.add("World");
for(int i = 0; i < ls.size(); i++) {
System.out.println(ls.get(i));
}
}
Getters and setters encapsulate the fields of a class by making them accessible only through its public methods and keep the values themselves private. That is considered a good OO principle.
Granted, it often seems like redundant code if it does nothing more than setting or returning a value. However, setters also allow you to do input validation or cleanup. Having that in one place improves data integrity for your objects,
Because we are using Object oriented programming language.
Here we are using Data hiding and encapsulation.
The variable should not directly accessible from out side world (for achiving data hiding) so we will create it private so
shape.x
is not correct.
Getter and setter method are used to get and set the value of x which is the way to achive encapsulation.

Is there case for not using getters and setters here?

From what I understand, getters and setters are recommended for use for ALL variables and situations.
However I have a situation here where it seems they are just making the code long and awkward so I want to know can I leave them out in this situation or is that bad practise...
I have the following class -
public class Conversation {
class Message
{
private int id;
private int senderId;
private Timestamp timeSent;
private String text;
}
private int conversationId;
private int userIdA;
private int userIdB;
private ArrayList<Message> messages = new ArrayList<Message>();
...
... (Getters and setters for members of Conversation)
...
}
So I am using getters and setters for the Conversation member variables. However I don't want to use them for inner class, Message, variables. It is just adding about 30 lines to the code of filler and makes it look much more awkward. So is it bad practise to leave them out here? I will also never be editing the Message variables, they will be set with a call to the constructor Message(..., ..., ..., ...) and after that they will just be read. So I definitely reckon it's fine to leave out the getters, but what about the setters?
If Message were private, I would say no problem at all with using the fields directly; it's just an internal-details struct, and there are no encapsulation issues (since the outer class can see all of the inner class' private variables, anyway).
But, Message is package-private: anyone in that package can also see its fields. This is a gray area, because it's not quite the published API, but it's still reasonable, depending on how big the package is, that you'll want encapsulation down the line. For instance, if it's a big package and some other class starts depending on Message (and if none do, you may as well make it private), then you risk encapsulation problems if you want to change Message's internals down the line. So, it's a judgement call.
If Message were public, I would definitely say to provide getters.
Btw, if you're using Message just as a POD here, you should make it static -- good habit to get into. Generally speaking, static is better than not.
getters and setters are recommended for use for ALL variables and situations.
Well, all never and always rules are bad. Excluding this one. :)
You shouldn't use getters and setters just because it's standard practice. For example, if I had a class Point2d with 2 members x and y, I'd probably not use accessors.
You should ask yourself - will my members be changed a lot inside the code? Will it be a hassle debugging and seeing where I change the members? If the answer is yes, you definitely need accessors. If not, it's up to debate - whatever makes the code more readable and easy to maintain.
If they are set in
new Message(int,int,Timestamp, String)
and the fields won't be changed then it is best have get methods only.
Only having get methods helps enforces your constraint of making them read only.

Is it bad to have public variables in a non-static class?

I am writing a game and I have a class for the input which contains booleans for all the different keys. I create an instance of this class in the main game class. Is it ok for the booleans to be public, or should I access them with accessors?
Instead of having a boolean for each key, it would be more readable and easier to code if you had a private Map<String, Boolean> keyStates, with all keys initialized to false. Then your accessors might be:
public void setPressed(String keyName) {
keyStates.put(keyName, true);
}
public void setReleased(String keyName) {
keyStates.put(keyName, false);
}
public boolean isPressed(String keyName) {
return keyStates.get(keyName);
}
The general reason for having accessor methods rather than public variables is that it allows the class to change its implementation without requiring changes in the classes that interact with its members. For example, with the above, you can now add code to count or log key presses, or change the underlying type of Map used, without exposing any of this to the outside.
This is not personal preference. Encapsulation and Interfaces are integral parts of OO Software Engineering, and are the primary design reasons that the Internet is possible from a technical POV.
Generally I would recommend using getters and setters as it is cleaner, more organized, and more readable. This will also help if you have a lot of different programmers looking at your code. My outlook is to always make your variables private unless you need to expose them for a specific reason. If performance is really an issue in your game then making your variables public will help a little by reducing function calls.
It's mainly a personal taste thing - I'm sure you'll find people arguing on both sides, and I'd say it's not black or white but depends on how "big" the class is.
The rationale for using getters and setters is so that you abstract out the actual representation as a field, in order to give you the freedom to start presenting this as e.g. a derived value without changing your interface. So really it comes down to how valuable the interface to this class is to you.
If it's part of your first-class public interface, then definitely use getters and setters. At the other extreme, if it's a simple data holder like a tuple that's used solely within a single class (e.g. to map database rows before transformation into another class), then I wouldn't hesitate to use fields; there's no real value to the interface as it's only being used internally.
So how many classes/packages would use this class? If it's a private, "local" class then I don't think there's anything wrong with just using the fields, and updating your callers if this ever needs to change.
Accessing fields is much easier to justify if they're final too, which is often the case with this sort of object.
It's not bad, but usually you'll want to encapsulate the state of an object.
Standard practice is to make member variables either protected or private with getters/setters that follow java bean convention. This tends to be somewhat verbose, but there is a very nice library (www.projectlombok.org) out there that generates the getters/setters/constructors/toString/hashCode/equals methods for you.
It is always a good java programming practice to declare the class variables as private and access them with public getter and setter methods unless its really needed to declare them as public .
If you are using an IDE , then its just a click away to generate getters and setters for class variables/member variables .
And now that you have been told over and over to use getter and setters, and because you are in Java (where IDEs help you make getters/setters trivially, and everyone clearly uses them), read over this thread to help add some balance to your usage of them:
Getters and Setters are bad OO design?

Should all methods that do not use instance variables be marked static

Suppose I have a class like this:
public class Car {
private double distanceDriven;
public void drive(double miles){
distanceDriven += miles;
}
public void driveInCanada(double kilometer){
distanceDriven += convertToMiles(kilometer);
}
private double convertToMiles(double km){
return km*0.621371192;
}
}
You can see that convertToMiles is:
not using any instance variables
is only used inside the class
Should it be declared as static? This does not change the functionality of the the function at all (see above). I think that it may affect:
readability
performance
other?
Should the convertToMiles function look like:
private double convertToMiles(double km){
or
private static double convertToMiles(double km){
For maximum stylistic hygiene, yes, private methods that don't use any object state, but only make sense inside the object, should be static.
That's the clearest (and strictest) way of indicating how they operate, and it will helpfully force you to be careful about your design around method-boundaries, and to think twice if you decide to go change one of them later to use object data.
FWIW, I don't suspect there's a relevant performance impact here (in theory the static is easier to call due to no implicit this reference). Also, you could go nuts being strict about this in your codebase, but it's certainly a reasonable goal to have.
N.B. Public methods require more consideration before marking them static; those can't change down the road without impact to callers, so "defaulting to tightness" isn't always the right choice.
If you're asking yourself this, they your design is already shaky. You should rip all those "static" functions out of the class and put them in a generic, reusable algorithm container static class.
Look at your code, what does convertToMiles have to do with a car? That's a generic algorithm that can be reused in multiple functions.
Using static might make a performance difference, however this is less likely if it is inlined as it won't be called as much.
static is useful as it makes it clear you are not accessing any member fields. This has picked up some bugs for me in the past when I marked a method as static but this produced an error (because it shouldn't have been using a member field)
You can get creative with the design and add layers and complexity which might be useful one day, but I would go with the YANGI principle and say it is unlikely you are going to want to change how kilo-meters are converted to miles, or if you do change it you are unlikely to want more than one way of doing it.
A definitive NO for ALL such methods.
For example it is perfect legal that such a method calculates an result (return value) only on its arguments, and the author would like to allow others to change the calculation in a subclass. (This is some kind of Template Method pattern.) -- And overriding a class can be only done if they are ..not.. static.
Btw: if you change your question and ask only for private methods, then I could not argue this way. But you asked for all kind of methods.
yes. Use static methods when you can.
private static double convertToMiles(double km){}
This will be the right one for your program code as convertToMiles() method has nothing to do with the instance variable.
But keep in mind this method is not reusable in other class by non-static members, if yes then the very purpose of static wont serve, as static avoids multiple object creation and memory wastage.

Categories