Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
When you have to access a "member variable"/field in a class, is it good practice to access it directly or call the getter and setter? and why?
I see almost only benefits in making your fields private and only provide access through a getter and possibly a setter
controlled access. If you only want to provide read access, or only write access you can only achieve this by using getters/setters
if you want to fire PropertyChangeEvents for bean properties, you can include this code in your setter. Otherwise all calls which modify this field directly should trigger a change event as well
I personally find it easier to discover in my IDE who modifies the field. The only direct access to the field is in the class (since it is a private field), and all external changes go through the setter. This allows for faster debugging than having to use a field watchpoint
subclasses who want to do something extra when the field change can override the setter, call super.set and do something extra
The only possible drawback I can think of is that it requires a bit more code to write (for the getters and setters), and a bit more code for accessing the field from outside the class. But with the current IDEs is this a pretty lame excuse
Some extra literature:
link1, link2
Call the setter/getter rather than accessing directly. That way any extra required code in the setter/getter will be run.
Getter/ Setter allows for lazy instantiation, which is often a way to go. Additionally, this way you have a controlled access to your variables (both for yourself and as part of any API you may want to expose); ability to hide implementation of initialization etc are also very important.
The biggest benefits of S/G in my opinion is reduced risk of someone modifying it without your control. A small example .. consider that a getter may give you .. a copy of the original instead of an original.
Benefits are multiple, when given a choice, choose setter/ getter for the benefits of data encapsulation and more control.
If it is a member of the calling class, access it directly. Otherwise use the getter/setter methods.
Why? You should not be creating getter/setter methods just so that the calling class can access its own members. Otherwise you should use the getter/setter methods for the reasons elaborated by others.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Short context: I made a tetris clone in java (all the game data and methods are a Class) and I am concerned about whether encapsulation matters in this case.
Almost all of the fields and methods are marked as "default", without any getters and setters because the user is not supposed to access them.
Methods manipulate variables directly without any arguments passed, of course only when the thing it is manipulating is unique (there can not be two current pieces, two next block lists, two held pieces and so on)
Do I really need getters and setters if the user is never supposed to get raw members of the class? Methods just directly get and set the values. If I have a simple int that I want to get or set, I am just doing it directly.
No return value, if one exact thing is supposed to happen every time. For example: if a collision happens during spawning, gameOver() is triggered immediately instead of returning false, then doing it outside of function. I chose to not have a return value because it is much simpler to do it inside function instead of surrounding each function call with an if statement doing the same thing.
Do I need to fix some of these things, and how should I, preserving stability in both readability and performance?
It does not.
Why? The understanding is that a class’s fields and methods are working in conjunction towards a common goal. So they are not enemies or careless actors that you have to protect yourself against.
It is only to prevent external actors from mucking up class invariants that you hide your fields and methods as much as possible and expose only that which is necessary.
If you have to use setters and getters to enforce discipline in the code within a class, then you have much bigger problems to handle than maintaining proper encapsulation (and other OO principles.)
No, you do not need getters and setters if you do not intend on anything accessing the member variables from outside of the class.
In your case because the member variables are only accessed from within the class itself then the access modifier(s) should be changed to private.
The use of the default keyword means that you do not want to provide an access modifier and that variable should be available to any other class in the same package.
More info can be found Here
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
The builder pattern is one of the most popular creation patterns, and it has numerous benefits. I specifically want to understand if immutability of the model object itself is one of the key benefits. All the while I thought it was, but I could not find any backing documentation on the same. Consider this scenario, you are creating an object from a network call (from json let's say). We create model objects and it has a Builder inline. This is what everybody does. The members of the model are also private. Since this is a network object, the members won't have setters. My doubts are
With builder securing object creation, do we need to make members private.
Can we instead keep them public final and eliminate need for getter()
In general (irrespective of the above two points), shouldn't all non-settable members be final? I don't see many people making members final, why is it so?
Is this a good approach or not?
I'm really having my pain with the example you chose. Parsing JSON into objects is really something you can delegate to JSON-B / Jackson / insert JSON library here nowadays. But I get it that we're on a theoretical level here.
Wikipedia just says: The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
From the theory, the builder pattern neither forces immutability nor is it any aspect of it.
With builder securing object creation, do we need to make members
private.
You don't need to do anything. But there is one simple stylistic rule: You either access members by getters and setters or by making them public. But not both.
Can we instead keep them public final and eliminate need for getter()
Final would imply immutability - if that's what you want to achieve, you can do so.
In general (irrespective of the above two points), shouldn't all
non-settable members be final? I don't see many people making members
final, why is it so? Is this a good approach or not?
You only make members final if you want them to be immutable or if they are constants. Otherwise it makes no sense. With your example, I can only think of constant values? However, you cannot make members final without setting their value. You either need to set them in the constructor or initialise them to null. But having final null values most likely doesn't serve any purpose.
The better approach for such values would be really just not to define a getter or setter and making it private. But then you again have just some useless null values laying in your class.
To be frank, this whole discussion about getters/setters or public is opening Pandora's box. I have had too many discussions about this by now, and it just doesn't matter which way you do it. In the end both serve the same purpose: setting and retrieving values.
Regarding final values: I don't have to use immutability often to be frank, in my area of development I can't really think of any case I've used it so far. The only thing I use it for is to mark constant values which I don't want to be changed by anything.
In the end, this whole discussion about design patterns is tedious. A builder is just a helping structure. You have to find your way on how to use it for your use case and in your company. Just remind you of the fact that it's whole purpose is to make the creation of complex objects more accessible.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
It is a good practice to use a proper qualifier between private, protected, private or default. But is there any other reason like performance or JVM optimization drawback default is used instead of private? As an example
public class Class1{
Class2 class2;
}
And where variable class2 could have been private.
Also if the variable is autowired or injected by DI framework. Framework calls field.setAccessible(true). Does that make any difference as per the performance or optimization.
I think I now understand the motivation for this question.
The reasons for using the correct access modifiers on variables in normal Java are well understood. Basically, it is all about modularity, encapsulation, avoiding unwanted / harmful coupling and so on.
What about Spring?
Well it is true that Spring can circumvent normal access rules and allow you to inject private variables. However, from what I understand, you have to deliberately annotate your private fields with #autowire or similar for this to occur. What is actually going on here is that Spring is following an "instruction" that is explicitly declared in the source code by means of the annotation. Spring XML-based wiring won't let you inject a value into a private field or using a private setter.
In the light of this, the argument that Spring allows you break private encapsulation is ... while technically true ... ultimately self-serving. Sure, you can do it. But you have to do it explicitly, deliberately ... by design. And it ONLY happens when the objects are wired.
By contrast, if you are sloppy about the modifiers, and declare every instance variable as public or package private, then you are leaving open the possibility of all sorts of lazy, ill-considered, or even accidental breaking of encapsulation. And even if you (the original author) are disciplined, the next guy reading / maintaining your code can't be sure that you have been disciplined. He has to check ...
So how do you "force" someone to toe the line?
It is probably best to persuade rather than force, but the way to force people to write decent code is to get your project manager / quality manager to adopt a coding standard, and insist that it is followed. (But this can be easier said than done if your management doesn't understand the long-term costs of poor quality.)
The real reason we have these pesky coding standards is so that the code can be maintained ... by someone other than the guy who wrote it. A good IT manager will understand this. A good PM will understand this. A good programmer will understand this.
If it's not meant to be used by any other application - then just make it private. The point is OTHER developers can't read your mind. And if it's not private, then they will think, that it is meant to be used outside of class.
This question already has answers here:
Using getters within class methods
(6 answers)
Closed 9 years ago.
In Java classes is it considered good or bad practice to access member fields with their getters and setters?
e.g which is better:
public Order {
private Agreement agreement;
public Agreement getAgreement() {
return agreement;
}
public void process() {
//should I use:
getAgreement().doSomething();
//Or:
agreement.doSomething();
}
}
In general I think accessing the field directly is best due to the KISS principle and also someone may override the get method later with unpredictable results.
However my colleagues argue that it is better to keep a layer of abstraction. Is there any consensus on this?
Honestly, in my opinion, it depends on what you're using it for. Personally, when in doubt, I always leave that extra level of abstraction in there just in case I need to override it later in a subclass. Many times have I been saved from the pain of rewriting a class just because I left a getter or a setter open to overriding.
Another thing is that other clients/programmers might need to use your class in a way that you haven't yet thought of, for example, pulling the Agreement class out of a database. In that case, when they override your class, you have made it painless for them (or potentially a future you) to modify how that data is retrieved.
So unless you're absolutely certain that there is only one way to access that field, and that it's 100% direct, it's probably best to decouple the retrieval and modification of values so that at some future point you can save yourself from rewrite hardship.
The core issue here is that direct field access is ineligible for interception by subclass overridden methods, AOP, dynamic proxies and the like. This can be a good or bad thing depending on the case. I would say that using getters and setters internally is not an anti-pattern or a pattern. It is a good or bad thing depending on the situation, and the design of your class.
I think that the public interface of a class represents encapsulation around state and as such even the other workings of the class benefit from that encapsulation.
If you have wrapped a field in a public get method then there is a reason you have done so. Perhaps there is logic within that method to lazy-load the field, or provide an audit trail. Whatever the reason for the method, your class will most likely need that logic as well.
It sounds to me like some people are interpreting this question as being about getters and setters that are used externally; my interpretation of Pablojim's question was that it's about using them within the class, as opposed to the class directly accessing its fields. (Which are private.)
In that light, I'm with Jherico and patros; use direct access from within the class unless there's some reason not to.
Keeping a layer of Abstraction is a good thing in Java.
The problem is that all the code that directly accesses your member variables without the class noticing it isn't under the control of your class.
So the moment you decide to edit your class in a way that one member that is used in a division as an example should never be 0 you have to be able to ensure that this value is only changed in a way that ensures this. So you would add a setter for this method and change the member to private. But now you need to change all the code that is accessing the member without the setter.
If you know you are changing the value from outside the class and only then provide a setter if you don't know make the variable private and if you need access later maybe provide a getter or a setter.
It gets an Anti-Pattern if there are certain methods in other objects that are always using get for a member then performs some calculations and then uses get. This shows that either the member should be in the other class or that the method needs to be in this class.
Having a getter and a setter without thinking about it for every member breaks encapsulation and is not a good design choice. For mor insides read this article
I'm now working on something that makes me in favor of the getters: we're now moving part of our properties into a "property bag", which means you cannot just reference the variable. So in addition of changing the getter, we need to change all the places that reference that variable. It's something to keep in mind.
It depends on what you use your getters and setters for. Generally I use them when I need to sanity check data coming into a class or format data going out. In that respect, I really use getters and setters as an interface layer between this class and other classes that might need access to its data.
I tend to write my internal code such that it knows how to handle data private to this class, so accessing it with its own getters and setters is generally unnecessary and undesired.
It all depends on how you use your getters and setters, though.
My rule of thumb is that if they do anything more complex than just set or return the value, use the setters/getters. Otherwise, it's not needed since you can fix any problems caused by changes to the member variables.
You're right in that it's annoying to do all that extra work for every attribute variable. Why does the language allow something so basic that no one does? There are very compelling reasons for not allowing direct attribute access, however.
I prefer Eiffel's Unified Access Principle. You can never assign to an attribute, and attributes and functions are accessed in the same way:
class EXAMPLE
feature
variable: INTEGER
variable_function: INTEGER
do
result := 4
end
variable_two: INTEGER assign variable_assign
variable_assign (in: INTEGER)
do
variable_two := in
end
end
feature
test
local
test: EXAMPLE
value: INTEGER
do
create test
value := test.variable -- Valid
value := test.variable_function -- Valid and same even though it's a function
test.variable := value -- Invalid
test.variable_two := value -- Valid, an explicit setter is defined
end
I think this is something that needs to be considered on a case by case basis. Using a getter throughout your class code does complicate it, and probably makes it slightly slower. However, it also makes it more extensible and reusable.
What I've usually done is use the getter if I can forsee any reason someone might want to override my getter with another one. If it's something so basic and simple that it would never make sense, I generally don't use getters.
If you write your code to access the variables without the getter, consider making the getter function "final". That way, no one will try to override your code and tear his hair out wondering why it's not working. (Note that Spring and Hibernate proxies might make this a bad idea.)
In order for it to be an anti-pattern, it'd have to be decidedly harmful. I don't see how there can possibly be any harm in defining getters and setters. At most, it is a waste of time (and typing), which makes it pointless, but not an antipattern.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?
I know that from outside of the object you should use a getter/setter, but from within would you just do:
Java:
String property = this.property;
PHP:
$property = $this->property;
or would you do:
Java:
String property = this.getProperty();
PHP:
$property = $this->getProperty();
Forgive me if my Java is a little off, it's been a year since I programmed in Java...
EDIT:
It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...
This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).
Personally, I feel like it's important to remain consistent. If you have getters and setters, use them. The only time I would access a field directly is when the accessor has a lot of overhead. It may feel like you're bloating your code unnecessarily, but it can certainly save a whole lot of headache in the future. The classic example:
Later on, you may desire to change the way that field works. Maybe it should be calculated on-the-fly or maybe you would like to use a different type for the backing store. If you are accessing properties directly, a change like that can break an awful lot of code in one swell foop.
I'm fairly surprised at how unanimous the sentiment is that getters and setters are fine and good. I suggest the incendiary article by Allen Holub "Getters And Setters Are Evil". Granted, the title is for shock value, but the author makes valid points.
Essentially, if you have getters and setters for each and every private field, you are making those fields as good as public. You'd be very hard-pressed to change the type of a private field without ripple effects to every class that calls that getter.
Moreover, from a strictly OO point of view, objects should be responding to messages (methods) that correspond to their (hopefully) single responsibility. The vast majority of getters and setters don't make sense for their constituent objects;Pen.dispenseInkOnto(Surface) makes more sense to me than Pen.getColor().
Getters and setters also encourage users of the class to ask the object for some data, perform a calculation, and then set some other value in the object, better known as procedural programming. You'd be better served to simply tell the object to do what you were going to in the first place; also known as the Information Expert idiom.
Getters and setters, however, are necessary evils at the boundary of layers -- UI, persistence, and so forth. Restricted access to a class's internals, such as C++'s friend keyword, Java's package protected access, .NET's internal access, and the Friend Class Pattern can help you reduce the visibility of getters and setters to only those who need them.
It depends on how the property is used. For example, say you have a student object that has a name property. You could use your Get method to pull the name from the database, if it hasn't been retrieved already. This way you are reducing unnecessary calls to the database.
Now let's say you have a private integer counter in your object that counts the number of times the name has been called. You may want to not use the Get method from inside the object because it would produce an invalid count.
PHP offers a myriad of ways to handle this, including magic methods __get and __set, but I prefer explicit getters and setters. Here's why:
Validation can be placed in setters (and getters for that matter)
Intellisense works with explicit methods
No question whether a property is read only, write only or read-write
Retrieving virtual properties (ie, calculated values) looks the same as regular properties
You can easily set an object property that is never actually defined anywhere, which then goes undocumented
Am I just going overboard here?
Perhaps ;)
Another approach would be to utilize a private/protected method to actually do the getting (caching/db/etc), and a public wrapper for it that increments the count:
PHP:
public function getName() {
$this->incrementNameCalled();
return $this->_getName();
}
protected function _getName() {
return $this->name;
}
and then from within the object itself:
PHP:
$name = $this->_getName();
This way you can still use that first argument for something else (like sending a flag for whether or not to used cached data here perhaps).
I must be missing the point here, why would you use a getter inside an object to access a property of that object?
Taking this to its conclusion the getter should call a getter, which should call a getter.
So I'd say inside an object method access a property directly, especially seeing as calling another method in that object (which will just access the property directly anyway then return it) is just a pointless, wasteful exercise (or have I misunderstood the question).
It is better to use the accessor methods, even within the object. Here are the points that come to my mind immediately:
It should be done in the interest of maintaining consistency with accesses made from outside the object.
In some cases, these accessor methods could be doing more than just accessing the field; they could be doing some additional processing (this is rare though). If this is the case, accessing the field directly would mean that you are missing that additional processing, and your program could go awry if this processing is always to be done during those accesses.
If you mean "most encapsulation" by "purist", then I typically declare all my fields as private and then use "this.field" from within the class itself. For other classes, including subclasses, I access instance state using the getters.
The question doesn't require an opinion based answer. It is a subject well covered by computing science for decades from the principle of high cohesion, low coupling and the SOLID principles.
The purist, read correct, OO way is to minimise coupling and maximise cohesions. Therefore both should be avoided and the Law of Demeter followed by using the Tell Don't Ask approach.
Instead of getting the value of the object's property, which tightly couples the two class, use the object as a parameter e.g.
doSomethingWithProperty() {
doSomethingWith( this.property ) ;
}
Where the property was a native type, e.g. int, use an access method, name it for problem domain not the programming domain.
doSomethingWithProperty( this.daysPerWeek() ) ;
These will allow you to maintain encapsulation and any post-conditions or dependent invariants. You can also use the setter method to maintain any pre-conditions or dependent invariants, however don't fall into the trap of naming them setters, go back to the Hollywood Principle for naming when using the idiom.
i've found using setters/getters made my code easier to read. I also like the control it gives when other classes use the methods and if i change the data the property will store.
Private fields with public or protected properties. Access to the values should go through the properties, and be copied to a local variable if they will be used more than once in a method. If and ONLY if you have the rest of your application so totally tweaked, rocked out, and otherwise optimized to where accessing values by going through their assosciated properties has become a bottleneck (And that will never EVER happen, I guarantee) should you even begin to consider letting anything other than the properties touch their backing variables directly.
.NET developers can use automatic properties to enforce this since you can't even see the backing variables at design time.
It depends. It's more a style issue than anything else, and there is no hard rule.
I can be wrong because I'm autodidact, but I NEVER user public properties in my Java classes, they are always private or protected, so that outside code must access by getters/setters. It's better for maintenance / modification purposes. And for inside class code... If getter method is trivial I use the property directly, but I always use the setter methods because I could easily add code to fire events if I wish.
If I don't edit the property, I'll use a public method get_property() unless it's a special occasion such as a MySQLi object inside another object in which case I'll just make the property public and refer to it as $obj->object_property.
Inside the object it's always $this->property for me.
Well, it seems with C# 3.0 properties' default implementation, the decision is taken for you; you HAVE to set the property using the (possibly private) property setter.
I personally only use the private member-behind when not doing so would cause the object to fall in an less than desirable state, such as when initializing or when caching/lazy loading is involved.
I like the answer by cmcculloh, but it seems like the most correct one is the answer by Greg Hurlman. Use getter/setter all the time if you started using them from the get-go and/or you are used to working with them.
As an aside, I personally find that using getter/setter makes the code easier to read and to debug later on.
As stated in some of the comments: Sometimes you should, sometimes you shouldn't. The great part about private variables is that you are able to see all the places they are used when you change something. If your getter/setter does something you need, use it. If it doesn't matter you decide.
The opposite case could be made that if you use the getter/setter and somebody changes the getter/setter they have to analyze all the places the getter and setter is used internally to see if it messes something up.