Can renaming a method preserve encapsulation?

by QueenSvetlana   Last Updated August 13, 2019 13:05 PM - source

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.



Answers 1


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.

Ewan
Ewan
August 13, 2019 12:48 PM

Related Questions


Encapsulation and Displaying Information

Updated June 28, 2017 15:05 PM

Hide access to field associated with property in C#

Updated August 02, 2019 14:05 PM

How exactly are getters and setters defined?

Updated May 25, 2017 12:05 PM