简体   繁体   English

封装-在同一个类中使用吸气剂?

[英]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(). 并且正在通过getName(),getAge()和getSalary()向外部提供对其值的访问。

Would proper encapsulation require me to only access those fields from within the class-methods as well? 适当的封装是否也需要我仅从类方法中访问这些字段?

eg 例如

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? 封装应该走多远?

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, eg when there are rules that need to be enforced in the setter. 有时使用内部的getter和setter是有意义的,尤其是在减少代码重复的情况下,例如在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.) 它们不是强制性的(在我看来,“正确”的OO总是有意见的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM