Java Conventions: Use Getters/Setters Within the Class

Java Conventions: use getters/setters WITHIN the class?

You CAN do either one. However, your professor might appreciate using the methods instead of the direct access. Here's why.

Let's say you have a class like this:

class SomeClass {
private int someValue;
private String someString;

public SomeClass(int someValue, String someString) {
this.someValue = someValue;
this.someString = someString;
}

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

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

public String toString() {
return someValue + ": " + someString;
}

}

It's pretty straightforward, right? Well, what if all of a sudden we want to CHANGE the implementation of how we calculate someValue, and base it off of someString:

public int someValue() {
int value = 0;
for(int i = 0; i < someString.length; i++) {
if(someString.charAt(i) == ' ') value++;
}
return value;
}

Now you also have to change every place where variable someValue was used.

So if you want to make the code easier to maintain in the long run, use the methods calls. This way when you code changes on you (and trust me, it changes all the time) you only have to change it in one spot instead of two.

And yes, you would want to use a method call in getting someString instead of the direct access in the last method :-)

Using getter / setter inside a class - good or bad practice?

It is more common to access the field directly. The value of a setFieldName method is more obvious for programmers using your code in other classes. With the implementation details hidden, they might not realize what ranges of values are acceptable, so keeping fields private and forcing other developers to go through a setter makes sense. But inside your own class, the case for using a setter is much weaker. If you look at the source for the java API you'll find that getter / setter methods are generally not used within a class.

Getters and Setters in Java convention

You should write getters and setters. Or better - let your IDE generate them automatically. Otherwise you break the encapsulation. Also maybe you need just a getter.

Another advantage of using a getter or setter can be doing some checks or preprocessing before returning or setting the field.

Here is a sample code snippet:

private String name;

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

Optionally you can use http://projectlombok.org/ and write it like this using annotations:

@Getter @Setter
private String name;

The code generation is done compile time.

is getter method call to access variable better than direct variable access within a class

In Java it is a convention to access all fields via getter/setters from outside the class. From inside the class, you usually access fields directly. However, you can also access them via getter/setter is you want to.

It is important to know that this is just a convention. Many other programming languages don't have such strict rules or other concepts. So you are not forced to do that. But it is a good practice.

And: Don't mind performance! Using getters/setters will not affect the performance of your app. The JVM/Java is designed to work exactly like this. Every JVM will optimize your code and handle getters/setters in a very effective way. Try to write clear and good readable code.

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

Use of getter-setter within class

Getters setters are generally used from outside class from inside directly access the fields.
The main advantage/purpose is encapsulation of getter setters,

If your getters setters has some logical code then use it.

for example :

public void setValue(int val){
if(val > 100)
this.val = 0;
else
this.val = val;
}

Also see

  • why-use-getters-and-setters
  • More on getters and setters

Java Interface conventions with getters and setters

If the code is properly documented saying A does not support

public T getK();
public void setK(T k);

and B does not support

public T getZ();
public void setZ(T z);

then I think you can go ahead with this design.

And, also construct UnsupportedOperationException with the specified detail message for the classes that doesn't support some of the methods of C. For example,

class A implements C{

T x;
T y;
T z;
...
public T getK(){
throw new UnsupportedOperationException("YOUR MESSAGE");
}

}


Related Topics



Leave a reply



Submit