3、错误的面向对象

发布时间 2023-06-24 16:35:04作者: lidongdongdong~

1、滥用 getter、setter 方法

在之前参与的项目开发中,我经常看到有同事定义完类的属性之后,就顺手把这些属性的 getter、setter 方法都定义上
有些同事更加省事,直接用 IDE 或者 Lombok 插件(如果是 Java 项目的话)自动生成所有属性的 getter、setter 方法

当我问起,为什么要给每个属性都定义 getter、setter 方法的时候,他们的理由一般是
为了以后可能会用到,现在事先定义好,类用起来就更加方便,而且即便用不到这些 getter、setter 方法,定义上它们也无伤大雅

实际上这样的做法我是非常不推荐的
它违反了面向对象编程的封装特性,相当于将面向对象编程风格退化成了面向过程编程风格

public class ShoppingCart {

    private int itemsCount;
    private double totalPrice;
    private List<ShoppingCartItem> items = new ArrayList<>();

    public int getItemsCount() {
        return itemsCount;
    }

    public void setItemsCount(int itemsCount) {
        this.itemsCount = itemsCount;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public List<ShoppingCartItem> getItems() {
        return items;
    }

    public void addItem(ShoppingCartItem item) {
        items.add(item);
        itemsCount++;
        totalPrice += item.getPrice();
    }

    // ... 省略其他方法 ...
}