Can Renaming a Method Preserve Encapsulation?

class-designencapsulationgettersobject-orientedsetters

I was reading this page, about when getters/setters are justified, and the OP gave the following code sample:

class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);        
}

The accepted answer states:

By the way, in your example, I would give the class Fridge the
putCheese() and takeCheese() methods, instead of get_cheese()
and set_cheese(). Then you would still have encapsulation.

How is encapsulation preserved by renaming it from get/set to putCheese()/takeCheese() You're obviously getting/setting a value, so why not simply leave it as get/set?

In the same answer it also states:

Having getters and setters does not in itself break encapsulation.
What does break encapsulation is automatically adding a getter and a
setter for every data member (every field, in java lingo), without
giving it any thought.

In this case, we only have one variable, cheese, and you may want to take and return the cheese to the fridge, so a get/set pair in this case is justified.

Best Answer

I think you are missing the point. Its not saying you should rename the setter and getter, but to have methods which add and remove items from the fridge. ie

public class Fridge
{
    private int numberOfCheeseSlices;

    public void AddCheeseSlices(int n)
    {
         if(n < 0) { 
             throw new Exception("you cant add negative cheese!");
         }
         if(numberOfCheeseSlices + n > this.capacityOfFridge) { 
             throw new Exception("TOO MUCH CHEESE!!");
         }
         ..etc
         this.numberOfCheeseSlices += n;
    }
}

Now the private variable is encapsulated. I cant just set it to anything I want, I can only add and remove cheese slices from the fridge using the methods, which in turn ensure that whatever cheese business logic rules I want are applied.

Related Topic