zoukankan      html  css  js  c++  java
  • [代码重构]利用单一职责原则(SRP)封装函数

    原始的设计:

    ///<summary>
    /// 修改密码
    ///</summary>
    ///<param name="id">主键</param>
    ///<param name="oldPassword">原密码</param>
    ///<param name="newPassword">新密码</param>
    ///<returns></returns>
    publicbool ChangePassword(int id, string oldPassword, string newPassword)
    {
    oldPassword
    = EncodeHelper.MD5(oldPassword.Trim());
    newPassword
    = EncodeHelper.MD5(newPassword.Trim());

    if (!oldPassword.Equals(this.GetStudent(id).LoginPassword))
    returnfalse;

    returnthis.UpdateStudent(new Student() { ID = id, LoginPassword = newPassword });
    }

    重构的设计:

    ///<summary>
    /// 修改密码
    ///</summary>
    ///<param name="id">主键</param>
    ///<param name="oldPassword">原密码</param>
    ///<param name="newPassword">新密码</param>
    ///<returns></returns>
    publicbool ChangePassword(int id, string oldPassword, string newPassword)
    {
    returnthis.ValidateOldPassword(id, oldPassword) &&this.SaveNewPassword(id, newPassword);
    }

    ///<summary>
    /// 验证原密码
    ///</summary>
    ///<param name="id">主键</param>
    ///<param name="oldPassword">原密码</param>
    ///<returns></returns>
    privatebool ValidateOldPassword(int id, string oldPassword)
    {
    oldPassword
    = EncodeHelper.MD5(oldPassword.Trim());
    return oldPassword.Equals(this.GetStudent(id).LoginPassword);
    }

    ///<summary>
    /// 保存新密码
    ///</summary>
    ///<param name="id">主键</param>
    ///<param name="newPassword">新密码</param>
    ///<returns></returns>
    privatebool SaveNewPassword(int id, string newPassword)
    {
    newPassword
    = EncodeHelper.MD5(newPassword.Trim());
    returnthis.UpdateStudent(new Student() { ID = id, LoginPassword = newPassword });
    }

    总结:

    1. 重构后的ChangePassword函数,职责更单一,逻辑也更清晰了。

    2. 原来的"验证原密码",和"保存新密码"的逻辑都重新定义到了单独的私有函数。对ChangePassword函数可能的变化进行了封装和隔离。

    3. ChangePassword函数返回的方式采用"逻辑与"的表达式进行运算返回,这样可以有效的"前置"了"验证原密码"逻辑错误的情况,做到了函数的提前返回。

  • 相关阅读:
    <Learning How to Learn>Week One: Focused versus Diffuse Thinking
    "Principles of Reactive Programming" 之<Actors are Distributed> (2)
    "Principles of Reactive Programming" 之<Actors are Distributed> (1)
    "reactive programming"的概念
    "Principles of Reactive Programming" 之 <Persistent Actor State>学习笔记
    从List[Future[T]]到Future[List[T]]
    用IDEA调试Play工程
    Scala的Pattern Matching Anonymous Functions
    Akka的fault tolerant
    Manifest 与TypeTag
  • 原文地址:https://www.cnblogs.com/JavCof/p/2005067.html
Copyright © 2011-2022 走看看