This question already has answers here:
Java Conventions: use getters/setters WITHIN the class?
(11 answers)
Closed 6 years ago.
Suppose I have a class Circle with a data member float radius. I have a getter and setter method as getRadius() and setRadius(float r). I use the latter to assign the radius value. Now, after the assignment, should I use the value of radius in calculations (in a method called areaCircle()) by directly accessing it or should I call the getter method instead?
You can just use radius as it's defined within the same class. Get and set methods are for getting or setting a variable from another class/object.
You can, and really, you ought to use the class field radius directly.
Having "getters" and "setters" by rote achieves little more than code bloat and a defeat of encapsulation. It's also makes your code less thread safe: what happens if one thread is computing the area while another is changing the radius through the "setter"? It can even, on occasions, be harmful: a child class might override the "getter" or "setter"; remember that all non-static functions are "virtual" in Java.
It's far better is to set all your fields in a constructor, and provide a "getter" if you really must.
And we're no longer in the 1970s. Stop using float. It's probably slower than a double due to internal conversions to and from the latter.
It depends on whether or not you have declared radius private. If you use getters and setters to access it you should have declared radius private because else the encapsulation is broken.
an exception to this might be when the method "areaCircle()" you mentioned is in the same class, in that case it will be able directly access the private radius attribute without the need for using getters and setters.
FYI:
http://www.tutorialspoint.com/java/java_encapsulation.htm
If your value may vary overtime (for example a timer) then use the getter.
If exists getters and setters, then should be used always even inside class. Of course if getter and setter do something more in method then it must be considered if it fullfils Your needs.
Should be used not means must be used. You can use property radius directly ( only inside class if property is private - and should be ) but in good practice is to use getter and setter.
So using property directly is possible, but I recommend use get and set because it give more flexibility and can do something more than tipical assign or get.
For example if in first place setter only sets something, but after a while setter is changed to do something more.
setName(name){
this.name="name";
}
So in code setName("John"); is equal name="John". But imagine that after a while we want to set another property when name is set:
setName(name){
this.name="name";
this.nameIsSet=true;
}
another example ( Listener pattern ):
setName(name){
this.name="name";
this.listener.nameChanged(this.name); //we call listener that variable changed
}
Then programmer needs to find every assigment like name="John" in class and refactor it to new behavior. If only setName is used then no code change must be done.
Of course everything depends from need and is possible that setting, getting property from outside do something more and different and it not fullfils our need inside class.
If you create a private method you can use the radius without getters or setters, but in public mehtodes it's better to use getters and setters.
If it's possible i would use getters and setters. These are better and you will get as less errors as without them.
Related
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)
This question already has answers here:
Why are getter and setter method important in java? [duplicate]
(6 answers)
Closed 8 years ago.
If I create a class in Java, I've always been taught that the convention is to make all fields of a class private. If I need to access or change them, I can create an accessor and mutator method. I do understand the importance of private variables, as they help reduce complexity and allow for encapsulation.
What I don't understand is that if I create a public accesor and mutator method, isn't the variable public at that point? Why is it still convention to use private variables in situations where anyone can access them?
I should also note that I understand the important of these methods, but I would like to know why we bother to make the variable private even though we are giving anyone access to it through those methods?
Yes, you're right, it does effectively make the variable public. But there's one important difference, which is that it gives you the ability to change things later on: you can remove the setter if you want, or make it private, without affecting code that reads from the field using the getter.
If you'd just made the variable public, you wouldn't be able to stop writes to the field without also breaking reads from the field.
It has other advantages. You can make the access synchronized if you want to later on, without breaking client code, for instance. In short, it allows lots of modifications later on that wouldn't otherwise be possible without causing lots of breakages in code that uses the class.
And you can add extra logic that logs whenever someone writes to the field, or prevents certain threads from writing, or whatever... you can change the type of a field from a HashMap to a TreeMap if your getter abstracts it away and just returns a Map... etc.
Private fields are considered to be internal to the object. So the outside world doesn't need to know about how the data is stored inside the object. This means you can easily change the internal representation of data of an object while everyone else still uses the same accessors / mutators to do its work.
It's also possible that accessors / mutators perform validation and other steps that are needed internally for the object but that you don't wish to expose to code that uses the object.
You could make all fields public but that limits your ability to change the internal structure of the object later on when a lot of code now depends on a field being named a certain way.
I am learning get and set methods, I was just wondering if these can only be public, and do they need to be written for every instance variable in a class?
No.
Many internal variables should never be edited, such as states of computations.
If a field is private and has no getter/setter, it is that way for a reason and is acceptable as long as you don't need to access it outside the class.
If it is public, there's no point, and if protected, it's per-package or subclasses not necessarily in the same package.
Without a modifier, it's package-private.
If you want to make a field private and the getter/setter controlled you can use access levels as well.
On that note, if you want, you can perform validation inside a setter to ensure only acceptable values are set. Then, you can either silently reject, return false if the setter is a boolean, or throw an exception in severe circumstances.
I am assuming you are talking about encapsulation.
The whole point of these methods is for them to be public so that they can pass the value of your variable somewhere else in the application.
For achieving this with many variables, you may consider using 'listeners' (Observer Pattern Theory) which are basically custom interfaces that work with a custom class that contains many of these get and set methods.
More on encapsulation:
http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
More on Observer Pattern Theory
http://www.youtube.com/watch?v=UEtyGP994X0
You need to have public getters and setters for your object to function as a JavaBean.
If you don't have a JavaBean requirement for your objects, then you don't need/have to provide public getters ( and especially setters ) in your classes.
Get and set methods in Java are just normal methods. They don't have to be public, but they wouldn't be very useful if they weren't public.
They don't need to be written for every instance variable in a class. If there are instance variables whose values depend on other values, then it may not make sense for them to have setters, e.g. a totalPrice instance variable that depends on a quantity instance variable.
If you want instance variables that shouldn't change, i.e they are immutable, then don't provide any set methods at all.
These methods provide your interface to the caller. They provide the operations on your object that you allow, so that the caller can't set your values to an invalid state, e.g. a count of -1 or a latitude of 91 degrees. This is "encapsulation", or hiding your object's implementation from your caller.
There is no java rule for making getters and setters public but these are made public for a reason.The point of getters and setters is that only they are meant to be used to access the private varialble, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.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.
A good article on the usage of getters and setters:
http://java.dzone.com/articles/getter-setter-use-or-not-use-0
Basically Yes, and No.
Yes, Get and Set methods (also called "getters" and "setters" or accessor methods) should almost always be public (although they can be otherwise -- there's a difference between can and should). The point of getters and setters is usually so other classes can access the encapsulated instance variables.
Exeptions:
You might make an accessor method to be protected if you only want child
classes or other classes in the same package to have access to those
methods.
You might use a private (or protected) setter if you want to
use special logic to set a variable (like concatenating it)
and you don't want other classes to be able to set the
variable.
No, they shouldn't always have accessors. Sometimes a variable should only have a getter (for instance, if that variable is final), and sometimes a variable shouldn't be accessed at all, and therefore you would not give it any accessor methods.
Get and set methods were designed originally for JavaBeans, classes stylized so IDEs and application programs can detect what properties the classes have and what event listeners they support. Through a limited version of reflection called introspection, tools can analyze the classes, and even if the programmer did not want to use is/get/set methods he could write BeanInfo classes that tell what methods be used instead.
Look at the Javadoc for java.beans.Introspector. and java.beans.BeanInfo. This provides ways to document additional information, including methods exposed to other tools and metadata about properties. For example, a TemperatureGauge class could expose the minimum and maximum temperature so a Swing program can set the limits of a slider without the programmer looking the information up.
Still, one should not expose more than one has to expose. You may need to limit access to getters and setters. You may need them for database tools, but you may not want ordinary programming to touch properties. This leads to ideas like OSGI or proxies where methods are limited to specific packages.
For example, one common tactic is to have getters only, to mark variables final, and build objects in the constructor. For example,
public final class Complex {
private final double re;
private final double im;
public Complex(double re, double I'm) {
this.re = re;
this.im = im;
}
public double getReal() {
return re;
}
// more getters, arithmetic, etc.
}
Note that I named the method slightly differently than the variable; that's okay.
On the other hand, there is a style of programming where one eschews getters and writes methods that tell the object what to do. Consider a Name class with givenName and surname instance variables. Then, add this method:
public void writeFormally(Appendable app) {
app.append(surname)
.append(", ")
.append(givenName);
}
You see this sometimes in Model-View-Presenter systems, like GWT and its HasText interface.
Unless you are writing code that deals with dependency injection systems or that use reflection to have your objects communicate with database, don't worry about the specifics of getters and setters. Just do what comes naturally and limit your objects' exposures. Also, every time you are tempted to write:
x.getA().getB().getC().setZ(42);
Rewrite the code to get rid of the chain of gets and sets. Look up the Law of Demeter in The Pragmatic Programmer.
Use protected if you want only child classes to access the field. However, if you want other classes to access the field, public is the way to go. Your decision should be based on the scope of access.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are Getters and Setters evil?
I can't find a logical reason behind having a private variable with a getter and a setter that does nothing but directly handling the value being preferable to having a public variable.
Am I missing something?
Because,
Validation is one reason. Keeping the field name out of the public API also allows you to change it later without breaking the API. And it allows you to change the class later in other ways as well, e.g. moving the field to some other class (so that the public setter would call a setter in a different class). Having the setter called also allows you to do other things, e.g. notify interested other components of the change of value. None of this would be possible if the field was accessed directly.
They are preferred to future proof the code. In the future if you want to eliminate the variable or use another variable to derive this variables value - the change is simpler. You just need to change the getter/setter, the rest of the code remains unaffected. This is not the case with direct access to the variable.
As #user370305 already mentioned one reason is validation.
Other reason is types conversion. Setter may accept string and parse it to integer.
Yet another reason is data encapsulation. It is not necessarily to have a simple filed stored in the same class. Method setName(String) of class Person may store the name in more complicated data structure. Using simple field does not allow you to change the internal implementation of class Person without affecting code that uses it.
EDIT:
yet another technical reason.
It is much easier to discover and debug code with getters and setters. If some field is changed unexpectedly you can just toggle break point into appropriate setter and find the problem very quickly. If this field is public and you have 1000 references to this field you theoretically have to put 1000 breakpoints in all these places.
1. Encapsulation has different use in different context, In design patterns its like behaviors that keeps changing needs to be encapsulated in abstract class, or interface.
2. Having private instance variable and public getter setter is b
3. Its mainly done to Validate the input from the user... Setting the value to an instance variable directly is dangerous.
Eg:
int dogAge;
System.out.println("My dogs age is :"+dogAge);
Now what if someone gives a negative age... then.......???
So we must do it this way...
int dogAge;
public void setAge(int age){
if (age>0){
dogAge = age;
}
else{
System.out.println("Not a valid age");
}
}
public int getAge(){
return dogAge;
}
System.out.println("My dog age is :"+ getAge());
Its simple .. if you make those variable public then you give rights for ading any values to them .
But if you do that via getter or setter ... you can put checks over it and control the input or conversion without letting the end user know that
eg :
getName(){
return firstName+lastName;
}
or
getData(){
// code to convert byte to Mb or whatever you like to represent
}
Use of accessors to restrict direct access to field variable is preferred over the use of public fields, however, making getters and setter for each and every field is overkill and considerd as not a good practice. It also depends on the situation though, sometimes you just want a dumb data object. Accessors should be added for field where they're really required. See this link to know more about it Getter Setter: To Use or Not to Use.
I can't find a logical reason behind having a private variable with a getter and a setter that does nothing but directly handling the value being preferable to having a public variable.
Consider that any additional code that you put into getters and setters adds to complexity and also needs to be tested. For a small system which is fully controlled by you, there may be little benefit in using getters and setters. Use your professional judgement. You may not need the future proofing and added complexity. Or it may be more important to you to have the efficiency and simplicity of direct access.
Personally, I think that getters and setters are over-used. For a small system which is fully controlled by you, direct access may be the way to go.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the point of setters and getters in java?
I have a question about set method. Please provide some details if possible.
I want to know why do we use set method with class name.
public class Mymainclass {
Private class ClassC {
Private Mysecondclass sec = null;
public void setMymainclass(Mysecondclass second){
Mymainclass.sec= second;
}
}
}
Is it just setting the sec variable value ? if yes why there is class name with set?
It seems like you are confusing a "class constructor" with a "setter method" in a class.
The primary reason for a constructor is to intialize the class variables
The primary reason for a setter method is to access private variables inside the clas
So in your case the name of the method should be "setSec" rather than setMainClass.
That is if you would like to modify the private variable "sec" after you have initialized the class then you can choose to use a setter method.
On the other hand you can also not use a setter method and just have the sec variable be initialized when the class is first created. To do that you will have to create a constructor.
Your constructor for this class will look like this:
Mymainclass(Mysecondclass sec){
this.sec = sec;
}
This way you can pass is a Mysecondclass object as soon as you create a new instance of Mymainclass.
Also try to make sure when you label classes to make each word in the class name to have its first letter capital like this: MySecondClass and MyMainClass!!
Firstly your method should be called "setSeconds" if you follow good practice. Just think how confusing it would be if you added a minutes member to your class.
There are two main reasons for coding setters and getters.
The first is purly pragmatic. If you want to invoke the magic of introspection and java beans then you need to follow these conventions. There are several libraries/APIs like FreeMarker that absolutly depend on haveing getter and setter methods in your class.
The second has more to do with good design. Consider thet you have a public member called seconds. Any user of you class could set this by coding.
instanceOfYourClass.seconds = 60;
This is just fine except maybe you want to impose an arbitary limit of 42 seconds on this value. To validate the value and set it a max of 42 seconds you now need a method to do this. So every user of you class must now change thier code to:-
instanceOfYourClass.setSeconds(60);
So by building in getters and setters from the start you are building in both the flexibilty to do more exotic things within your class, while at the same time providing a stable interface to your class users which wont rquire them to change thier code every time there is a small change in functionality.
I think part of the source of your confusion is that the example you gave is bad code! You don't name a setter based on the class of its argument, you named it based on the property of the object that you're setting. e.g., the canonically 'correct' version of your example would be:
public class Mymainclass {
private Mysecondclass sec= null;
public void setSec(Mysecondclass second){
this.sec= second;
}
}
Having setters that map to property names allows all kinds of different frameworks from UI to persistence and all in between to manipulate your objects in an abstract way. If you tell, for example, your database layer that the property named 'sec' maps to a particular database column, it can use reflection to find the method named "setSec" and set it for you!
The idea of having lots of methods just named 'set' also breaks down when you have lots of properties of the same type, lots of Strings, lots of BigDecimals, whatever. It would be really wierd if there were two standards to only use 'set' when you can and use the property name when you have to. (and you'd find yourself refactoring away those 'set' only methods awfully often.)
In object oriented programming, a good practice is to expose getters and setters to allow other class to interact with a class content instead of making member variables public.
Even if most of the time, at least in the very first version of the class, there won't be much more there than the actual assignment statement, this will allow you to add other behaviors later:
add logging traces to know when and how a new value has been set
do some controls/transformations on the value that is passed before really assign it (what if the other class provided null ?)
trigger some other actions that could be necessary whent this new assignment is done
...