Prefix IS before a Boolean field getter in Java — Why?
Common practice developers community follow is to declare a Boolean variable with ‘is’ prefixed to it. Let’s discuss the efficacy or need of the approach and what happens internally if we generate getter/setters for the fields manually.
Let’s take an example to understand the scenarios:
We have a java class named ClassA and and a field expected to be in it is current of Boolean dataype.
Scenario 1
Normally we declare a Boolean field by prefixing it with ‘is’ to justify that this variable will have True or False value in it. Hence when one creates getters and setters manually or generate those via any IDE the code looks like given below.
public class classA {
private boolean isCurrent;
public boolean isCurrent(){
return current;
}
public void setCurrent(final boolean current){
this.current = current;
}
}
Scenario 2
But what if a person hasn’t prefixed ‘is’ to the Boolean variable and now one generates the getters. By default the getters will be prefixed with ‘is’ as given below:
public class classA {
private boolean current;
public boolean isCurrent(){
return current;
}
public void setCurrent(final boolean current){
this.current = current;
}
}
Conclusion
If a Boolean variable isn’t prefixed with ‘is’ then the generated getter is auto prefixed with ‘is’ thus forming a getter method as below:
public boolean isCurrent(){
return current;
}