Related
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
I know it has been asked before, but I still am not truly getting it.
People say it is about encapsulation, to protect the fields from outside classes from being accessed? But what's the point of protecting the fields if you are using a get/set methods to change and access the fields anyways?
People also said using get/set methods, you can have the flexibility to add more logic into the methods. I agree, but what happens if your program will never require such a thing? In that case, can you just still declare the field as public instead of get/set method?
You should not set your field as public. This is encapsulation in java. Others doesn't know how the values are populated in to the private variables, they may change it from several places, atlast it become a huge mess. But they have access to some method which is public. I didn't say Getters/Setters.
So up to your point Getter/Setter . Don't use that if you follow java encapsulation. This is same as public variable then (May be some more logic added to it, but user can alter that using setter).
What you have to do is, expose public method in the same class, do whatever manipulation you want to do with instance variables and return only the required results that user need to know.
Eg: Take a class CocaCola . You write a method createCola(). inside that you create the cola and return the result. User doesn't need to know the ingredients of Cola. If you create Getter/Setter otr make the ingredient public that is worse.
These are just standards or best approach in java, that experts suggest. So if you don't want to follow, you don't need to .
Refer:
Java Getters/Setters are evil
It is my understanding that if you make your fields public, other programs running on the same machine can access and edit the data unchecked (Someone correct me if I am wrong). Then there is the possibility of the program trying to store a String object into an address that is supposed to point to an Integer, resulting in an exception that could potentially be a security flaw.
The main idea is that if someone else uses your class as part of a bigger program, the set method can include validity checking and exception handling so as to protect them from having to deal with it.
Example:
private int value;
public void setNonNegativeValue(int newValue){
try{
if (newValue >= 0){
value = newValue;
}
} catch (Exception e){
//handle it here
}
}
Now obviously this method isn't going to result in needing Exception handling, but you see how more complicated ones could.
In this case, value can only be a positive number because the setter method checks for that. However, if value was public, any class could just do myClass.value = -1; This would be a problem if you needed value to be positive
public fields mean every one can access and modify them , but having private fields does not mean you have to declare its setter/getter every time it may depend upon your requirement, for suppose there is such field you want user to get its value but not to change its value. this is all data hiding depending upon your business.
This question already has answers here:
Why are getter and setter method important in java? [duplicate]
(6 answers)
Closed 7 years ago.
Encapsulation is hiding the data. I would like to hear some really interesting answers here.
What is the point behind keeping variables as private when we already declare public setter methods for variables?
I understand the usage of encapsulation but when we are making the setters as public what is the point behind keeping the variables as private, we can directly use public access modifiers.
Is it because we do not want others to know the exact way we are storing data or managing data on the back-end?
Is it because we do not want others to know the exact way we are
storing data or managing data on the back-end?
Yes, that's the point. It is related to the concepts of abstraction and information hiding too.
You provide a public setter that when invoked by the class client will have the effect that you have documented. It is none of the client's business how this effect is actually achieved. Are you modifying one of the class attributes? Ok, let the client know that, but not the fact that you are actually modifying a variable. In the future, you could want to modify your class so that instead of a simple backup variable it uses something completely different (a dictionary of attributes? An external service? Whatever!) and the client will not break.
So your setter is an abstraction that you provide to the client for "modify this class attribute". At the same time you are hiding the fact that you are using an internal variable because the client doesn't need to know that fact.
(Note: here I'm using the word "attribute" as a generic concept, not related to any concrete programming language)
I fully agree with Konamiman's answer, but I'd like to add one thing:
There are cases where you really don't want that abstraction. And that's fine.
A simple example I like to use here is a class for a 3-dimensional float vector:
class Vector3f {
public:
float x;
float y;
float z;
};
Could you make those fields private and provide setters instead? Sure, you could. But here you might argue that the class is really just supposed to provide a tuple of floats and you don't want any additional functionality. Thus adding setters would only complicate the class and you'd rather leave the fields public.
Now, you can easily construct scenarios where that might bite you later on. For instance, you might one day get a requirement that Vector3fs are not allowed to store NaNs and should throw an exception if anyone tries to do so. But such a hypothetical future problem should not be enough to justify introducing additional abstractions.
It's your call as a programmer to decide which abstractions make sense for the problem at hand and which ones would only get in your way of getting the job done. Unnecessary abstractions are over-engineering and will hurt your productivity just as much as not abstracting enough.
Bottom line: Don't blindly use setters everywhere just because someone claimed that's good practice. Instead, think about the problem at hand and consider the tradeoffs.
Because by encapsulation we provide single point of access. Suppose you define a variable and its setter as follows
String username;
public void setUsername(String username){
this.username = username;
}
Later you like to add some validation before setting username property. If you are setting the username at 10 places by directly accessing the property then you don't have single point of access and you need to make this change at 10 places. But if you have one setter method then by making a change at one place you can easily achieve the result.
Think about this : I'm representing a real life object, a Lion through a class. I'd do something like this.
class Lion {
public int legs;
}
Now my class is needed by some other developer to create an object and set its legs field. He'd do something like this
Lion jungleKing = new Lion();
jungleKing.legs = 15;
Now the question is, Java won't restrict him to setting any number more than 4 as the number of legs for that object. It's not an error, and it'll run just fine. But it's a logical blunder, and the compiler won't help you there. This way a Lion may have any number of legs.
But if we write the code this way
class Lion {
private int legs;
public void setLegs(int legs){
if(legs > 4){
this.legs = 4;
}
else this.legs = legs;
}
}
Now you won't have any Lion with more than 4 legs because the policy of updating the fields of the class has been defined by the class itself and there's no way anyone not knowing the policy is going to update the legs field because the only way to update the legs field is through the setLegs() method and that method knows the policy of the class.
Although Konamiman's answer is spot on, I'd like to add that, in the particular case of public setters versus directly exposing public fields you are asking, there is another very important distinction to keep in mind apart from information hiding and decoupling implementation from the public surface, or API, of a class; validation.
In a public field scenario, there is no way to validate the field's value when it's modified. In case of a public setter (be it a Foo {get; set;} property or a SetFoo(Foo value)) method you have the possibility to add validation code and launch required side-effects and this way ensure that your class is always in a valid or predictable state.
What if you do want to a range check before assignment? That's one of the cases I use setters and getters
More or less simple and realistic example I encountered in practice is an Options class, which has a lot of setters and getters. At some point you might want to add new option which depends on others or has side effects. Or even replace group of options with Enum. In this case setA function will not just modify a field, but will hide some additional configuration logic. Similarly getA will not just return value of a, but something like config == cStuffSupportingA.
Wikipedia has a good overview of [mutator methods(https://en.wikipedia.org/wiki/Mutator_method), which is what setter methods are and how they work in different languages.
The short version: if you want to introduce validation or other logic that gets executed on object modification it is nice to have a setter to put that logic in. Also you may want to hide how you store things. So, those are reasons for having getters/setters. Similarly, for getters, you might have logic that provides default values or values that are dependent on e.g. configuration for things like Locale, character encoding, etc. There are lots of valid reasons to want to have logic other than getting or setting the instance variable.
Obviously, if you have getters and setteres, you don't want people bypassing them by manipulating the object state directly, which is why you should keep instance variables private.
Other things to consider include whether you actually want your objects to be mutable at all (if not, make fields final), whether you want to make modifying the object state threadsafe with e.g. locks, synchronized, etc.
Setting fields as private documents a powerful fact: these private fields are only directly used within the current class. This helps maintainers by not having to track down field usage. They can reason better on the code by looking at the class and determining that the effects on and from these fields with the class' environment go through public and protected method calls. It limits the exposure surface on the class.
In turn, defining a "setter" for a private field is not about giving it publicity again. It is about declaring another powerful fact: an object belonging to this class has a property that can be modified from the outside. (The terms object and property are used in the sense of a bounded part of the whole and an observable fact about this part, not in the OOP sense)
Why then declare a "setter" on a field when making the field public would suffice? Because declaring a field not only binds a name to a property of the objects of the class, but also commits to use memory storage for this property.
Therefore, if you declare a "private field with a setter", you declare three things:
You declare that the name you gave to the field/setter cluster represents a property of the object which is of interest when the object is seen as a black box.
You declare that the value of this property is modifiable by the environment of the object.
You declare that in this particular concrete class, the property of the object is realized by committing some memory storage to it.
I advocate that you never make your fields private with getters and setters indiscriminately. Fields are for describing storage. Methods are for interactions with the environment. (And the particular case of "getters" and "setters" are for describing properties of interest)
I'm newbie to Java and I'm learning about encapsulation and saw an example where instance variables are declared as private in a class.
http://www.tutorialspoint.com/java/java_encapsulation.htm
I have 2 queries:
Why are instance variables private? Why not public?
What if instance variables are made public and accessed directly? Do we see any constraints?
Can you explain with an example as to what will go wrong in case the instance variables are declared as public in a class in Java?
Instance variables are made private to force the users of those class to use methods to access them.
In most cases there are plain getters and setters but other methods might be used as well.
Using methods would allow you, for instance, to restrict access to read only, i.e. a field might be read but not written, if there's no setter. That would not be possible if the field was public.
Additionally, you might add some checks or conversions for the field access, which would not be possible with plain access to a public field. If a field was public and you'd later like to force all access through some method that performs additional checks etc. You'd have to change all usages of that field. If you make it private, you'd just have to change the access methods later on.
If phone was private:
Consider this case:
class Address {
private String phone;
public void setPhone(String phone) {
this.phone = phone;
}
}
//access:
Address a = new Address();
a.setPhone("001-555-12345");
If we started with the class like this and later it would be required to perform checks on the phoneNumber (e.g. some minimum length, digits only etc.) you'd just have to change the setter:
class Address {
private String phone;
public void setPhone(String phone) {
if( !isValid( phone) ) { //the checks are performed in the isValid(...) method
throw new IllegalArgumentException("please set a valid phone number");
}
this.phone = phone;
}
}
//access:
Address a = new Address();
a.setPhone("001-555-12345"); //access is the same
If phone was public:
Someone could set phone like this and you could not do anything about it:
Address a = new Address();
a.phone="001-555-12345";
If you now want to force the validation checks to be performed you'd have to make it private and whoever wrote the above lines would have to change the second line to this:
a.setPhone("001-555-12345");
Thus you couldn't just add the checks without breaking other code (it wouldn't compile anymore).
Additionally, if you access all fields/properties of a class through methods you keep access consistent and the user would not have to worry about whether the property is stored (i.e. is a instance field) or calculated (there are just methods and no instance fields).
They don't have to be private - but they should be. A field is an implementation detail - so you should keep it private. If you want to allow users to fetch or set its value, you use properties to do so (get and set methods) - this lets you do it safely (e.g. validating input) and also allows you to change the implementation details (e.g. to delegate some of the values to other objects etc) without losing backward compatibility.
First, it is not true that all instance variables are private. Some of them are protected, which still preserves encapsulation.
The general idea of encapsulation is that a class should not expose its internal state. It should only use it for performing its methods. The reason is that each class has a so-called "state space". That is, a set of possible values for its fields. It can control its state space, but if it exposes it, others might put it in an invalid state.
For example, if you have two boolean fields, and the class can function properly only in 3 cases: [false, false], [false, true], and [true, false]. If you make the fields public, another object can set [true, true], not knowing the internal constraints, and the next method called on the original object will trigger unexpected results.
Making instance variables public or private is a design tradeoff the
designer makes when declaring the classes. By making instance
variables public, you expose details of the class implementation,
thereby providing higher efficiency and conciseness of expression at
the possible expense of hindering future maintenance efforts. By
hiding details of the internal implementation of a class, you have the
potential to change the implementation of the class in the future
without breaking any code that uses that class.
Oracle White Paper
Like has been pointed out by several answerers already, instance variables don't have to be private, but they are usually at the very least not made public, in order to preserve encapsulation.
I saw an example in (I think) Clean Code, which very well illustrates this. If I recall correctly, it was a complex number (as in a+bi) type; in any case, something very much like that, I don't have the book handy. It exposed methods to get the value of the real and imaginary parts as well as a method to set the value of the instance. The big benefit of this is that it allows the implementation to be completely replaced without breaking any consumers of the code. For example, complex numbers can be stored on one of two forms: as coordinates on the complex plane (a+bi), or in polar form (φ and |z|). Keeping the internal storage format an implementation detail allows you to change back and forth while still exposing the number on both forms, thus letting the user of the class pick whichever is more convenient for the operation they are currently performing.
In other situations, you may have a set of related fields, such as field x must have certain properties if field y falls inside a given range. A simplistic example would be where x must be in the range y through y+z, for numerical values and some arbitrary value z. By exposing accessors and mutators, you can enforce this relationship between the two values; if you expose the instance variables directly, the invariant falls apart immediately, since you cannot guarantee that someone won't set one but not the other, or set them so that the invariant no longer holds.
Of course, considering reflection, it's still possible to access members you aren't supposed to, but if someone is reflecting your class to access private members, they had better realize that what they are doing may very well break things. If they are using the public interface, they might think everything is fine, and then they end up with nasty bugs because they unknowingly did not fully adhere to the implementation details of your particular implementation.
In traditional Object-Oriented design, a class will encapsulate both data (variables) and behavior (methods). Having private data will give you flexibility as to how the behavior is implemented, so for example, an object could store a list of values and have a getAverage() method that computes and returns the mean of these values. Later on, you could optimize and cache the computed average in the class, but the contract (i.e., the methods) would not need to change.
It has become more popular the past few years (for better or worse) to use anemic data models, where a class is nothing but a bunch of fields and corresponding getters and setters. I would argue that in this design you would be better off with public fields, since the getters and setters provide no real encapsulation, but just fool you into thinking you are doing real OO.
UPDATE: The example given in the link in the question is a perfect example of this degenerate encapsulation. I realize the author is trying to provide a simple example, but in doing so, fails to convey any real benefit of encapsulation (at least not in the example code).
Because if you change the structure of the class (removing fields etc.); it will cause bugs. But if you have a getX() method you can calculate the needed value there (if field was removed).
You have the problem then that the class does not know if something is changed and can't guarantee integrity.
Well keeping fields private has many advantages as suggested above.
Next best level is to keep them package private using java default access level.
Default level avoid cluttering in your own code and prevents clients of your code from setting invalid values.
For user of class
We, who are using ide like eclipse, netbins.....
saw that it suggest us for public method, so if creator of class provide getter and setter for private instance variable you do not have to memorize the name of variable. just write set press ctrl+space you are getting all of setter method created by creator of that class and choose your desired method to set your variable value.
For creator of class
Sometimes you need to specify some logic to set variable value.
"suppose you have an integer variable which should store 0
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
I want to know when to use get and set methods(getName,setName ) in my class and when simple classVariable.name = "" instead а = classVariable.getName()
Here is example of class using set and get methods
public class ClassExampe {
String name;
String course;
public String getName ( )
{
return name;
}
public void setName (String studentName)
{
name = studentName;
}
public String getCourse ( )
{
return course;
}
public void setCourse (String studentCourse)
{
course = studentCourse;
}
}
Thanks
Using Getters / Setters vs using Fields
As a rule of thumb:
use the variables directly from the same class (actually from the same .java file, so inner classes are ok too), use Getters / Setters from other classes.
The simple rule is: never use direct access (except, of course, when referring to them from inside the class).
field access can't be proxied
you may want to have some event notification
you may want to guard against race conditions
expression languages support setters and getters
theoretically this breaks encapsulation. (If we are pedantic, setter and getter for all fields also breaks encapsulation though)
you may want to perform some extra logic inside the setter or getter, but that is rarely advisable, since consumers expect this to follow the convention - i.e. being a simple getter/setter.
you can specify only a setter or only a getter, thus achieving read-only, or write-only access.
Even if this does not happen that you need any of these, it is not unlikely. And if you start with field access, it will be harder to change.
In Java, using a getter and setter is usually considered best practice.
This is because if you ever need to change your code to do something else when a property is accessed or modified, you can just change it in the existing getter or setter.
I tend to think it causes a bit of clutter for simple objects, but if you have ever had to refactor a public property to a getter and setter to add additional functionality you will see that it can be a pain.
I suspect most will say to always use getters/setters to access private members. It's not necessary, but is considered a "best practice".
One advantage is that you can have more than just simple assignment and returning. Example:
public void setLevel(int lvl)
{
if (lvl<0)
{
this.level=1;
}
else
this.level = lvl;
}
public int getLevel()
{
if (this.someIndicator==4)
return this.level*7.1;
else
return level;
}
Getters and Setters allow you to change the implementation later (e.g. do something more complex), allow you to implement validation rules (e.g. setName throws an exception if the name is not more than 5 characters, whatever.)
You could also choose to add a getter but not a setter so that the variable is like 'read-only'.
That's the theory, however in many cases (e.g. Hibernate using setters) you cannot throw exceptions in setters so you can't do any validation. Normally the value will just be assigned/returned. In some companies I've worked at, it's been mandatory to write getters and setters for all attributes.
In that case, if you want to access an attribute from outside an object, and you want it to be readable/writable, I just use a public attribute. It's less code, and it means you can write things like obj.var += 5 which is easier to read than obj.setVar(obj.getVar() + 5).
If you mean: when to use public accessor methods instead of making the internal, private variable public my answer is "always" unless there is a severe performance reason.
If you mean, call your own get and set methods vs direct access to the vars w/in your class I still say call your own access methods. This way, any conversion, edits or rules you implement as part of get/set get invoked automatically by your own internal calls as well as external callers.
In pure OO languages (for example, Smalltalk) there is no concept of public - all internal vars are private and so you must use accessors. In less pure OO languages, you can make things public - however exposing the internals of your data structures and implementation is an exceptionally bad idea for stability and maintenance in the long run. Look up "tight coupling" for more on this.
Simply put, if you expose internal vars publicly, people can access them directly and if you ever change name or type everything down the line breaks. This is called side effects.
Its a matter of taste, but generally speaking you always should use get/set methods for all properties that are public. But for things like Value Objects (VOs) that you probably are not going to be bothered with for some time you can use public variables without getting too much criticism I think.
In general, you'd want to use setters and getters to give the opportunity to developers reusing your code by modifying it or extending it to add layers of processing and control when accessing and modifying your internal data. This wouldn't be possible in Java when using direct accesses.
Parenthesis: However, it's perfectly possible in other languages, for instance in Scala, when the line between properties and methods can become quite fine. And it's great, as then it doesn't become a coding-problem that gets in the way and it makes usage more transparent.
You can also often consider that in your class you can feel free to access your internal (private or protected) members directly, as you're supposed to know what you're doing, and you don't need to incur the overhead of yet another method call.
In practice, multiple people working on a class might not know what everyone's doing and those lines of integrity checking in your getters and setters might be useful in most cases, while the micro-optimization may not.
Moreover, there's only one way for you to access a variable directly, whereas you can define as many accessors as you want.
Encapsulate the private fields of a class and expose them with getter/setter classes the way you want to.
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
I'm currently working on a simple game in Java with several different modes. I've extended a main Game class to put the main logic within the other classes. Despite this, the main game class is still pretty hefty.
After taking a quick look at my code the majority of it was Getters and Setters (60%) compared to the rest that is truly needed for the logic of the game.
A couple of Google searches have claimed that Getters and Setters are evil, whilst others have claimed that they are necessary for good OO practice and great programs.
So what should I do? Which should it be? Should I be changing my Getters and Setters for my private variables, or should I stick with them?
There is also the point of view that most of the time, using setters still breaks encapsulation by allowing you to set values that are meaningless. As a very obvious example, if you have a score counter on the game that only ever goes up, instead of
// Game
private int score;
public void setScore(int score) { this.score = score; }
public int getScore() { return score; }
// Usage
game.setScore(game.getScore() + ENEMY_DESTROYED_SCORE);
it should be
// Game
private int score;
public int getScore() { return score; }
public void addScore(int delta) { score += delta; }
// Usage
game.addScore(ENEMY_DESTROYED_SCORE);
This is perhaps a bit of a facile example. What I'm trying to say is that discussing getter/setters vs public fields often obscures bigger problems with objects manipulating each others' internal state in an intimate manner and hence being too closely coupled.
The idea is to make methods that directly do things you want to do. An example would be how to set enemies' "alive" status. You might be tempted to have a setAlive(boolean alive) method. Instead you should have:
private boolean alive = true;
public boolean isAlive() { return alive; }
public void kill() { alive = false; }
The reason for this is that if you change the implementation that things no longer have an "alive" boolean but rather a "hit points" value, you can change that around without breaking the contract of the two methods you wrote earlier:
private int hp; // Set in constructor.
public boolean isAlive() { return hp > 0; } // Same method signature.
public void kill() { hp = 0; } // Same method signature.
public void damage(int damage) { hp -= damage; }
Very evil: public fields.
Somewhat evil: Getters and setters where they're not required.
Good: Getters and setters only where they're really required - make the type expose "larger" behaviour which happens to use its state, rather than just treating the type as a repository of state to be manipulated by other types.
It really depends on the situation though - sometimes you really do just want a dumb data object.
You've already had a lot of good answers on this, so I'll just give my two cents. Getters and setters are very, very evil. They essentially let you pretend to hide your object's internals when most of the time all you've done is tossed in redundant code that does nothing to hide internal state. For a simple POJO, there's no reason why getName() and setName() can't be replaced with obj.name = "Tom".
If the method call merely replaces assignment, then all you've gained by preferring the method call is code bloat. Unfortunately, the language has enshrined the use of getters and setters in the JavaBeans specification, so Java programmers are forced to use them, even when doing so makes no sense whatsoever.
Fortunately, Eclipse (and probably other IDEs as well) lets you automatically generate them. And for a fun project, I once built a code-generator for them in XSLT. But if there's one thing I'd get rid of in Java, its the over-dependence on getters and setters.
Getters and setters enforce the concept of encapsulation in object-oriented programming.
By having the states of the object hidden from the outside world, the object is truly in charge of itself, and cannot be altered in ways that aren't intended. The only ways the object can be manipulated are through exposed public methods, such as getters and setters.
There are a few advantages for having getters and setters:
1. Allowing future changes without modification to code that uses the modified class.
One of the big advantage of using a getter and setter is that once the public methods are defined and there comes a time when the underlying implementation needs to be changed (e.g. finding a bug that needs to be fixed, using a different algorithm for improving performance, etc.), by having the getters and setters be the only way to manipulate the object, it will allow existing code to not break, and work as expected even after the change.
For example, let's say there's a setValue method which sets the value private variable in an object:
public void setValue(int value)
{
this.value = value;
}
But then, there was a new requirement which needed to keep track of the number of times value was changed. With the setter in place, the change is fairly trivial:
public void setValue(int value)
{
this.value = value;
count++;
}
If the value field were public, there is no easy way to come back later and add a counter that keeps track of the number of times the value was changed. Therefore, having getters and setters are one way to "future-proof" the class for changes which may come later.
2. Enforcing the means by which the object can be manipulated.
Another way getters and setters come in handy is to enforce the ways the object can be manipulated, therefore, the object is in control of its own state. With public variables of an object exposed, it can easily be corrupted.
For example, an ImmutableArray object contains an int array called myArray. If the array were a public field, it just won't be immutable:
ImmutableArray a = new ImmutableArray();
int[] b = a.myArray;
b[0] = 10; // Oops, the ImmutableArray a's contents have been changed.
To implement a truly immutable array, a getter for the array (getArray method) should be written so it returns a copy of its array:
public int[] getArray()
{
return myArray.clone();
}
And even if the following occurs:
ImmutableArray a = new ImmutableArray();
int[] b = a.getArray();
b[0] = 10; // No problem, only the copy of the array is affected.
The ImmutableArray is indeed immutable. Exposing the variables of an object will allow it to be manipulated in ways which aren't intended, but only exposing certain ways (getters and setters), the object can be manipulated in intended ways.
I suppose having getters and setters would be more important for classes which are part of an API that is going to be used by others, as it allows keeping the API intact and unchanged while allowing changes in the underlying implementation.
With all the advantages of getters and setters said, if the getter is merely returning the value of the private variable and the setter is merely accepting a value and assigning it to a private variable, it seems the getters and setter are just extraneous and really a waste. If the class is going to be just for internal use by an application that is not going to be used by others, using getters and setters extensively may not be as important as when writing a public API.
They absolutely are evil.
#coobird unfortunately they absolutely do not "enforce the concept of encapsulation", all they do is make you think you're encapsulating data when in fact you're exposing data via a property with delusions of method grandeur. Anything a getter/setter does a public field does better.
First, if you want public data, make it public, get rid of the getter & setter methods to reduce the number of methods the client has to wade through and make it cognitively simpler for the client to change it's value by eg.
object.field = value;
instead of the more cognitively intense
object.setField(value);
where the client must now check the getter/setter method to see if it has any side-effects.
Second, if you really need to do something else in the method, why call it a get/set method when it's got more responsibilities than simply getting or setting?
Either follow the SRP or call the method something that actually tells you what the whole method does like Zarkonnen's examples he mentioned eg.
public void kill(){
isAlive = false;
removeFromWorld(this);
}
instead of
public void setAlive(boolean isAlive){
this.isAlive = isAlive;
if (isAlive)
addToWorld(this);
else
removeFromWorld(this);
}
where does the setAlive(boolean) method tell the client that as a side-effect it'll remove the object from the world? Why should the client have any knowledge about the isAlive field? Plus what happens when the object is re-added to the world, should it be re-initialised? why would the client care about any of that?
IMHO the moral is to name methods to say exactly what they do, follow the SRP and get rid of getters/setters.
If there's problems without getters/setters, tell objects to do their own dirty work inside their own class instead of trying to do things with them in other classes.
here endeth my rant, sorry about that ;)
It's a slippery slope.
A simple Transfer object (or Parameter object) may have the sole purpose of holding some fields and providing their values on demand. However, even in that degenerate case one could argue that the object should be immutable -- configured in the constructor and exposing only get... methods.
There's also the case of a class that exposes some "control knobs"; your car radio's UI probably can be understood as exposing something like getVolume, setVolume, getChannel, and setChannel, but its real functionality is receiving signals and emitting sound. But those knobs don't expose much implementation detail; you don't know from those interface features whether the radio is transistors, mostly-software, or vacuum tubes.
The more you begin to think of an object as an active participant in a problem-domain task, the more you'll think in terms of asking it to do something instead of asking it to tell you about its internal state, or asking it for its data so other code can do something with those values.
So... "evil"? Not really. But every time you're inclined to put in a value and expose both get... and set... methods on that value, ask yourself why, and what that object's reponsibility really is. If the only answer you can give yourself is, "To hold this value for me", then maybe something besides OO is going on here.
Your Game class is probably following the god object antipattern if it exposes that many variables. There's nothing wrong with getters and setters (though their verbosity in Java can be a bit annoying); in a well-designed app where each class has a clearly separated functionality, you will not need dozens of them in a single class.
Edit: If the main point for the getters and setters is to "configure" the game classe (I understand your comment that way), then your probably don't need the getters (it's perfectly fine for a class to access its own private variables without using get methods), and you can probably collapse many of the setters into "group setters" that set several variables which belong together conceptually.
The presence of getter and setters tends to indicate (a "smell" if you are into that sort of primary school language) that there is a design problem. Trivial getters and setters are barely distinguishable from public fields. Typically the code operating on the data will be in a different class - poor encapsulation, and what you would expect from programmers not at ease with OO.
In some cases getters and setters are fine. But as a rule a type with both getters and setters indicates design problems. Getters work for immutability; setters work for "tell don't ask". Both immutability and "tell don't ask" are good design choices, so long as they are not applied in an overlapping style.
My opinion is that getters and setters are a requirement for good programs. Stick with them, but don't write unnecessary getters/setters - it's not always necessary to directly deal with all variables.
I don't really think they are evil. But I would love to live in a world where I never had to use them unless I really needed to.
One example I read above was future-proofing your code. For example:
public void setValue(int value)
{
this.value = value;
}
Then, the requirements change and you need to track how many times the value was set.
So:
public void setValue(int value)
{
this.value = value;
count++;
}
This is beautiful. I get it. However, in Ruby, would the following not serve the same purpose?
someobject.my_value = 100
Later, you need to track the number of times my_value was set. Well then, could you not just override the setter THEN and only THEN?
def my_value=(value)
#my_value = value
#count++
end
I'm all for beautiful code but I have to admit, looking through the mountains of Java classes we have and seeing literally thousands and thousands of lines of code that are NOTHING but basic getter/setters is ugly and annoying.
When I was developing in C# full time, we used public properties all the time and did custom getters/setters only when needed. Worked like a charm and it didn't break anything.
As always the only answer is: it depends. If you are the only peron touching the code, you can do anything you're comfortable with, including taking shortcuts.
One of the benefits of using setters is that checks need to be performed at only one location in your code.
You might want to pay some closer attention to what is actually being get and set by these methods. If you're using them to provide access to constant values you are probably better off by using constants.
This depends on the programming language in question. Your question is framed in the context of Java, where it seems that getters and setters are generally thought of as a good thing.
In contrast, in the Python world, they are generally considered as bad style: they add lines to the code without actually adding functionality. When Python programmers need to, they can use metaprogramming to catch getting and/or setting of object attributes.
In Java (at least the version of Java I learned slightly a decade ago), that was not possible. Thus, in Java it is usually best to use getters and setters religiously, so that if you need to, you can override access to the variables.
(This doesn't make Python necessarily better than Java, just different.)
Just FYI: In addition to all the excellent answers in this thread, remember that of all reasons you can come up with for or against getters/setters, performance isn't one (as some might believe). The JVM is smart enough to inline trivial getters/setters (even non-final ones, as long as they aren't actually overridden).
You may want to replace some of your classes by value classes. This will allow you to remove the getter and avoid problems when the content is changed from under you.
If you need external access to individual values of fields, use getters and/ or setters. If not, don't. Never use public fields. It's as simple as that! (Ok, it's never that simple, but it's a good rule of thumb).
In general you should also find that you need to supply a setter much less often than a getter - especially if you are trying to make your objects immutable - which is a Good Thing (but not always the best choice) - but even if not.
I've been programming in java for few monts ago, and I've learned that we should use getters & setters only when it's necessary for the application
have fun :)