封装的魅力

本文探讨了封装在编程中的重要性,强调信息隐藏和限制外部访问接口以保护数据的安全。通过示例展示了不恰当的封装可能导致的问题,并提供了一个优化后的Wallet类,该类仅允许增加和减少余额,从而提高了代码的易用性和数据安全性。封装可以防止外部随意修改数据,降低错误使用的可能性,使得类的使用者无需了解内部实现细节。
摘要由CSDN通过智能技术生成

简介

以前创建一个model,全都设置为private 属性,然后都是无脑的getter和setter来获取和设置值,自从看了一篇文章后对封装有了新的了解

封装的意义是什么

1.信息隐藏

2.类通过保留有限的访问接口,外部访问仅能通过类提供的方式(或函数)来访问内部信息或者数据

通过访问权限控制,隐藏内部数据,外部仅能通过类提供的有限的接口访问、修改内部数据

反例

public class Wallet {
    private String id;
    private long createTime;
    private BigDecimal balance;
    private long balanceLastModifiedTime;

    /**
     * shit code :
     *
     * @param id
     * @param createTime
     * @param balance
     * @param balanceLastModifiedTime
     */
    public Wallet(String id, long createTime, BigDecimal balance, long balanceLastModifiedTime) {
        this.id = id;
        this.createTime = createTime;
        this.balance = balance;
        this.balanceLastModifiedTime = balanceLastModifiedTime;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(long createTime) {
        this.createTime = createTime;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public long getBalanceLastModifiedTime() {
        return balanceLastModifiedTime;
    }

    public void setBalanceLastModifiedTime(long balanceLastModifiedTime) {
        this.balanceLastModifiedTime = balanceLastModifiedTime;
    }
}

以上代码有一下缺点:

id可以在类内部生成

createTime:不应该暴露set方法,在对象构造的时候才会被赋值

balanceLastModifiedTime:不应该暴露 set方法,在改变balance才会被赋值

balance:默认初始化为0,只有加,减两种情况,不应该暴露set方法

如果我们将属性封装起来,暴露少许的几个必要的方法给调用者使用,调用者就不需要了解太多背后的业务细节,用错的概率就减少很多

就比如你买电视给你一个遥控板,你直接使用遥控板操作电视就行了~,而不是把电视的内部原理图给你,然后让你输出高低电平来控制电视

优美的代码

package p2.code.obj.lab_05_01_nice;

import java.math.BigDecimal;
import java.util.UUID;

public class Wallet {
    private String id;
    private long createTime;
    private BigDecimal balance;
    private long balanceLastModifiedTime;

    public Wallet() {
        this.id = UUID.randomUUID().toString();
        this.createTime = System.currentTimeMillis();
        this.balance = BigDecimal.ZERO;
        this.balanceLastModifiedTime = System.currentTimeMillis();
    }

    public String getId() {
        return this.id;
    }

    public long getCreateTime() {
        return this.createTime;
    }

    public BigDecimal getBalance() {
        return this.balance;
    }

    public long getBalanceLastModifiedTime() {
        return this.balanceLastModifiedTime;
    }

    public void increaseBalance(BigDecimal increasedAmount) throws InvalidAmountException {
        if (increasedAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new InvalidAmountException("无效的数量");
        }
        this.balance.add(increasedAmount);
        this.balanceLastModifiedTime = System.currentTimeMillis();
    }

    public void decreaseBalance(BigDecimal decreasedAmount) throws InvalidAmountException, InsufficientAmountException {
        if (decreasedAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new InvalidAmountException("无效的金额");
        }
        if (decreasedAmount.compareTo(this.balance) > 0) {
            throw new InsufficientAmountException("...");
        }
        this.balance.subtract(decreasedAmount);
        this.balanceLastModifiedTime = System.currentTimeMillis();
    }
}

封装的好处

1.保护数据:

防止外部随意修改 setBalance是可以修改为任意值(-1,-100)等,
但是实际业务角度来说钱包余额,只会有两种修改方式:增或减,缩小数据修改范围,让数据更安全,

2.易用性

时刻保持最小暴露,反而能提高易用性
如果暴露的是setBalance和setBalanceLastModifiedTime,外部调用者要熟悉业务,更改setBalance时要setBalanceLastModifiedTime

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值