
《clean code》指出,要想写出好的代码,首先得知道什么是肮脏代码、什么是整洁代码;
然后通过大量的刻意练习,才能真正写出整洁的代码。
- 
Bjarne Stroustrup:优雅且高效;直截了当;减少依赖;只做好一件事
 - 
Grady booch:简单直接
 - 
Dave thomas:可读,可维护,单元测试
 - 
Ron Jeffries:不要重复、单一职责,表达力(Expressiveness)
 
命名的艺术
- 
不要挂羊头卖狗肉
 - 
不要覆盖惯用缩略语
 
如果名称读不出来,那么讨论的时候就会像个傻鸟 
名字长短应与其作用域大小相对应 
注释
The proper use of comments is to compensate for our failure to express ourself in code. 
    
    
    
     
     
     
 bad
 
     
     
     
// 
 
     
     
     check 
 
     
     
     to see 
 
     
     
     if the employee 
 
     
     
     is eligible 
 
     
     
     for 
 
     
     
     full benefit
 
     
     
     
 
     
     
     if ((employee.flags & HOURLY_FLAG) && (employee.age > 
 
     
     
     65))
 
     
     
     
 
     
     
     
good
 
     
     
     
 
     
     
     if (employee.isEligibleForFullBenefits())
    
    
     
- 
法务信息 
 - 
对意图的注释,为什么要这么做 
 - 
警示 
 - 
TODO注释 
 - 
放大看似不合理之物的重要性 
 
函数
    
    
    
 
     
     
     public 
 
     
     
     class UserValidator {
 
     
     
     
    
 
     
     
     private Cryptographer cryptographer;
 
     
     
     
    
 
     
     
     public 
 
     
     
     boolean checkPassword(
 
     
     
     String userName, 
 
     
     
     String password) {
 
     
     
     
        User user = UserGateway.findByName(userName);
 
     
     
     
        
 
     
     
     if (user != User.NULL) {
 
     
     
     
            
 
     
     
     String codedPhrase = user.getPhraseEncodedByPassword();
 
     
     
     
            
 
     
     
     String phrase = cryptographer.decrypt(codedPhrase, password);
 
     
     
     
            
 
     
     
     if (
 
     
     
     "Valid Password".equals(phrase)) {
 
     
     
     
                Session.initialize();
 
     
     
     
                
 
     
     
     return 
 
     
     
     true;
 
     
     
     
            }
 
     
     
     
        }
 
     
     
     
        
 
     
     
     return 
 
     
     
     false;
 
     
     
     
    }
 
     
     
     
}
    
    
     
    
    
    
 
     
     
     def 
 
     
     
     pushElephantIntoRefrige():
 
     
     
     
    
 
     
     
     openRefrige()
 
     
     
     
    
 
     
     
     pushElephant()
 
     
     
     
    
 
     
     
     closeRefrige()
    
    
     

测试
- 
You are not allowed to write any production code unless it is to make a failing unit test pass. 没有测试之前不要写任何功能代码 
 - 
You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures. 只编写恰好能够体现一个失败情况的测试代码 
 - 
You are not allowed to write any more production code than is sufficient to pass the one failing unit test. 只编写恰好能通过测试的功能代码 
 
本文分享自微信公众号 - Java后端(web_resource)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
相关文章
暂无评论...
