I know that many suggest this convention:
boolean deleted;
boolean isDeleted();
But what do you do when you want to name a boolean to indicate that a user can leave?
boolean userCanLeave
boolean isUserCanLeave()
boolean canUserLeave
boolean isCanUserLeave()
boolean userLeave
boolean isUserLeave()
boolean userLeave
boolean canUserLeave()
I'm not sure if there is any standard for this or do you just take the one you think is most readable? It is the variable to getter method name mapping that is interesting here.
Boolean variables should be prefixed with 'is' This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag.
The usual convention to name methods that return boolean is to prefix verbs such as 'is' or 'has' to the predicate as a question, or use the predicate as an assertion. For example, to check if a user is active, you would say user. isActive() or to check if the user exists, you would say user. exists().
Rules to Declare a VariableThe first character must not be a digit. Blank spaces cannot be used in variable names. Java keywords cannot be used as variable names.
For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.
You should use a better variable name like userAllowedToLeave
.
And, then use the getter method as isUserAllowedToLeave()
.
This at least uses the "is" getter, and sounds grammatically correct too.
Using booleans like this is almost always a bad and confusing idea. If you want to make your code understandable and easily maintainable you should use an enum to represent state, maybe with strong transition rules (an FSM).
Assuming that your 'leave' concept is based on whether a user has completed a task or set of tasks, then you might have
public enum UserState { inProgress, complete }
You could then implement a method leave
on your user class like this:
public void leave() { if (state == UserState.complete) ... }
where state
is a private instance of the enum defined above. You can then reframe the question isLeaveable to getState, if such a thing is needed. Of course, you'd also need a complete()
method which would change the state appropriately and which would be called when the user has completed their tasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With