Can renaming a method preserve encapsulation?

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

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!!");
         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.

August 13, 2019 12:48 PM

Related Questions

Updated June 28, 2017 15:05 PM

Updated August 02, 2019 14:05 PM

Updated May 25, 2017 12:05 PM

Updated February 21, 2019 20:05 PM

Updated October 10, 2017 20:05 PM