重構 001 - 刪除Java的Setter方法

banq發表於2021-11-18

Setter方法違反了不變性並新增了意外耦合!

重構步驟:

  1. 找到 setter 的用法
  2. 如果您正在設定基本屬性,請將它們移動到建構函式並刪除該方法
  3. 如果你需要改變一個偶然的屬性,它不是一個 setter。刪除 setXXX 字首

public class Point {
   protected int x;
   protected int y;

   public Point() {
        this.x = 0;
        this.y = 0;        
   }

   public void setX(int x) {
    this.x = x;
   }

   public void setY(int y) {
        this.y = y;
  } 
}

Point location = new Point();
//At this momment, it is not clear which points represent
//It is coupled to constructor decision.
//Might be null or some other convention

location.setX(1);
//Now we have point(1,0)

location.setY(2);
//Now we have point(1,2)

重構後的程式碼:

//1. We locate setters usage
location.setX(1);

location.setY(2);

//2. If you are setting essential properties move 
//them to the constructor and remove the method
public class Point {
   public Point(int x, int y) {
        this.x = x;
        this.y = y;        
     //We remove the setters
   }

Point location = new Point(1, 2);

  

另外一個案例:

public class Car {
   protected int speed;

   public Car() {     
   }

   public void setSpeed(Speed desiredSpeed) {
    this.speed = desiredSpeed;
   }   
}

Car tesla = new Car();
//We have no speed??

tesla.setSpeed(100 km/h);
//Now our car runs fast

重構後的程式碼:

public class Car {
   protected int speed;

   public Car() {    
     this.speed = 0 km/h;
   }

   public void speed(Speed desiredSpeed) {
        this.speed = desiredSpeed;
   }   
}


//1. Locate the setters usage
//3. If you need to change an accidental property
// it is not a setter. Remove the setXXX prefix


Car tesla = new Car();
//Our car is stopped

tesla.speed(100 km/h);
//We tell the desired speed. We don't set anything
//We don't care if the car stores its new speed.
//if it manages through the engine
//if the road is moving etc

我們應該用我們的 IDE 檢測 setter(除非他們使用超程式設計)。

如果我們有良好的覆蓋率,我們也可以刪除它們並檢視哪些測試失敗

相關文章