12

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.

Tn Hn
  • 301
  • 2
  • 3
  • 8

3 Answers3

11

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.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
  • In a way I agree with you but don't you think it gets too verbose? "AllowedTo" and the prefix "is" kind of do the same thing. "AllowedTo" just makes it more grammatically readable. – Tn Hn Oct 31 '16 at 10:37
  • @TnHn - It may sound verbose, but, still it is very much readable and easier to understand. The usefulness of "allowed to" is just to make the name stand grammatically correct. And, you should not use `enum` for such trivial cases; it will only add to code being complex to understand and execute! – Am_I_Helpful Oct 31 '16 at 10:57
2

Many frameworks still use method calls to set values on beans, and those methods need to conform to a certain pattern:

isXXX or getXXX

So I try to stick to that, even if I'm not using frameworks to create instances of the beans, or if those frameworks use reflection to bind straight to the variables instead. I still think it's good practice.

So getUserCanLeave()? Or isUserLeavable()?

David Lavender
  • 8,021
  • 3
  • 35
  • 55
2

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.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102