zoukankan      html  css  js  c++  java
  • 写让别人能读懂的代码

    教程:http://saebbs.com/forum.php?tid=37496&page=1&extra=&mod=viewthread

    一.DRY(Don't repeat yourself)
    此原则如此重要,简单来说是因为:
    代码越少,Bug也越少
    没有重复逻辑的代码更易于维护,当你修复了一个bug,如果相同的逻辑还出现在另外一个地方,而你没意识到,你有没有觉得自己很冤? 

    1、

    良好的代码命名完全可以替代注释的作用,如果你正在试图写一段注释,从某种角度来看,你正在试图写一段别人无法理解的代码。

    当你无法为你的方法起一个准确的名称时,很可能你的方法不止做了一件事,违反了(Do one thing)。特别是你想在方法名中加入:And,Or,If等词时

     2、为布尔变量赋值:很好的例子,虽然比较特殊,但是慢慢体会

    public bool IsAdult(int age)
    
    {
    
        bool isAdult;
    
        if (age > 18)
    
        {
    
            isAdult = true;
    
        }
    
        else
    
        {
    
            isAdult = false;
    
        }
    
        return isAdult;
    
    }
    简化后
    public bool IsAdult(int age)
    
    {
    
        var isAdult = age > 18;
    
        return isAdult;
    
    }
    

    3、拒绝hardcord

    if (carName == "Nissan")
    
    {
    
    
    }
    更改后
    if (car == Car.Nissan)
    
    {
    
    
    }
    

    4、拒绝魔数:所谓魔数(Magic number)就是一个魔法数字,读者完全弄不明白你这个数字是什么

    if (age > 18)
    
    {
    
    
    }
    
    
    重构后:
    
    const int adultAge = 18;
    
    if (age > adultAge)
    
    {
    
    
    }
    

    5、复杂的条件判断:使用其他的函数来简化

    iif (job.JobState == JobState.New
    
        || job.JobState == JobState.Submitted
    
        || job.JobState == JobState.Expired
    
        || job.JobTitle.IsNullOrWhiteSpace())
    
    {
    
        //....
    
    }
    
    
    重构后:
    
    if (CanBeDeleted(job))
    
    {
    
        //
    
    }        
    
    
    private bool CanBeDeleted(Job job)
    
    {
    
        var invalidJobState = job.JobState == JobState.New
    
                              || job.JobState == JobState.Submitted
    
                              || job.JobState == JobState.Expired;
    
        var invalidJob = string.IsNullOrEmpty(job.JobTitle);
    
    
        return invalidJobState || invalidJob;
    
    }
    

    6、嵌套判断

    var isValid = false;
    
    if (!string.IsNullOrEmpty(user.UserName))
    
    {
    
        if (!string.IsNullOrEmpty(user.Password))
    
        {
    
            if (!string.IsNullOrEmpty(user.Email))
    
            {
    
                isValid = true;
    
            }
    
        }
    
    }
    
    return isValid;
    
    
    重构后:
    
    if (string.IsNullOrEmpty(user.UserName)) return false;
    
    if (string.IsNullOrEmpty(user.Password)) return false;
    
    if (string.IsNullOrEmpty(user.Email)) return false;
    
    return true;
    

    7、使用前置条件:写的真是好

    if (!string.IsNullOrEmpty(userName))
    
    {
    
        if (!string.IsNullOrEmpty(password))
    
        {
    
            //register
    
        }
    
        else
    
        {
    
            throw new ArgumentException("user password can not be empty");
    
        }
    
    }
    
    else
    
    {
    
        throw new ArgumentException("user name can not be empty");
    
    }
    
    
    重构后:
    
    if (string.IsNullOrEmpty(userName)) throw new ArgumentException("user name can not be empty");
    
    if (string.IsNullOrEmpty(password)) throw new ArgumentException("user password can not be empty");
    
    //register
    

    8、参数过多,超过3个:过多的参数让读者难以抓住代码的意图,同时过多的参数将会影响方法的稳定性。另外也预示着参数应该聚合为一个Model

    public void RegisterUser(string userName, string password, string email, string phone)
    
    {
    
    
    }
    
    
    重构后:
    
    public void RegisterUser(User user)
    
    {
    
    
    }
          
    

    9、方法参数中有布尔值:布尔参数在告诉方法不止做一件事,违反了Do one thing

    public void RegisterUser(User user, bool sendEmail)
    
    {
    
    
    }
    
    
    重构后:
    
    public void RegisterUser(User user)
    
    {
    
    
    }
    
    
    public void SendEmail(User user)
    
    {
    
    
    }
    

    10、具有表现力的代码:相对于命令式代码,声明性代码更加具有表达力,也更简洁。这也是函数式编程为什么越来越火的原因之一。

    private string CombineTechnicalBookNameOfAuthor(List<Book> books, string author)
    
    {
    
        var filterBooks = new List<Book>();
    
    
        foreach (var book in books)
    
        {
    
            if (book.Category == BookCategory.Technical && book.Author == author)
    
            {
    
                filterBooks.Add(book);
    
            }
    
        }
    
        var name = "";
    
        foreach (var book in filterBooks)
    
        {
    
            name += book.Name + "|";
    
        }
    
        return name;
    
    }
    
    
    重构后:
    
    private string CombineTechnicalBookNameOfAuthor(List<Book> books, string author)
    
    {
    
         var combinedName = books.Where(b => b.Category == BookCategory.Technical)
    
             .Where(b => b.Author == author)
    
             .Select(b => b.Name)
    
             .Aggregate((a, b) => a + "|" + b);
    
    
         return combinedName;
    
    }
    

      

      

      

      

     

  • 相关阅读:
    Mysql 安装
    网站搭建 so easy
    git 命令!!!!!!!!!!!
    git branch 管理常用命令
    Java开发环境的搭建以及使用eclipse从头一步步创建java项目
    git 放弃本地修改 强制更新
    java算法之猴子排序睡眠排序
    sql业务需求,查询每个分类下的前两n条数据
    mysql安装
    linux服务自启
  • 原文地址:https://www.cnblogs.com/wang-jing/p/4850123.html
Copyright © 2011-2022 走看看