Search code examples
javaclassfieldencapsulation

Encapsulation - use getters in same class?


Let's assume I have this simplified class:

public class Employee {
   private final String name;
   private int age;
   private int salary;


   public Employee(String name, int age, int salary) {
      name = name;
      age = age;
      salary = salary;
   }

   public Employee(Employee copyEmployee) {
      name = copyEmployee.name;
      age = copyEmployee.age;
      salary = copyEmployee.salary;
   }

   public void riseSalary() {
      if(age > 40) {
         salary += 500;
      }
   }

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public int getSalary() {
      return salary;
   }

   private void setSalary(int salary) {
      salary = salary;
   }
}

I have my fields declared as private. And am offering access to their values to the outside via getName(), getAge() and getSalary().

Would proper encapsulation require me to only access those fields from within the class-methods as well?

e.g.

public void riseSalara() {
   if(getAge() > 40) {
      setSalary(getSalary()+500);
   }
}

Or use them in my copy-constructor where I can access the private fields because it's the same class-type?

I have to write a class for an assignment and part of it is to "use encapsulation". However, the classfields only need to be accessed by the same object or a different object of the same class. How far should one go with encapsulation?


Solution

  • Encapsulation is about putting a thing into a capsule so that from the outside it looks neat and tidy. What you do on the inside is your choice.

    The goal is in a way, making it possible to write the ugliest code ever exposed via a nice interface. You may change the code in that class every day but not the interface because it needs to hide the "implementation details".

    It sometimes makes sense to use internal getters and setters, especially if that reduces code duplication, e.g. when there are rules that need to be enforced in the setter. Treat setters and getters as a method at your disposal. They are not mandatory (in my opinion, "correct" OO is always a matter of opinions.)