why we use set method [duplicate] - java

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
...

Related

Encapsulation - why do we need it when setters are already public? [duplicate]

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)

Java set properties by string key [duplicate]

I have a class that has many settable/gettable attributes. I'd like to use reflection to set these attributes, but I have 2 questions about my implementation
Here is some stripped down code from my class
class Q {
public String question_1;
public String question_2;
public String question_3;
public String answer_1;
public String answer_2;
public String answer_3;
//etc. etc. Many String attributes
// … constructor and other stuff are omitted
// here is my method for "dynamically" setting each attribute
public void set_attribute(String a_raw_string, String my_field) {
try {
Class cls = Class.forName("com.xyz.models.Q");
Field fld = cls.getField(my_field);
fld.set(this, a_raw_string);
}
catch (Throwable e) {
System.err.println(e);
}
}
I then set various fields like this:
Q q = new Q();
q.set_attribute("abcde", "question_1");
q.set_attribute("defgh", "question_2");
// etc.
This works (i.e., the instance variables are set when I call set_attribute.
However, they only work when the instance variables are declared public. When they are declared private I get a NoSuchFieldException
QUESTION 1: Why do I get that error when the fields are private? My naive assumption is that since the set_attribute function is part of the class, it should have unfettered access to the instance variables.
QUESTION 2: I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way). Is there a more recommended approach?
The reason that I want to use reflection is because it's a pain in the ass to declare a ton of setter methods…so I'm wondering if someone has solved this annoyance in a better way.
Thanks!
I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way)
Yep. Reflection is fairly slow and should only be used as a last resort. If this is simply to avoid having so much redundant code, consider using automatic code generation. For pure data objects, I would strongly recommend using protocol buffers; it will generate the getters / setters (you only need to declare the fields). Plus it allows for easy communication of the data between C++, Java, and Python.
If you have a class that has a lot of fields but isn't a pure data object... well
You should consider whether all the fields should be mutable. (Do you really need setters?)
Whether the fields should even be visible. (Do you need any accessors at all?)
It is often a good idea to make fields "final", initialize them in the constructor(s), and provide no access or provide limited access through an implemented interface.
Using setter methods is the accepted way to set values for class member variables, reflection should definitely not be used for that as the code will be harder to understand and run much more slowly.
Most IDEs (eg Eclipse or NetBeans) include tools for automatically creating getter and setter methods for a class's fields.
When they are private you need to call fld.setAccessible(true);
Yes, why don't you just set the fields directly and avoid reflection? It doesn't look like you're doing anything dynamic. It's just that they are private -- why? Perhaps you mean to expose getters/setters and make the fields private? If so, then you should just invoke the public setters.

Return & print field value or just print value through class method?

I'm currently learning Java and learning about encapsulation and I'm unsure which of the following is a better practice:
Use a getter to return a field value from one class to another and then print it through a method in another class.
Call a method in a class from another class to print the value of the field.
The value isn't manipulated, only shown through System.out.println();
Any advice would be appreciated :)
EDIT: One class (Person) holds information about people, such as name, age, weight etc. and another class (Directory) has a method used to search through a LinkedList of people to find a object with a matching age. If a person is found, then the method prints out the name of the person.
Encapsulation is all about maintaining a separation of concerns, the core idea of which is that one class should know as little as possible about how other classes work, partly so that you can make changes to those classes without having to change other classes that interact with them.
Broadly: As a rule of thumb, you want each of your classes to do "it's own little thing" - to have its own little concern, with all the logic that goes into doing that little thing encapsulated in private methods of that class. If other classes, in the course of doing their own little things, need to know things from the first class, then you provide getter methods in that class that expose those things without exposing the details of how they are implemented internally.
With respect to your question specifically, the options you mention are actually the same thing: A getter is a method that gets called by other classes to return the value of a field. The advantage of such a method is that it encapsulates that field in the class that contains it, which can then parse/recalculate/store or otherwise interact with that field however it pleases, as long as it's getter returns the expected data type.
To illustrate, imagine you create a BankAccount class with a double balance field. You do a few tests and it seems to work fine, so you create several other classes that reference this balance field. At some point, you notice that some of your calculations are coming up a few cents off. You do some research and find out that it's a bad practice to use double to store monetary values, and that you should be using a class called BigDecimal instead.
If your other classes accessed your balance field directly, they would all have to change (and all would have to import BigDecimal even though they never use it directly) in order to facilitate this change. On the other hand, if they access an account's balance by way of a getter method, you can change the type of balance to BigDecimal in BankAccount
while leaving the return type of getBalance() as double, by calling BigDecimal's toDouble() method to return the double value your other classes expect: None of your other classes will ever know you've changed the data type.
Another way of stating the idea of separation of concerns is to say that each class should have a single reason to change (this is the single responsibility principle referenced in #GregKopff's comment): Needing to change the data type of the balance field is a valid reason for BankAccount to change, but would it be a valid reason or all the other classes that interact with it to change? Should you have to change your BankAccountHolder or BankEmployee class because a technical detail in the Account class changed?
This might not seem to answer your question directly, but I think the only answer to this question in general is to illustrate the question you should ask yourself to answer it each time you come across it... which will happen just about every time you write a class.
If my illustration is unclear, please let me know how I can clarify it: You've asked an important question, and it's important that you grasp the answer to it (as well as what you're asking.)
My suggestion would be to use Getters and Setters. Getters are public methods which returns the value of their respective fields. Setters are public methods which sets the value of their respective fields.
public class YourClass {
private String yourMember;
public String getYourMember() {
return this.yourMember;
}
public void setYourMember(String member) {
this.yourMember = member;
}
}
And use these methods to get or set the values of the variable.
public class AnotherClass {
public void someMethod() {
YourClass yc = new YourClass();
yc.setYourMember( "Value" );
System.out.println( yc.getYourMember() );
}
}
But if printing the value is part of the behavior of the class, then it would be better if you add a printYourMember() method also to your class. This really is a context sensitive question. Without knowing the actual context, I can not give more specific answer.
Good Luck!

Why are private variables with handlers encouraged? [duplicate]

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.

Java Reflection to set attributes

I have a class that has many settable/gettable attributes. I'd like to use reflection to set these attributes, but I have 2 questions about my implementation
Here is some stripped down code from my class
class Q {
public String question_1;
public String question_2;
public String question_3;
public String answer_1;
public String answer_2;
public String answer_3;
//etc. etc. Many String attributes
// … constructor and other stuff are omitted
// here is my method for "dynamically" setting each attribute
public void set_attribute(String a_raw_string, String my_field) {
try {
Class cls = Class.forName("com.xyz.models.Q");
Field fld = cls.getField(my_field);
fld.set(this, a_raw_string);
}
catch (Throwable e) {
System.err.println(e);
}
}
I then set various fields like this:
Q q = new Q();
q.set_attribute("abcde", "question_1");
q.set_attribute("defgh", "question_2");
// etc.
This works (i.e., the instance variables are set when I call set_attribute.
However, they only work when the instance variables are declared public. When they are declared private I get a NoSuchFieldException
QUESTION 1: Why do I get that error when the fields are private? My naive assumption is that since the set_attribute function is part of the class, it should have unfettered access to the instance variables.
QUESTION 2: I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way). Is there a more recommended approach?
The reason that I want to use reflection is because it's a pain in the ass to declare a ton of setter methods…so I'm wondering if someone has solved this annoyance in a better way.
Thanks!
I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way)
Yep. Reflection is fairly slow and should only be used as a last resort. If this is simply to avoid having so much redundant code, consider using automatic code generation. For pure data objects, I would strongly recommend using protocol buffers; it will generate the getters / setters (you only need to declare the fields). Plus it allows for easy communication of the data between C++, Java, and Python.
If you have a class that has a lot of fields but isn't a pure data object... well
You should consider whether all the fields should be mutable. (Do you really need setters?)
Whether the fields should even be visible. (Do you need any accessors at all?)
It is often a good idea to make fields "final", initialize them in the constructor(s), and provide no access or provide limited access through an implemented interface.
Using setter methods is the accepted way to set values for class member variables, reflection should definitely not be used for that as the code will be harder to understand and run much more slowly.
Most IDEs (eg Eclipse or NetBeans) include tools for automatically creating getter and setter methods for a class's fields.
When they are private you need to call fld.setAccessible(true);
Yes, why don't you just set the fields directly and avoid reflection? It doesn't look like you're doing anything dynamic. It's just that they are private -- why? Perhaps you mean to expose getters/setters and make the fields private? If so, then you should just invoke the public setters.

Categories

Resources