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 4 months ago.
Improve this question
I am writing some immutable types in Java and wonder about how to name the accessor methods.
The Java Bean specification says that the names of accessors should be getX or isX, but since the fields are final, there is no setter and the fields are more like attributes than properties.
There for I'd prefer naming the getter methods like:
public T x()
rather than
public T getX()
Please note as an example:
public int java.lang.String#length()
(Which might have been specified so early in the Java history, so the conventions where not there yet.)
The immutable objects expose means to create modified versions of themselves through methods which I've tried to name like a verb rather than MyObject MyObject#setX(), this should limit the risk of the user calling setX() and think that the object has changed. So: MyObject MyObject#shine(newShineLevel).
This is not always possible easy though. How would you name a method for adjusting an endpoint in a rectangle other than Rectangle.setUpperLeft()? Rectangle.adjustUpperLeft maybe, but now we're just moving away from the conventions.
I guess the question is relevant for all languages, but this questions concern Java in particular.
If these classes may be used with any reflection based framework then you are better off staying with the getX convention. For example, accessing properties in JSPs and other templating systems via an expression "x.y" requires that the object have a method getY().
In my opinion, the get prefix is really only mandatory if you're writing a bean. There are lots of examples of where get is not used. not only String.length(). You find it in the primitive wrapper classes (intValue(), doubleValue(), booleanValue(), ...), enums (name() and ordinal()) and collections (size()), and the way annotations were design also seems to encourage the get-less style. (Josh Bloch covers the subject in Effective Java, and advocates the more readable get-less style unless you're actually writing a bean.)
So: Use the get prefix and your object can be used as a bean. Ditch it, and your code gets easier to read. It's up to you to decide what you think is more important.
Even for immutable types, the convention getX() still stands. Some examples:
java.lang.Integer.getInteger()
java.lang.Boolean.getBoolean()
It is true that there are also many examples such as java.lang.String.length(), but the common convention is to use getX. Just as mentioned in the answer below, it is crucial to separate between an atomic get operation, and a method which does some calculations on the data.
Also worth mentioning that plain java beans in many frameworks depend on the fact that getters/setters are conveniently named getX and setX.
The convention in Java for accessing properties of a class -- including immutable classes -- is to use the get and set prefixes so I would recommend using public final T getX().
The reason the length() method on a String isn't called getLength() is because there is no property called length on the String class.
I'd stick with the "get" convention simply because so many other tools work with it. Jakara Commons BeanUtils for example. Lots of tools/libraries will work by default if you have the right naming, but require configuration if you've deviated from the bean accessors convention.
I'm not disagreeing with you reasoning for deviating, I just think you're probably better off in the long run sticking with the get/set convention.
It's a good idea to use get--never mandatory, but people will automatically know what it's for.
Get does not imply that you have that as a member variable, in fact it's supposed to hide that fact. It can easily be giving access to a computed value.
size(), length(), etc were created before Borland found they needed the get/set concept to implement their GUI builder (I'm not sure exactly who came up with the idea, but that was the reason).
intValue, doubleValue etc are not getters, they are converters and therefore are named differently.
Now, all that said, if you really want to use x or getX it is your choice. getters and setters are no longer needed for most decent toolsets, they will use annotations instead--just be ready for a few people to take a few extra seconds typing "get" followed by "ctrl-space" and not finding what they are after.
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
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.
Is the follwing true: Java getters and setters are just methods.
I know they are implemented to manipulate or get the value of private ... attributes/fields. But is it okay to call them methods?
Yes it's okay they are just methods!
Technically, from the language and VM point of view, yes, they are just methods.
Some libraries and frameworks, however recognize their special nature. For example, JPA may be used to map “properties” by annotating either fields or methods. Beans Binding library uses them to access properties, so if you have a getText() / setText() pair on some object, then you can bind the “text” property to some other property of some other object (you'll still have to do the addPropertyChangeListener magic, though). But this is just a “convention over configuration” phenomena combined with the power of Reflection.
As per JLS,
A method declares executable code that can be invoked, passing a fixed number of values as arguments.
And this criterias satisfies to getters and setters as well; so we can say the are "methods" in java language.
Luckily I was able to pull Craig Larman's "Applying UML and Patterns" book section in google. As quoted
Accessing methods retrieve(accessor method) or set(mutator method)
attributes. In some languages such as Java it is a common idiom to
have an accessor and mutator for each attribute, and to declare all
attributes private(to enforce data encapsulation). The methods are
excluded in the class diagram because of the high noise-to-value ratio
they generate."
Java Getters and Setters are accessor methods. So, yes, they are methods.
Many programmers (Java or otherwise) may feel annoyed at constantly writing getXXX() and setXXX(type t) for all of their private fields, especially if they are basically just one line methods. For this case, there are some annotation libraries (like Lombak) that generate these through the power of metaprogramming and Java annotations and reflection.
However, there are many reasons to explicitly write getters/setters. A good list can be found here. But I really like this answer, too.
Yes, essentially they are methods.
The standard definition for a Java method is as follows;
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name.
-https://mathbits.com/MathBits/Java/Methods/Lesson1.htm
So you can consider methods as small programs within a class itself that allows us to fulfill specific tasks, which is also exactly what getters and setters do.
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 8 years ago.
Improve this question
I've seen some legacy code that uses lengthproperty on some objects and others that uses length() method. Currently I'm working with a NodeList from the org.w3c.dom package and I found that it have the getLength() method to get the numbers of elements.
My Question is how as Java developer I can know how to determine when to use length, length(), size(), getLength()? obviously it depends of the object type and the API is there for read... but the point is how the Java Development select which of that implements in their classes.
Note: In the Question When to use .length vs .length() Makoto answer's indicates that .length is a property on arrays. That isn't a method call, and length() is a method call on String. But, why is the reason? why not use ever a method or ever a property for maintain the consistency around all the API.
how would Java developers select which of [the methods] to implement in their classes?
When you implement classes that contain other objects, it's almost always going to be size(), the method provided by theCollection interface.
As far as other choices go, you should avoid exposing member variables, even final ones, because they cannot be accessed through an interface. Java gets away with it for arrays because of some JVM trickery, but you cannot do the same. Hence, length should be out: it remains in Java because it's not possible to change something that fundamental that has been in the language from day one, but it's definitely not something one should consider when designing new classes.
When you implement your own type that has length (say, a rectangle or a line segment) you should prefer getLength() to length() because of Java Beans naming conventions.
obviously it depends of the object type and the API is there for read...
You already have answered your question yourself: look in the API documentation of whatever class you are using.
but the point is how the Java Development select which of that implements in their classes.
The classes in Java's standard library have been developed over a long period of time by different people, which do not always make the same choice for the name of methods, so there are inconsistencies and unfortunately you'll just have to live with that.
There is no clear rule, otherwise we wouldn't see such a mixup in the jdk itself. But here are some things to consider when making such a design decision.
Don't worry to much. It is a minor thing and won't make to much of a difference. So when you think longer then 5 minutes about this, you are probably wasting money already.
Use getters when a frameworks need them. Many frameworks depend on the getter style. If you need or want such frameworks to work nicely with your class it might be beneficial to use that style.
Shorter is better. the 'get' part doesn't increase clarity. It just generates to characters of noise to the source code, so if you don't need it for some reason, don't use it.
Methods are easier to evolve. Length is often a quantity that is not set directly but somehow computed. If you hide that behind a method it gives you the flexibility to change that implementation later on, without changing the API.
Direct field accesses should be a tiny bit faster, but if you aren't working on high volume online trading or something, the difference isn't even worth thinking about. And if you do you should do your own measurements before making a decision. The hotspot compiler will almost for sure inline the method call anyways.
So if there aren't any external forces driving you in a different direction I would go with 'length()'
According to OOPS principles, length should be attribute and getLength() should be method. Also length attribute should be encapsulated should be exposed through methods, so getLength() sounds more appropriate.
Unfortunately not all Java library classes follow standards. There are some exceptions and this is one among them.
In a pure OO language it should be probably always a method like length(). So in a class hierarchy you can override the attribute length.
But Java is not pure OO. And the main reason for fields (.length) vs method (length()) is/was performance issues.
And even Sun/Oracle programmers did some bad class design.
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
I have seen member variables given a private modifier and then using getter/setter methods just to set and get the values of the variable (in the name of standardization).
Why not then make the variable public itself (Other than cases like spring framework which depends on getter/setters for IOC etc). It serves the purpose.
In C# I have seen getter/setter with Capitalization of the member variable. Why not make the variable public itself?
In order to get a stable API from the first shot. The Java gurus thought that if later on, you might want to have some extra logic when setting/getting an instance member, you don't want to break existing API by replacing public fields with public methods. This is the main reason in Java.
In the case of C#, public properties are used instead of public fields because of binary interface compatibility. Someone asked a similar question right here, on SO.
So, it's all about encapsulating some logic while still preserving interface for... future proofing.
Even back in 2003 it was known that getter and setter methods are evil.
Because interfaces only allow for specifying methods, not variables. Interfaces are the building stones of API's.
Hence, to access a field through an interface, you need to have the getter and setter.
This is done so you can change the getter or setter implementation in your public API after you release it. Using public fields, you wouldn't be able to check values for validity.
Encapsulation
You also mentioned C# properties. These are really just getters/setters under the hood, but with a more concise syntax.
It's part of encapsulation: abstracting a class's interface (the "getters" and "setters") from its implementation (using an instance variable). While you might decide to implement the behaviour through direct access to an instance variable today, you might want to do it differently tomorrow. Say you need to retrieve the value over the network instead of storing it locally—if you have encapsulated the behaviour, that's a trivial change. If other objects are relying on direct access to an instance variable, though, you're stuck.
The most and foremost use for getters and setters in Java is to annoy the developers. The second most important use is to clutter the code with useless noise. Additionally, it forces you to use a different name for the same thing, depending on where you are (inside or outside the class). Not to forget the added ambiguity (do you call the getter inside the class or do you use the field directly?) Next, they are used to allow access to private data but that's just a minor side effect ;)
In other programming languages, the compiler will generate them for you (unless, of course, you provide your own implementations). In Delphi, for example, you have read and write modifiers for fields (just like private, static or final in Java). The define if you'll have a getter or setter generated for you.
Unlike the Delphi guys, the Java guys wanted everything to be explicit. "If it's not in the source, it's not there". So the only solution was to force people to write all the getters and setters manually. Even worse, people have to use a different name for the same thing.
Getters and setters may very well be the greatest lie ever told. They are considered a sign of good design, while the opposite is true. New programmers should be taught proper encapsulation, not to write dumb data carrier classes that contain nothing but getters and setters.
(The idea that you need getters and setters to future-proof your code if you want to change the implementation later on is an obvious case of YAGNI. But that is really beside the point.)
The most common reason is a poor understanding of encapsulation. When the developer believes that encapsulating stuff really just means getters & setters rather than encapsulating behavour.
The valid reasons for having getters/setters are:
1) You are making a generic¹ object such as JComponent. By using a getter/setter rather than direct access to the variable means that you can do some pre-processing on said variable first (such as validate it is with a set range) or change the underlying implementation (switching from an int to a BigInteger without changing the public API).
2) Your DI framework does not support ctor injection. By having just a setter you can ensure that the variable is only set once.
3) (Ties in with #1) To allow tools to interact with your object. By using such a simple convention then GUI tools can easily get all the settings for a given component. An example of this would be the UI builder in NetBeans.
¹ Of the not-Generic type. Bad word to use I know, please suggest an alternative.
Having a setter allows you
perform validation
to fire a property changed event if the new value is different from the previous value
In the case in question there is no need for getter and setter if the value is simply read or written.
Well,
OOP. ;)
Or to be a little more precise:
Getters and Setters are used to provide a defined interface to a classes
properties. Check the OOP link, it describes the concepts more in detail...
K
You'd need encapsulate those attributes if there are constraints for example or to make general validity checks or post events on changes or whatever. The basic use is hiding the attribute from the "outer world".
Some Java frameworks require them (JavaBeans I think).
-- Edit
Some posters are trying to say this is about encapsulation. It isn't.
Encapsulation is about hiding the implementation details of your object, and exposing only relevant functions.
Providing a get/set that does nothing but set a value does not accomplish this at all, and the only reason for them is:
Perform some additional validation before set/get
Get the variable from somewhere else
Integrate with frameworks (EJB)
There are several reasons:
Some Java APIs rely on them (e.g. Servlet API);
making non-final variable public is considered to be a bad style;
further code support: if sometime in future you`ll need to perform some actions before each access/mutation (get/set) of the variable, you will have less problems with it.
In C# constructions like
public int Age
{
get
{
return (int)(today() - m_BirthDate);
}
}
are are just syntactic sugar.
property idea is core in OOP (Object oriented programming). But problem is that Java introduce them not in core of language (syntax / JVM), but (probably few years later??? historics of Java say better) as convention: pair of consistent getters/setter is property in bean, concept of property is in libraries, not in core.
This generate problem in few libraries, framework. Is single getter a read only property or not? That is the question. I.e.in JPA entities if You want implement classic method (algorithm) beggining with "get" like getCurrentTine() is the best mark by #Transient to disable interpretation like property having value.
In other words, I like very much property concept in C# designed 10 years later and better. BTW C# property has getter/setter too, but sometimes/partially hidden, visible at low level debugging. Free from question "why getter" etc ...
In Java world is interesting to read about Groovy concept of property (hidden getter/setter in different way than C#) http://www.groovy-lang.org/objectorientation.html#_fields_and_properties
EDIT: from real life, every java object has getClass() method, tools from java.beans.BeanInfo package report this as property "class", but this not true. It isn't property (readonly property) in full sense. I imagine properties like C# (with his internal hidden name get_Something1) hasn't conflict with "functional" GetSomething2()
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.