第十四条 在公有类中使用访问方法而非公有域

在一个类中,往往有着各种属性。根据属性的访问级别,可以直接调用或者通过方法调用,获取属性值。本章就一句重点,通过对外暴露方法获取属性值,把属性值私有,防止直接调用。
反例 
public class Point {
    public int x;
    public int y;

    public Point() {}

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

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

public class Rect  {
    public int left;
    public int top;
    public int right;
    public int bottom;

    public Rect() {}

    public Rect(int left, int top, int right, int bottom) {
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
    }
}

这两个例子,一般使用都是  
     Point p = new Point();
     p.x = 3;
     p.y = 5;

    Rect rect = new Rect();
    rect.left = 6;

以上两种写法是典型的反例,直接把属性public对外开放,很危险,一不留神哪里改动了,如果不知道的话,程序不会报错,但数据会错误,并且还不好排查原因,好的指导原则就是讲点属性访问权
限,增加对外访问或赋值的方法。修改为

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

        public Point() {}

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

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

        public int getX() {
            return x;
        }

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

        public int getY() {
            return y;
        }

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

    public class Rect  {
        public int left;
        public int top;
        public int right;
        public int bottom;

        public Rect() {}

        public Rect(int left, int top, int right, int bottom) {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

        public int getLeft() {
            return left;
        }

        public void setLeft(int left) {
            this.left = left;
        }

        public int getTop() {
            return top;
        }

        public void setTop(int top) {
            this.top = top;
        }

        public int getRight() {
            return right;
        }

        public void setRight(int right) {
            this.right = right;
        }

        public int getBottom() {
            return bottom;
        }

        public void setBottom(int bottom) {
            this.bottom = bottom;
        }
    }

访问改为
    Point p = new Point();
    p.setX(3);
    p.setY(5);

    Rect rect = new Rect();
    rect.setLeft(6);


如果要进行一些校验或约束,可以在方法里开始的时候先对参数进行校验,如果不符合要传入的值,直接抛异常提醒开发者。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值