zoukankan      html  css  js  c++  java
  • 重构27-Remove God Classes(去掉神类)

    在传统的代码库中,我们常常会看到一些违反了SRP原则的类。这些类通常以Utils或Manager结尾,有时也没有这么明显的特征而仅仅是普通的包含多个功能的类。这种God类还有一个特征,使用语句或注释将代码分隔为多个不同角色的分组,而这些角色正是这一个类所扮演的。 
    久而久之,这些类成为了那些没有时间放置到恰当类中的方法的垃圾桶。这时的重构需要将方法分解成多个负责单一职责的类。
    public class CustomerService {
    public Double CalculateOrderDiscount(List<Product> products, Customer customer) {
    // do work
    }
    public Boolean CustomerIsValid(Customer customer, Order order) {
    // do work
    }
    public List<String> GatherOrderErrors(List<Product> products, Customer customer) {
    // do work
    }
    public void Register(Customer customer) {
    // do work
    }
    public void ForgotPassword(Customer customer) {
    // do work
    }
    }
    使用该重构是非常简单明了的,只需把相关方法提取出来并放置到负责相应职责的类中即可。这使得类的粒度更细、职责更分明、日后的维护更方便。上例的代码最终被分解为两个类:
    public class CustomerOrderService {
    public Double CalculateOrderDiscount(List<Product> products, Customer customer) {
    // do work
    }
    public Boolean CustomerIsValid(Customer customer, Order order) {
    // do work
    }
    public List<String> GatherOrderErrors(List<Product> products, Customer customer) {
    // do work
    }
    }

    public class CustomerRegistrationService {
    public void Register(Customer customer) {
    // do work
    }
    public void ForgotPassword(Customer customer) {
    // do work
    }
    }







  • 相关阅读:
    vue简单的富文本实现(亲测可以)
    做手机兼容性看友盟手机统计
    压测并发数上不去的原因分析(泽嵩大佬说的)
    跨域问题解决
    jmeter压力测试报Address already in use: connect错误
    选择器(可搜索)+气泡提示组件
    2020
    Redis集群搭建采坑总结
    echarts自定义背景图片
    百度ECharts地图Json数据在线下载(geoJson)
  • 原文地址:https://www.cnblogs.com/jgig11/p/5786448.html
Copyright © 2011-2022 走看看