• The solution to duplicated code


    The solution to duplicated code involves twe steps(Extraction and Invocation) that would be explained in detail in subsequent section.

    Extraction means that programmer need to extract the duplicated code into a method defined in a class. You can add a new class or modify existing class to include the method. If you are sure that the method is invoked within only one class, it shoud be defined as private method. otherwise, the access specifier of the method should be public or others.

    Invocation just means invoking the method described above. Invocation contains direct invocation and indirect invocation.
    Direct invocation looks like this:
    class caller {
    callerMethod { callee.calleeMethod() }
    }
    The method invoked directly is typically used as utility method.

    The way of indirect invocation contains Factory Pattern, IoC/DI and AOP. The method invoked indirectly by Factory Pattern or IoC/DI is generally used as shared business logic. Considering the case: many places in program need to call a method, but some places need to keep the logic and some places need to change the logic. In this case, Directly invocation would have problem with it. Because the methed invocation expression in caller methods are still duplicated. the solution to this case is to introduce a interface to replace the concrete implementation, then use Factory Pattern to generate the concrete instance or use IoC/DI to inject the instance. thus we can get away with changing caller method. For Factory Pattern caller need to depend on factory, while IoC/DI don't have such problem.

    The method invoked indirectly by AOP is generally used as base/system service. Considering the case: the system service cross the business logic or some place need to remove the system service. In this case, AOP is the best solution.

  • 相关阅读:
    ORACLE数据库逐步解决ORA-12541、ORA-01034和ORA-27101、ORA-00119和ORA00132的过程
    Windows下MySQL主从复制的配置
    Windows下Git的使用
    spring boot 2 集成JWT实现api接口认证
    spring boot 2 全局统一返回RESTful风格数据、统一异常处理
    spring boot 2 + shiro 实现权限管理
    Java 密码加盐
    Java中往zip压缩包追加文件
    IntelliJ IDEA 安装、配置和使用Lombok插件
    大规模微服务单元化与高可用设计
  • 原文地址:https://www.cnblogs.com/tsai-87/p/10983454.html
Copyright © 2020-2023  润新知