`name()` vs. `getName()` naming convention? - java

I have seen some projects (jsoup for example) are using this new getter/setter naming convention:
String name()
void name(String value)
instead of old getter/setter convetion:
String getName()
void setName(String value)
What are positive and negative aspects of each naming convention? When and why you think one should be preferred over the other?

The first example doesn't adhere to the JavaBeans specification [Warning PDF]. There are certain frameworks like Spring, that assume this naming convention, especially when you do something in EL like ${object.name}, which gets translated to object.getName(). This will fail if you don't follow the naming conventions (although there are ways to get around it).
Without getting into a discussion about when/if to use getters/setters, in general it's better to stick with the naming convention because there are fewer surprises that way, especially when you're integrating with third-party libraries or frameworks that expect things to be named according to convention.

Nothing except readability and API style.
Some APIs accept this style and some don't, like Spring injections and JSF can't recognize this syntax (they explicitly require get/set for properties).

I like to simply use name() when the object that I'm dealing with is immutable, i.e. I would never change the value of the name field. When I'm dealing with a mutable object, I would use the second convention you mentioned, simply because I think it is superior in terms of readability.

I always prefer using verbs for methods name, so this is valid also for getters and setters.
I use nouns only for variables.
Follow classic JavaBean standard make me feel more comfortable. :)

I prefer to use the shorter style if the library is low level and I want to make it clear this component is not a JavaBean.
If in doubt, I would use the JavaBean style.

Related

are there java method naming conventions are in use for mutable `with`?

IMPORTANT: I am NOT asking for an opinion on what naming convention I should use. I want to know what naming conventions others have seen for the case below, in projects large and public enough to be noteworthy. Unfortunately, my Google searches have turned up nothing, probably because I don't already know any of the prefixes and therefore can't search for it by name.
I know that the with method prefix should be used to return a new instance of an immutable object, with its contents modified according to the specified object. However, I’m not aware of any naming convention for simply mutating a mutable object. Is anyone aware of any naming conventions for this and where they’re used?
If it matters, the problem I want to solve is I want to add a method that initializes the contents of an existing DTO, using a corresponding entity.
I don't think there is a standard convention for the scenario you're describing. Take a look at a GsonBuilder (documentation here). There are many prefixes used, including "set", "add", "register", "enable", etc. They all just describe the method's behavior.
I would recommend using initializeFromEntity(entity) or something similar, since this describes what the method does -- you're initializing the DTO contents using an entity.
Searching Google for "Java initializeFrom" results in several usages (example, example).

Eclipse getter/setter generation strange behaviour depending on capitalization [duplicate]

if I have the following private member:
private int xIndex;
How should I name my getter/setter:
getXindex()
setXindex(int value)
or
getxIndex()
setxIndex(int value)
EDIT: or
getXIndex()
setXIndex(int value);
?
The correct answer is
getxIndex()
setxIndex(int value)
if you want them to be used as properties according to section 8.8: Capitalization of inferred names of the JavaBeans API specification (e.g. access them via ${object.xIndex} in a JSP.
In accordance with JavaBeans API specification from 1997
it should be as Thomas Einwaller describes:
// According to JavaBeans API specification
public int getxIndex() { return xIndex; }
public void setxIndex(int xIndex) { this.xIndex = xIndex; }
This is unfortunate, getx and setx are not words. In the rare case when this would form a word or acronym it would be disinformative, eg the method setiMessage most
likely has nothing to do with SETI.
Using the only valid measurement of code quality (WTFs per minute),
I assess that this is bad code.
If we modify this to follow the convention for
naming a method it would be:
// According to Java naming convention
public int getXIndex() { return xIndex; }
public void setXIndex(int xIndex) { this.xIndex = xIndex; }
Why does the JavaBeans specification violate the convention? It all comes down to this sentence of the JavaBeans specification:
However to support the occasional use of all upper-case names, we check if the first two characters of the name are
both upper case and if so leave it alone.
Exactly what kind of use of all upper-case names this refers to is unclear to me. Field names should, according to
convention, be camel cased. It seems
to me that we generate unconventional method names in order to support unconventional field names as decided by a
20+ year old document.
It should also be noted that even though it seems to be an overwhelming support for the JavaBeans specification in tools,
it is not exclusively used. Eg. Kotlin will not recognize xIndex as a property in the above example. Reversely, the
Kotlin property var xIndex = 0 will result in the Java methods getXIndex and setXIndex. This seems to be a bug
according to the JetBrains support, but I fail to see how they can fix that without making a breaking change.
Some tools that does support the JavaBeans specification has not always done so, eg Jackson
and Swagger Code Generator have been patched to conform to it.
Even though IntelliJ generate accessors according to the JavaBeans specification, the example
in the documentation differs from it. Probably because people don't know about the standard and naturally prefers the
normal method naming convention.
So when should we follow the JavaBeans specification? When property names should be inferred by accessors by tools that
rely on this standard, then we might want to use it. For instance, Jackson will rely
on the property xIndex being accessed through getxIndex and setxIndex methods unless we use annotations.
When should we avoid this standard? Per my recommendation: When the code should be read and understood by humans.
Because to not use proper camel casing when naming methods is disinformative.
If I would have it my way, we would use normal naming conventions, ie getXIndex and setXIndex. But, given the state
of things, the best solution I see is suggested by #vaxquis:
Name your field "indexX" or whatever else, your problem is solved... don't overcomplicate things - even if setxIndex
is the correct way for Beans, having method named setxIndex increases the WTF factor of the code without giving you
anything in return.
Any comments regarding the JavaBeans specification should, according the specification itself, be sent to
java-beans#java.sun.com.
Should be:
getXIndex()
setXIndex(final int xIndex)
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
You should use Introspector.decapitalize from package java.beans and you have no problem beacause it is compliant with java rules.
Eclipse ide automatically generates setters and getters as:
getxIndex()
setxIndex(int value)
Which is according to the java beans API specification.
I think getXindex() is the best way. The getter should start with 'get', followed by the member name, with its first letter capitalized. Also the latest conventions I heard of, say that we should avoid multiple capital letters one after another. For example getHTMLtooltip is wrong. it should be getHtmlTooltip instead. Also you should try to make all your members final and there should not be a need of setters, since the class will be immutable ;)

Naming the member variable beginning with m_ conforms to javabean style?

Wondering if m_ naming convention conforms to Javabean property style?
well, m_ comes from Microsoft standards, which is based on Hungarian Notation. So that naming pattern isn't recommended by Sun/Oracle.
That's not to say you can't use them in JavaBeans as, javabeans are all about the method signatures, not about the field names, so you can call fields whatever you like.
Well,You can name your Java bean member, using any naming convention. The name is not part of the contract that makes a class, Java Bean.
Your class needs a public contructor,all its properties should be accessible via get and set and the class needs to be serializable.
But then again, I would not suggest using the m_ naming convention. Java Beans convention are used by lots by Java tooling support and more importantly by frameworks like JSF and Web Services (for UI binding and xml marshaling respectively). So apart from confusing some Java developers, who needs to maintain your code, there is also a possibility that some tooling support might not work.

What are the uses of getter/setters in Java? [duplicate]

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()

Getters on an immutable type [closed]

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.

Categories