Are setter methods only used to set the value of attributes as it is passed as argument? Can we write some validation logic before assigning the value to the attributes?
Yes, validation logic is definitely acceptable.
It should be noted though that if you have extensive validation you might want to extract this to a specific validator service. But for simple validations you can safely do this.
The entire idea behind using getters & setters is so nobody will have direct access to your fields. If you just wanted to set/get the value, you can make them public.
Instead, we use setters to validate the incoming data and see if it complies with the rules we set.
This concept is also called "Encapsulation", a cornerstone of Object-Oriented Programming.
Yes, you can add validation logic in your setter attributes before assigning the values. In fact, you must do it if it is possible that unwanted values may be sent to the setters.
Sure. You can include a validation. It is acceptable, but not neccessary. You just have to take into account that if you don't validate it then any values will try to get set to the variable (meeting the data type requirements).
Basically if you have
public void setNickname(String nick)
{
this.nickname = nick;
}
and you want to validate it you can either do it inside the setter - for example
public void setNickname(String nick)
{
if(nick.matches("[a-zA-Z]+"){ // only letters
this.nickname = nick;
}else{
// react
}
}
or outside of the setter before using it
if(nick.matches("[a-zA-Z]+"){ // only letters
account.setNickname(nick);
}
or you can use a method to validate it or even a separate validator class. There are a lot of possibilities.
You don't have to be afraid of developers being dazzled by this, like some say here.
It is actually encouraged to validate the input (check whether it fits your data abstraction) to your setter method, so yes you can.
Sure, there's nothing wrong with making setters only accept valid values.
As long as you do not modify other fields of class it is correct to validate.
You should also consider removing setters and using constructor with valitation or builder in Joshua Bloh version
There is absolutely nothing stopping you from doing any kind of other operation inside a setter of a property. You could do anything from validation to setting the value of some other property etc. etc. Thats not to say you should however. Use your good judgement and common sense to decide what to put in there. If the setter is bulked out with innumerable lines of code then you should question your program structure...
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)
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.
Looking at some code cleanup and I was wondering the best way to deal with this:
Have a class with some private variables like:
myBool1, myBool2, myBool3
myInt1, myInt2, myInt3
myString1, myString2, myString3
What's the best way to do a getter function that is generic to the return value? So if I do a call to the getter with something like:
myNewBool=<blah>.get("myBool1")
myNewString=<blah>.get("myString2")
myNewInt=<blah>.get("myInt3")
Anyone have any suggestions?
You can't really have a generic getter if you don't know what you want to get, for example :
boolean myNewBool= get("myString1");
If get returns something, but you don't really know if this something is compatible with a boolean, and terrible things could happen.
You could try this:
public <T> get(String element){
return (T) elementToGet;
}
But you would have to specify the return type when you call the get method.
String element = myObject.<String>get("element");
Here are the bad sides :
You can't work directly with primitives
You can have a lot of ClassCastException
If you misspell an attribute name you won't see it until you run it
You don't expose a nice public API, people would have to know evert possible attribute to use it, and as said above, a misspelled attribute (or an inexistant one) wouldn't be seen until runtime.
You have to know the return time and type it each time you use your method
You would have to type a really long (and smelly) code in your get method either to use each possible attribute (if you still want have some private and not accessible) or worse, use reflection to find the right attribute.
So definitively not a good idea.
What you can do instead is using the good old getters//setters and if there is a lot of them, generate them with your IDE.
Another way would be to use the project lombok.
Resources :
Project Lombok
On the same topic :
Create automatically only getters in Eclipse
Eclipse Generate All getters setters in package
Java Getters and Setters
First you should ask what would be the pros and cons of such a solution.
Pros:
One method instead of many
Cons:
Non-intuitive to the users of your class (classical getters are more common)
You cannot have an overload that only differs by a return type, therefore you will have to have methods like getBool, getInt etc.
It's slower - you have to pass the string, check for validity, do a lookup in a map...
The only advantage of your proposed solution would be not repeating the get()/set() code. However, as these methods are usually generated by your IDE and contain only a single-line command, I wouldn't see that as a big problem.
To answer your actual question - you can create a HashMap with name-attribute mapping. Alternatively, you may use Java reflection to access the attributes. The second solution is more general but also harder to write.
This is really a terrible idea. I'm not sure why creating a getter/setter for each private variable is a problem, but passing around strings that map to a variable's symbolic name would be hard to maintain and confusing. You don't need this to be generic; each variable represents a different quantity and they should be accessed as such.
It wouldn't be clean up but mess up. I'd either created 3 getter methods for the fields or redesign it completely. But calling a function, with a name of a field to return, as an argument can bring nothing good.
When you code, you must be refactoring your code for all the time you are coding. But not like this. Solution is delegating logic to another class, wrapping code into more utilizable methods or changing and simplifying domain objects...
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.