Naming Convention for Getters/Setters in Java

Naming convention for getters/setters in Java

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.

Post Java-14 getter/setter naming convention

Quote from JEP 359:

It is not a goal to declare "war on boilerplate"; in particular, it is not a goal to address the problems of mutable classes using the JavaBean naming conventions.

My understanding, based on the same document is that records are transparent holders for shallowly immutable data.

That being said:

  1. Records are not the place to look for getters/setters syntactical sugar, as they are not meant to replace JavaBeans.
  2. I strongly agree with you that JavaBeans are too verbose. Maybe an additional feature (called beans instead of records) could be implemented - very similar behavior with the records feature but that would permit mutability. In that case, records and beans would not be mutually exclusive.
  3. As it has been mentioned, records are in preview mode. Let's see what the feedback from community would be.

All in all, IMHO they are a step forward... I wrote this example set where you can see a code reduction to ~15% LOC from standard JavaBeans.

Also, note that records behave like normal classes: they can be declared top level or nested, they can be generic, they can implement interfaces (from the same document). You can actually partly simulate JavaBeans (only getters would make sense, though) by extracting an interface containing the getters - however that would be a lot of work and not a really clean solution...

So, based on the logic above, to address your question, no - I didn't see any (semi)official guideline for getters and setters and I don't think that there is a motivation for it right now because, again, records are not a replacement for JavaBeans...

For a boolean field, what is the naming convention for its getter/setter?

Suppose you have

boolean active;

Accessors method would be

public boolean isActive(){return this.active;}

public void setActive(boolean active){this.active = active;}

See Also

  • Java Programming/Java Beans
  • Code Conventions for the Java Programming Language

Typescript getter/setter naming convention

We can use get, set where we need to implement some constraints when a value is accessed.

From Typescript documentation:

TypeScript supports getters/setters as a way of intercepting accesses
to a member of an object. This gives you a way of having finer-grained
control over how a member is accessed on each object.

Example:

class StudentMark {
isPass: boolean;
_mark: Mark;
set mark(value: Mark) {
if (value.subject1 > 35 && value.subject2 > 35&& value.subject3 > 35) {
this.isPass = true;
} else {
this.isPass = false;
}
this._mark = value;
}
get mark(): Mark {
return this._mark;
}
}

Here, whenever we set the mark, the pass will be updated. No, need to update it separately. In this, type of cases get, set will be useful.

Suffix of get and set should have same name. And we can access it by only calling the name itself. Example, mark from above code.

For, more about get, set visit typescript documentation.

How to configure setter and getter name convention in Jackson for a particular class?

You can override the default accessor naming strategy as shown below.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.DefaultAccessorNamingStrategy;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.ToString;

public class CustomPropertyNaming{
public static void main( String[] args ){
try{
/* ObjectMapper instance configuration:
* (a) Override the default accessor naming strategy
* (b) Set FAIL_ON_UNKNOWN_PROPERTIES to false to avoid looking for other method names as properties (eg, toString()).
* (c) Set REQUIRE_SETTERS_FOR_GETTERS to true to handle 'toString()' being construed as a property getter */
ObjectMapper m = new ObjectMapper();
m.setAccessorNaming( new DefaultAccessorNamingStrategy.Provider().withGetterPrefix( "" ).withSetterPrefix( "" ) );
m.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
m.configure( MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true );

/* Serialization */
String json = m.writeValueAsString( MyModel.of( "ONE", 2 ) );
System.out.println( "Serialized: " + json );

/* Deserialization */
MyModel mm = m.readValue( json, MyModel.class );
System.out.println( "Deserialized: " + mm );
}
catch( JsonProcessingException e ){
e.printStackTrace();
}
}

@NoArgsConstructor @AllArgsConstructor(staticName = "of") @ToString
private static class MyModel{
private String first;
private int second;

public String first(){
return this.first;
}

public void first( String value ){
this.first = value;
}

public int second(){
return this.second;
}

public void second( int value ){
this.second = value;
}
}
}

Output from running the above class

Serialized: {"first":"ONE","second":2}
Deserialized: CustomPropertyNaming.MyModel(first=ONE, second=2)

(I have used Lombok on MyModel. You may have your constructors and toString().)

A couple of points about this solution.

  • Since the property names and accessor names are now same, Jackson tends to consider every zero-arg method as a getter and every one-arg method as setter. This needs to be handled. The way I have done here is by adding a couple configurations explained in the code comments.
  • DefaultAccessorNamingStrategy.Provider has some other configurability that you may want to explore.

Proper naming conventions for getters

would it be OOP appropriate to add "get" into the name even if it is returns a value calculated from a member variable, but not the member variable it self?

Naming of getters and setters in Java is not governed by any "OOP principles" - it's purely a JavaBeans convention:

The class properties must be accessible using get, set, is (used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.

Note how the convention deliberately calls the values being accessed through getters and setters "properties", to distinguish them from fields. The intention behind this has been to cover both calculated and stored properties.

This leads to an answer to your question: it is entirely appropriate to use the "get" prefix for getters of calculated properties.

Naming conventions for complex getters in Java

I was asking myself how you could express this difference in Java.

Just don't use the get prefix on the method, as it normally implies that the method will be cheap (as getters usually only access fields, delegate to other getters, or perform fairly simple calculations based on other getters). For example, if a class has this interface:

class Blob {
long getLength() { ... }
ByteBuffer getBytes() { ... }
Sha1Checksum getChecksum() { ... }
}

... it would seem that getting the length, contents, and checksum from the Blob are equally costly. If we did like this, instead:

interface Blob {
long getLength() { ... }
ByteBuffer getBytes() { ... }
Sha1Checksum calculateChecksum() { ... }
}

... it becomes clear(er) that we can expect calculateChecksum() to be more expensive than the other operations, as its name says it's going to do more than just get something.

To a certain degree, the complexity is an implementation issue that shouldn't be seen in the interface (maybe I decide to calculate the checksum eagerly when the Blob is constructed?), but there are occasions where it makes sense to make a distinction.

Confused about naming of JavaBean properties, with respect to getters and setters

The JavaBeans Specification says that for a property propertyName there should be a getter method getPropertyName() and/or a setter method setPropertyName().

A property is defined by the only presence of the getter and setter methods and can also be a computed value. A instance variable on the object is not required.

The specification defines the capitalization rules for properties and getter/setter methods:

Thus when we extract a property or event name from the middle of an
existing Java name, we normally convert the first character to lower
case. 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. So for example,

“FooBah” becomes “fooBah”, “Z” becomes “z”, “URL” becomes “URL


The method is in fact implemented as:

/*
Utility method to take a string and convert it to normal Java variable name
capitalization. This normally means converting the first character from upper case to
lower case, but in the (unusual) special case when there is more than one character
and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

Parameters:
name The string to be decapitalized.
Returns:
The decapitalized version of the string.
*/
public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
return name;
}

char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}

So:

  1. if the name is null, return it as such
  2. if the name has first two characters in caps, return it as such
  3. all other strings, decapitalize first character

Method name conventions for setters and getters

You'd be best off using @property to declare things like this. That way you can get all its implementation benefits (like atominicity, automatic ivar generation, etc) along with convenient dot syntax (e.g. myInstance.supportsMusicians = YES), all without having to worry about the underlying method names at all.

But in case you do want to declare your methods manually, or just want to know what the auto-generated ones are, the naming convention is:

- (void)setSupportsMusicians:(BOOL)supportsMusicians;
- (BOOL)supportsMusicians;

There's also a side-case for some types of booleans properties, where "is" is used as a prefix for readability, e.g.

- (BOOL)isVisible;

This is not followed universally, however, and might be considered a legacy convention.

Note that "get" as a prefix shouldn't be used randomly as it has a specific meaning: it's used in a context where the caller provides a buffer to be filled in, e.g. -[NSString getBytes:length:].

Unexpected result when creating Getters/Setters

This behavior seems to be specific to Domino Designer (8.5.3 and 9.0.1). It does create the following setters:

private String aaPage;
private String aPage;
private String aPa;
private String aP;
private String a;

public void setAaPage(String aaPage) {
this.aaPage = aaPage;
}
public void setAPage(String page) {
aPage = page;
}
public void setAPa(String pa) {
aPa = pa;
}
public void setAP(String ap) {
aP = ap;
}
public void setA(String a) {
this.a = a;
}

The three middle generated setters are in fact weird. This "special" parameter for setters gets created when you choose "Source / Generate Getters and Setters...". Because the parameter name is different to the private field name it doesn't need to add "this.".

Although it's weird it doesn't mean it's wrong. But, it doesn't really follow the usual conventions...

Setters are generated the normal way if you click STRG+1 in line private String ... and choose "Create getter and setter for '...'".

In Eclipse (Juno) works all as expected.



Related Topics



Leave a reply



Submit