Software good practices - set and get methods - java

I want to get my head around the idea of using setters and getters in superclass and subclass in terms of software good practices.
From your experience, which method of the below are appropriate and also promote good software re-usability:
declaring a protected instance variables in the superclass and let the subclass uses them.
declaring a private instance variables in the superclass with public getter methods to let the subclass inherits the getter methods from the superclass.

Depends on your style of coding. Some prefer concise code over more verbose structured code. If your ultimate goal is interoperability and scalability, you're 'safer' using getters/setters. Another advantage is with the getters/setters you can perform multiple operations instead of only a single operation, for instance getUsers() may actually tabulate multiple data rows. This way you can consolidate that operation instead having to repeat it in subclasses.
Use your best judgement. If the values are simple booleans or strings, probably don't need a g/s. If they're query related or make specific, repeated modifications to state or data, use a g/s approach.

Both methods are acceptable. Normally, I would have public getter/setter methods since anyone can use them, not just subclasses.

I pick number 1. That's exactly the situation where the existence of protected is justified. Getters and setters are for classes using another non-related class.

I pick 1 mostly when I am going to create an abstract class.
Otherwise, I always pick 2 (creating getter/setter). Because:
Not only that avoid any accidental/unintended modification to
class's member variable, it also help when you will go about
creating jUnit test-cases for your classes.
Decouple the classes.
Any good book on Object Oriented Programming will list other benefits of using getter and setter.

Related

In Java, is there a better alternative to getter and setter methods?

It is common in Java classes to have lots of getter and setter methods, one each for every data model class variable. I realize that many IDEs will create these for you, but I'm trying to avoid this clutter and not have all these methods in my classes. So, is there any way to access a variable in a read only fashion outside the class (as if it were public final), while retaining write access inside the class or subclass exclusively (as if it were private or protected).
The only pseudo-solution I've come up with is a base class (or interface with default methods) that has a get(String variableName) method which then gets the fields of the class via reflection and returns the appropriate one. The downside is that for that to work, the variables have to be public, so only by convention does it meet my requirements (in that in the extending/implementing class that has the variables I want to access, I only call the get method from outside the class, and don't implement a set method). The main thing I don't like about this is that if a variable name changes, callers of the get methods will not cause compiler errors, since the variable name is just a hardcoded String.
Anyone have a better idea?
Yes - try to design your classes so you don't have getters and setters at all. Typically it's a bad design to have getters and setters on all of your fields because it breaks encapsulation. An exception is the case of Java Beans (where you have a model class/DTO or some class that's mapped to XML/JSON); here you should not mind them because setters and getters are the only methods.
In classes that have logic, inject your dependencies via constructor or directly if you use Spring/CDI and you like it. This is more safe because you won't have objects in inconsistent states; like for example you create an object but forget to call a setter -> NullPointerException. But by using constructors, you avoid the case of forgetting to call the setters.
Of course there might be exceptions, like when setting some optional fields when you don't want all the dependencies in the constructor all the time. This however can be solved with overloading constructors or if the case is more complex the problem can be solved in a more elegant way by using the builder pattern.
See a great article on this: http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html
You may use lombok - to manually avoid getter and setter method. But it create by itself.
The using of lombok significantly reduces a lot number of code. I found it pretty fine and easy to use. But here you may find some pros and cons of using lombok here.
Hope it will help.
Thanks a lot.
Java FX introduced something similar to what you want: ReadOnlyProperty
Might not be exactly what you are looking for, though. In general, I don't think exposing a variable is a good idea.

Treatment to field inside the class. Through getter or explicit?

consider the class:
class MyClass{
MyOtherClass obj;
//setObj and getObj methods
public void someMethod(){
...
//access to obj needs.
...
}
}
How to right replace
//access to obj needs.
through getter or explicitly?
P.S.
I saw both variants in my expirience.
Personally I would say it depends on the level of "connection" between both classes. If they are in the same package and part of the same "mecanism" (one would have no reason to exist without the other), bypassing accessors is acceptable.
So here we're talking about code in Class MyClass accessing information in an instance of MyOtherClass.
Typically you don't get a choice. If MyOtherClass exposes a getter for a data member, it's unlikely to also expose that data member. If it does (even if the data member is, say, protected but the accessor is public), the design is a bit questionable.
But if you do have the choice, I would use the getter, rather than the exposed data member. It's a bit subjective, but using data members rather than accessors more tightly binds the classes together. In my protected/public example, you'd have more work to do if for any reason you wanted to move MyClass to a different package.
It's worth noting that using the getter is not more expensive in performance terms with a decent JVM (such as the one from Sun). If the code becomes a performance "hotspot" for whatever reason (or possibly even if it doesn't), the JVM's JIT will convert the call to the getter into a direct access anyway (presuming it's a pure getter), so you get the benefit of abstraction at the coding/design-time without the function call overhead at runtime.
To answer this, let's first see why getters and setters were introduced in the first place. It is clear that direct access to data members is simpler.
SOme of the reasons are:
for a better encapsulation, to hide the property implementation from a class user. For example you can internally store a temperature value in C and return it by a getter in F.
for more control over the access. If you want to do something more besides pure getting/setting a piece of data, you would need a method. For example, you might want to log the change of value for audit purpose
methods are much more "interface friendly" than pure data members.
In this case the class itself accesses its own property. Are you sure you want that?
If so, let's see the reasons:
Encapsulation is definitelly not needed, since the class itself accesses its own attributes.
Do you need to somehow control access here? Do you need to do something else, besides get/set? Are there any other possible users of this class?
If all these answers are NO, ans especially if the only user of this class the mentioned method, then go for a simpler option and use direct access, without getters/setters.
If some of the answers is true, just make a simple trade-off and decide.

java - public access vs accessor methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
I'm reading the Java for Dummies 2nd edition, and it says that it's better to define accessor methods for class's variables instead of making them public. Is that true?
Yes.
Defining accessor methods allows you greater flexibility. For instance, you can make it publicly readable, but only privately writable.
Here's a Skeet answer to this particular question. He suggests always making your fields private
Yes, it's a convention.
It allow you to control how other classes will access the members (that are usually private). For example you can start with a basic get/set that return and set the value. But maybe later in the project you will want to add more control. in this case you will only have to change get/set method instead of refractoring all your project.
I'd go as far as to say it is better not to even have accessor methods either, if possible. Make the class do work on its own state rather than exposing it for another class to work with.
If you do have to expose state, accessor methods give you the opportunity to return a copy of the state rather than the actual object. This way calling classes wont be able to modify the state from outside, avoiding the issue of invariants being broken.
This is true!
In Java, it is common practice to declare class variables private, and then write public accessor and mutuator methods to control them outside of the class.
It is usually good to make accessor methods, to regulate the data any other class (and anybody) can use.
Particularly in big projects, you want other classes only to use just a few of the many variables in the class, so you only make a few getter methods.
On the second hand, it makes the code cleaner, it is easier to see what is happening. Thirdly, it is harder to create your own bugs in your program by using the wrong variable, because in other classes there are less possible variables to choose from.
I recommend reading about object oriented programming philosophy:
wikipedia:
When you define accessors you can write there some extra logic protecting the state of your objects.

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?

Java Interface Usage Guidelines -- Are getters and setters in an interface bad?

What do people think of the best guidelines to use in an interface? What should and shouldn't go into an interface?
I've heard people say that, as a general rule, an interface must only define behavior and not state. Does this mean that an interface shouldn't contain getters and setters?
My opinion: Maybe not so for setters, but sometimes I think that getters are valid to be placed in an interface. This is merely to enforce the implementation classes to implement those getters and so to indicate that the clients are able to call those getters to check on something, for example.
I don't see why an interface can't define getters and setters. For instance, List.size() is effectively a getter. The interface must define the behaviour rather than the implementation though - it can't say how you'll handle the state, but it can insist that you can get it and set it.
Collection interfaces are all about state, for example - but different collections can store that state in radically different ways.
EDIT: The comments suggest that getters and setters imply a simple field is used for backing storage. I vehemently disagree with this implication. To my mind there's an implication that it's "reasonably cheap" to get/set the value, but not that it's stored as a field with a trivial implementation.
EDIT: As noted in the comments, this is made explicit in the JavaBeans specification section 7.1:
Thus even when a script writer types
in something such as b.Label = foo
there is still a method call into the
target object to set the property, and
the target object has full
programmatic control.
So properties need not just be simple
data fields, they can actually be
computed values. Updates may have
various programmatic side effects. For
example, changing a bean’s background
color property might also cause the
bean to be repainted with the new
color."
If the supposed implication were true, we might just as well expose properties as fields directly. Fortunately that implication doesn't hold: getters and setters are perfectly within their rights to compute things.
For example, consider a component with
getWidth()
getHeight()
getSize()
Do you believe there's an implication that there are three variables there? Would it not be reasonable to either have:
private int width;
private int height;
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Size getSize() {
return new Size(width, height); // Assuming an immutable Size type
}
Or (preferrably IMO):
private Size size;
public int getWidth() {
return size.getWidth();
}
public int getHeight() {
return size.getHeight();
}
public Size getSize() {
return size;
}
Here either the size property or the height/width properties are for convenience only - but I don't see that that makes them invalid in any way.
I think that there are two types of interfaces declared in general:
a service description. This might be something like CalculationService. I don't think that methods getX should be in this sort of interface, and certainly not setX. They quite clearly imply implementation detail, which is not the job of this type of interface.
a data model - exists solely to abstract out the implementation of data objects in the system. These might be used to aid in testing or just because some people as old as me remember the days when (for example) using a persistence framework tied you down to having a particular superclasss (i.e. you would choose to implement an interface in case you switched your persistence layer). I think that having JavaBean methods in this type of interface is entirely reasonable.
Note: the collections classes probably fit in to type #2
There's nothing inherently evil about getters/setters. However:
I tend to make my objects immutable (in the first instance) with respect to the fields they contain. Why ? I instantiate most things during the construction phase. If I want to change something later then I relax those restrictions. So my interfaces will tend to contain getters, but not setters (there are other benefits - particularly threading).
I want my objects to do things for me, not the other way around. So when one of my objects acquires a number of getters, I start to ask whether that object should have more functionality in it, rather than exposing all its data for something else to work with. See this answer for more detail.
These are all guidelines, note.
I don't think a bean should have an interface on top of it, in general. A javabean is an interface in the more general meaning. An Interface specifies the external contract of something more complex. A javabean's external contract and its internal representation are identical.
I wouldn't say that you shouldn't have getters in an interface, though. It makes perfect sense to have a ReadableDataThingie interface that is implemented by DataThingieBean.
I've heard people say that, as a
general rule, an interface must only
define behavior and not state. Does
this mean that an interface shouldn't
contain getters and setters?
For starters, at least with Java and excluding Exception declarations, you cannot define complete behavior without state. In Java, interfaces do not define behavior. They can't. What they define are types; promises of implementing a set of feature signatures possibly with some post-conditions wrt exceptions. But that's it. Behavior and state are defined by classes implementing those interfaces.
Secondly, if getters and setters are defined in an interface, they don't really define complete behavior (other that one is for read and one is for write wrt a property.) You can have complex behavior behind setters and getters, but they can only be implemented in the actual classes. There is nothing in the Java language that can allow us to freely define behavior in interfaces except for the most restrictive of cases.
With that into consideration, there is nothing wrong - syntactically and semantically - with having setters and getters in interfaces.
If your application is well-modeled and the problem requires that you have an interface defining setters and getters, why not. For example, take a look at the ServletResponse interface.
Now, if we look at getters and setters from the point of view of implementing classes compliant with the JavaBeans specs, then you do not need to define interfaces for them.
But if you have things that require setters and getters, like a bean might, and which is also required to be plugged at compile-type (not at run-time like a bean might), and for which multiple implementations might exist, then yeah, this would call for an interface defining getters and setters.
Hope it helps.
This touches upon the whole Getter/Setters are evil topic which is addressed multiple times on this site and elsewhere.
I tend to favour not having accessors in the interface, but to add collaborators using constructor arguments to the implementation.
The fact that the straightforward implementation of something is as a getter shouldn't stop it being in an interface if it needs to be.
I used those kind of interfaces, for example we had classes with fields beginDate, endDate. Those fields were in many classes and I had one use case I need to get those dates for different objects, so I extracted interface and was very happy :)
For further reading: Practical API Design Confessions of a Java Framework Architect (Jaroslav Tulach, 2008, Apress).
Basically if the answer to "Do I need to know the value of [state, property, whateverThignAMaGit] in order to work with an instance of it ?" then yes... the accessors belong in the interface.
List.size() from John above is a perfect example of a getter that needs to be defined in an interface
Getters are used to query the state of an object - which you can really avoid when designing your interface. Read http://www.pragprog.com/articles/tell-dont-ask

Categories