Leonid Semyonov
Leonid Semyonov

Reputation: 387

Should I use getters and setters inside a class implementation?

Or it depends?

For example fictional class:

public class Worker {

    private boolean paused;

    public boolean isPaused() {
        return paused;
    }

    public void onIteration() {
        if (!paused) {
            doIteration();
        }
    }

}

Or would it be better if I use if isPaused() { } in the example above ?

Is there any rule about what I always must use?

Upvotes: 2

Views: 190

Answers (2)

Maroun
Maroun

Reputation: 96016

I would use the getter since it decides the internal logic. In your case there's no much logic, you simply return the value.

But consider a situation where isPaused will be changed to:

public boolean isPaused() {
   return isReallyPaused(paused);
}

Another reason I prefer to use getters,

If it was an int, I wouldn't take chance of changing it by mistake, and instead of writing if(myInt == 5) (that can be = by mistake), I would use if(getMyInt() == 5).

Upvotes: 3

David Limkys
David Limkys

Reputation: 5133

Well as a rule always use getters. why ?

Lets say you made it a public member and after 5 usages of this class you decide that now you need to add more logic in to this.

Now its paused only if A and B. Maybe the user does not have permission to view if isPauesd true or false.

How do you change this without breaking the outer usages of the class ?

You cant, but if you use a getter then its not problem:

public boolean isPaused() {
    if (hasPermissions){
       return isPaused;
    }

    throw newPermissionException();
}

I changed the code with out breaking the usages. In fact the users of this class don't even know of the change.

This is called encapsulation.

Upvotes: 1

Related Questions