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
Related
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.
In my project I have a small data structure Key.
public class Key implements Serializable {
private static final long serialVersionUID = 1L;
public String db;
public String ref;
public Object id;
protected Key() {
}
public Key(String db, String ref, Object id) {
this.db = db;
this.ref = ref;
this.id = id;
}
}
Yes this class is simple and every field is publicly accessible.
But someone has suggested I use POJO style classes instead but when I asked why they were unable to tell me.
In my opinion , calling getters and setters is slower than direct access to a field.
So why I must use POJO programming style?
Taken from Wikipedia:
POJO is an acronym for Plain Old Java Object. The name is used to
emphasize that a given object is an ordinary Java Object, not a
special object.
A POJO is usually simple so won't depend on other libraries, interfaces or annotations. This increases the chance that this can be reused in multiple project types (web, desktop, console etc).
As someone has already pointed out in the comments, your object is technically a POJO already however you have specifically asked about getters and setters which are more akin to JavaBeans.
There are a number of reasons I can think of for using getters and setters:
You might only want to get some of the values (I.E. read only values). With fields, clients can both get and set the values directly. Fields can be made read-only if they are marked as final although this doesn't always guarantee that they are immutable (see point 9).
Getter & setter methods allow you to change the underlying data type without breaking the public interface of your class which makes it (and your application) more robust and resilient to changes.
You might want to call some other code such as raising a notification when the value is obtained or changed. This is not possible with your current class.
You are exposing the implementation of your class which could be a security risk in some cases.
Java beans are designed around POJO's which means that if your class is not implemented as one it can't be used by certain tools and libraries that expect your class to adhere to these well established principles.
You can expose values that are not backed by a field I.E. calculated values such as getFullName() which is a concatenation of getFirstName() and getLastName() which are backed by fields.
You can add validation to your setter methods to ensure that the values being passed are correct. This ensures that your class is always in a valid state.
You can set a breakpoint in your getters and setters so that you can debug your code when the values are obtained or changed.
If the field is an object (I.E. not a primitive type) then the internal state of your class can be modified by other objects which can lead to bugs or security risks. You can protect against this scenario in your POJO's getter by returning a copy of the object so that clients can work with the data without affecting the state of your object. Note that having a final field does not always protect you against this sort of attack as clients can still make changes to the object being referenced (providing that object is itself mutable) you just cannot point the field at a different reference once it has been set.
Yes, accessing or setting the values via method calls may be slower than direct field access but the difference is barely noticeable and it certainly won't be the bottleneck in your program.
Whilst the advantages are clear this does not mean that getters and setters are a silver bullet. There are a number of 'gotchas' to consider when designing real world, robust scalable classes.
This answer to a very similar question looks at some considerations in detail when designing a class that has getters and setters. Although the suggestions may be more relevant depending on the type of class you are designing E.G. a class that forms part of an API in a large system as opposed to a simple data transfer object.
Also note that there may be certain scenarios where a class with direct field may be advantageous such as when speed is essential or memory is limited although this should only be considered after profiling your code and finding that it is actually a bottleneck.
Also be careful that you are not just wrapping all of your fields in getters and setters as this is really missing the point of encapsulation.
This answer provides a good summary of the reasons for choosing a POJO over a JavaBean style object with getters and setters.
Use private class variables and public getters and setters which will provide you Encapsulation.
Getters and setters, especially the simplest forms will just be inlined by the JIT compiler and thus remove the method call overhead. This sounds very much like premature optimisation. If you ever get a bottleneck, then profile and look where it occurs. I am fairly certain it'll be not in property accesses.
Get yourself the book Effective Java.
Item 14, in public classes use accessor methods not public fields.
In this Joshua Bloch says there is nothing inheriently wrong with public fields in package-private or nested classes but strongly advises against use public classes.
He goes into much more detail on the subject, it's a great book, suggest you get a copy.
Imagine if some other programmer is using your code. If you don't provide setter and getter methods then he can directly call your variable and it surely will affect to your code. And it may lead to security issues
So by providing POJO class you are forcing him to call on your methods rather than directly calling your Instance variables.
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.
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.
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?