`
jacky1118sally
  • 浏览: 13142 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

switch(clean code)

阅读更多
看了《clean code》 关于 switch ,很有感触,给大家分享分享
首先 有这样的例子:
public Money calculatePay(Employee e)   throws InvalidEmployeeType {  
 switch (e.type) {     
  case COMMISSIONED:       
    return calculateCommissionedPay(e);     
  case HOURLY:        
    return calculateHourlyPay(e);     
  case SALARIED:        
    return calculateSalariedPay(e);      
  default:        
    throw new InvalidEmployeeType(e.type);  
  }  
} 

Payroll  这个对象 需要 根据 员工的不同来计算他们的工资,所以有这样的一个方法,返回 Money  用switch来区别type 然后做不同处理,这样也无可厚非。但是仔细想 确实是有问题的,首先雇员的类别有可能增加,那么这个switch 需要修改,而且会有 诸如isPayday(Employee e, Date date), 或 deliverPay(Employee e, Money pay)   这样的结构出现。确实是很头痛的事情。

看看书上是怎样 解决的
public abstract class Employee { 
   public abstract boolean isPayday();  
   public abstract Money calculatePay();  
   public abstract void deliverPay(Money pay); 
 }
  
 public interface EmployeeFactory {   
 public Employee makeEmployee(EmployeeRecord r) throws   InvalidEmployeeType;  
} 

public class EmployeeFactoryImpl implements EmployeeFactory{         

  public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType {    
   switch (r.type) {        
     case COMMISSIONED:          
       return new CommissionedEmployee(r) ;       
     case HOURLY:         
       return new HourlyEmployee(r);      
     case SALARIED:     
        return new SalariedEmploye(r);   
      default:         
         throw new InvalidEmployeeType(r.type);      
    }  } 
 }  
} 


使用工厂模式创建对象,创建不同对象,对于不同type的 区分,放到工厂下层,而不在上面体现,如此函数的 不同层级就很明确,而且使用Employee 抽象来完成 那几个动作。
设计 真的是体现了高手的 技术,层次,抽象,模型,这些虽然有时候仅仅没多少代码,但是都是精华,需要好好学习,像大师们学习。

分享到:
评论

相关推荐

    clean-code-smells-and-heuristics

    开发入门按照的说明进行操作。TL; 博士运行bundle exec jekyll serve 导航到localhost:4000

    clean-code-net:一组C#Roslyn分析器,以提高代码正确性

    确保在switch语句中涵盖所有可能的情况,以进行枚举和模式匹配。 考虑示例: enum TestEnum { Case1 , Case2 , Case3 } switch ( TestEnum . Case1 ) { case Test . TestEnum . Case1 : { break ; } case ...

    acpi控制笔记本风扇转速

    Additional cleanup and optimizations for the new Table Manager code. AcpiEnable will now fail if all of the required ACPI tables are not loaded (FADT, FACS, DSDT). BZ 477 Added #pragma pack(8/4) to ...

    01450A (1).pdf

    mechanical switch so that a clean signal can feed other circuitry. The application makes use of the Configurable Logic Cell (CLC) peripheral to produce fast switching on the output (if desired). If ...

    绘图MyPaintView执行文件

    // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CMyPaintView diagnostics #ifdef _DEBUG void CMyPaintView::AssertValid() const ...

    Amplify Shader Editor1.5.4 最新版

    INTUITIVE and UX-focused, the workspace is familiar, clean and flexible. Dock it, or use it in a second monitor, it’s prepared to fit your layout requirements. MINIMALISTIC toolbars and menus have ...

    Medical Chatbot Agent - using Langchain.rar

    In this code I am using GPT-4, but you have the flexibility to switch to any other supported model. Streamlit GUI: A clean and intuitive user interface built with Streamlit, making it accessible for ...

    BobBuilder_app

    You can switch to the SortedDictionary in the code at any time if you wish and it makes no difference to the overall code other than you can remove the sorting in the page splits. I also tried an ...

    Amplify Shader Editor 1.5.7

    • Full source-code • Support for Xbox One/PS4/Switch • Custom Node API • Shader Templates • Shader Functions • Multi-window Support • Intuitive, familiar node interface • Extensive node ...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed)....

    Git-2.21.0-64-bit.zip

    * Code cleanup and futureproof. * More parameter validation. * "git update-server-info" used to leave stale packfiles in its output, which has been corrected. * The server side support for ...

    Kwin Scripts

    * 1.6 (unreleased): Make resizing layout-agnostic, a manual tiling mode, code cleanup, fix tiling when compositing is disabled * 1.6.1: Respect min/maxSizes, multiple (or zero) master support in ...

    Sakemail

    Minor changes to the scanning code for the filename of attachments.1.8.2- Fixed a bug with the filename of attachments (thanks to Taufer Pavel Ing.).- Added the function IsIPAddress from hou yg (the ...

    C#100例题 献给c#初学者

    /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } }...

    缓冲区代码

    switch(get) { case 'q': quit=1; break; case 'r'://开始录像 alarm_rec_enable=1; break; case 's'://停止录像 alarm_rec_enable=0; break; default:break; } } ...

    用单片机设计的4位密码锁

    Electronic Code Lock is a password input through the control circuit, or chip, thus controlling the closed mechanical switch to complete the lock, closed the task of electronic products. It is of many...

    selenium-dotnet-2.45.0.zip

    Code cleanup and refactoring will take place under a separate commit. Note that there is still no support in the .NET bindings for the Presto-based Opera without using the remote server, nor is ...

    Kriging 算法实现 2维和3维地图等高线

    Because of the template, this doesn‘t look that clean but you can get the idea if you look at it carefully. The matrix solver is as follows:template<class T>void LUDecompose(TMatrix<T>& A, std::...

    Oracle sqldeveloper without jdk (win+linux)

    To switch the time zone used for formatting, change the client O/S time zone setting and restart SQL Developer. 4.4 Known Globalization Issues This version of SQL Developer has the following ...

    Bochs - The cross platform IA-32 (x86) emulator

    - added 'pseudo device' in common USB code for the device creation. This makes the HCs independent from the device specific code. - USB MSD: added support for disk image modes (like ATA disks) - ...

Global site tag (gtag.js) - Google Analytics