防御式编程

场景

证券交易终端支持市中核算,必须需要处理当日的委托和成交数据,现系统的委托和成交在本地缓存和远端缓存中各有一份。

思路:

核算优先使用本地缓存,本地缓存不存在那么就(防御式)取远端缓存。

实现

package demo.design.defensive;

/**
 * 
 * 作者: YUGY 
 * 项目:demo-design-defensive
 * 场景:证券交易终端支持市中核算,必须需要处理当日的委托和成交数据,
 *       现系统的委托和成交在本地缓存和远端中各有一份。
 * 思路:核算优先支持本地缓存,本地缓存不存在那么就(防御式)取远端缓存。
 * 日期:2018年5月21日
 * 备注:
 */
public class Defensive {
    public final static Integer nearOrder = 1 << 1;
    public final static Integer nearMatch = 1 << 2;
    public final static Integer farOrder = 1 << 3;
    public final static Integer farMatch = 1 << 4;

    //默认取本地缓存的委托和成交数据
    public static Integer options = nearOrder | nearMatch;

    public static void main(String[] args) {
        doWithNearOrder();
        doWithFarOrder();

        doWithNearMatch();
        doWithFarMatch();
    }

    private static void doWithNearOrder() {
        if ((options & nearOrder) != nearOrder)
            return;
        try {
            System.out.println("nearOrder处理");
        } catch (Exception e) {
            options |= farOrder;
        }
    }

    private static void doWithFarOrder() {
        if ((options & farOrder) != farOrder)
            return;
        System.out.println("farOrder处理");
    }

    private static void doWithNearMatch() {
        if ((options & nearMatch) != nearMatch)
            return;
        try {
            System.out.println("nearMatch处理");
        } catch (Exception e) {
            options |= farMatch;
        }
    }
    private static void doWithFarMatch() {
        if ((options & farMatch) != farMatch)
            return;
        System.out.println("farMatch处理");
    }

延伸

1.假设我们不考虑防御式编程而根据实时的需要去决定使用本地或者远端缓存,那么更简洁的代码如下:

        doWithNearOrder();
        //doWithFarOrder();

        doWithNearMatch();
        //doWithFarMatch();
好处是非常快速简单,缺点是一旦需要对具体的业务逻辑做修改,很难强求其他的程序员去对已经注释的代码里面的内容也做相应的调整并充分测试,者就导致将来需要从本地缓存切换到远端缓存的时候,程序出现运行错误的情况。

你可能感兴趣的:(设计和思想)