首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >代码整洁之道

代码整洁之道

作者头像
用户9831583
发布2022-06-16 16:33:58
发布2022-06-16 16:33:58
4020
举报
文章被收录于专栏:码出名企路码出名企路

1.命名规范

1.1.模糊的命名
代码语言:javascript
复制
//代码的模糊度
public List<int[]> getThem(){
    List<int[]> list1 = new ArrayList<int[]>();
    for (int[] x : theList){
        if (x[0] == 4){
            list1.add(x);
        }
    }
    return list1;
}

疑问:

(1) theList中是什么类型? (2) theList 零下标意义是什么? (3) 值 4的意义是什么? (4) 怎么使用返回的列表?

改进:

代码语言:javascript
复制
public List<int[]> getFlaggedCells(){
    List<int[]> flaggedCells = new ArrayList<int[]>();
    for (int[] cell : gameBoard){
        if (cell[STATUS_VALUE] == FLAGGED){
            flaggedCells.add(x);
        }
    }
    return flaggedCells;
}

更进一步:

用类代替 int 数组表示单元格 同时包含一个函数 进行判断

代码语言:javascript
复制
public List<Cell> getFlaggedCells(){
    List<Cell> flaggedCells = new ArrayList<int[]>();
    for (Cell cell : gameBoard){
        if (cell.isFlagged()){
            flaggedCells.add(x);
        }
    }
    return flaggedCells;
}
1.2.语境不明确
代码语言:javascript
复制
private void printGuessStatistics(char candidate, int count){
    String number;
    String verb;
    String pluraModifier;
    if (count == 0){
        number = "no";
        verb = "are";
        pluraModifier = "s";
    }
    else if (count == 1){
        number = "1";
        verb = "is";
        pluraModifier = "";
    }
    else{
        number = Integer.toString(count);
        verb = "are";
        pluraModifier = "s";
    }
    String guessMessage = String.format(
        "%s %s %s %s",verb, number, candidate, pluraModifier);
    print(guessMessage);
}

优化:

(1)创建一个名为 GuessStatisticsMessage的类, 3个变量做成类的成员函数 (2)算法通过分解更小的函数

代码语言:javascript
复制
public class GuessStaticticsMesage{
    private String number;
    private String verb;
    private String pluraModifier;

    public String make(char candidate, int count){
        createPluralDependentMessageParts(count);
        return String.format("%s %s %s %s",verb, number, candidate, pluraModifier);
    }

    private void createPluralDependentMessageParts(int count){
        if (count == 0){
            thereAreNoLetters();
        }
        else if (count == 1){
            thereIsOneLetter();
        }
        else{
            thereAreManyLetters(count);
        }
    }

    private void thereAreManyLetters(int count){
        number = Integer.toString(count);
        verb = "are";
        pluraModifier = "s";
    }

    private void thereIsOneLetter(){
        number = "1";
        verb = "is";
        pluraModifier = "";
    }

    private void thereAreNoLetters(){
        number = "no";
        verb = "are";
        pluraModifier = "s";
    }
}

2.函数规则

编程系统由程序,子程序 和函数组成。

(1)函数的第一条规则是短小,第二条规则是还要更短小; (2)程序中每个函数都只有两行,三行或四行; (3)每个函数都一目了然,每个函数都只说一件事; (4)每个函数都依序把你带到下一个函数。

代码语言:javascript
复制
public static String renderPageWithSetupAndTearsdowns(
    PageData pageData, boolean isSuite) throws Exception {
        if (isTestPage(pageData))
            includeSetupAndTeardownPages(pageData, isSuite);
    return pageData.getHtml();
}
2.1.抽象Switch
代码语言:javascript
复制
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 InvalidEmplyeeType(e.type);
    }
}

缺点:

(1) 当出现新的雇员时候 函数会变得很长 (2)违反了单一职责原则 明显不是在做一件事 (3)违反了开闭原则 当添加新类型时候 就必须修改该函数

优化:

(1)switvh 语句隐藏在抽象工厂下面 该工厂使用 swith语句为 Rmployee的派生物创建适当的实体 (2) 不同的函数 calculatePay 由 Employee 接口多态地接口派遣

代码语言:javascript
复制
  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(e);
            case HOURLY:
                return new HourlyEmployee(e);
            case SALARIED:
                return new SalariedEmployee(e);
            default:
                throw new InvalidEmplyeeType(e.type);
        }
    }
  
  }
2.2.函数参数

(1)参数越少越好,最好没有参数 (2)不要带有输出参数 利用返回值代替 (3)如果函数看起来需要3个或以上参数,则说明其中一些参数需要封装成类了

代码语言:javascript
复制
   Circle makeCircle(double x,double y,double radius)
   circle makeCircle(Point cener,double radius)
3.3.异常处理
代码语言:javascript
复制
if (deliverPage(page) == E_OK){
    if (registry.deleteReference(page.name) == E_OK) {
        if (configkeys.deleteKey(page.name.makeKey()) == E_OK){
            logger.log("page deleted");
        }
        else{
            logger.log("configkey not delete");
        }
    }
    else{
        logger.log("deleteReference from registry failed");
    }
}
else{
    logger.log("delete failed");
}

优化:

(1) 使用异常代替错误代码 错误代码就能从主路径中分离出来

代码语言:javascript
复制
 try{
     deletePage(page);
     registry.deleteReference(page.name);
     configkey.deleteKey(page.name.makeKey());
 }
 catch (Exception e){
     logger.log(e.getMessage());
 }

更进一步:

把 try和 catch代码块的主体部分抽离出来 另形成函数

代码语言:javascript
复制
  public void delete(Page page){
      try{
          deletePageAndAllReferences(page);
      }
      catch (Exception e){
          logError(e);
      }
  }

  private void deletePageAndAllReferences(Page page) throws Exception {
    deletePage(page);
     registry.deleteReference(page.name);
     configkey.deleteKey(page.name.makeKey());
  }

 private void logError(Exeception e){
     logger.log(e.getMessage());
 
 }

3.注释格式

3.1.多余清除
代码语言:javascript
复制
//代码名称代替注释
//check to see if the employee is eligible for full benefits
if (employee.flags & HOURLY_FLAG && (employee.age > 65))
if (employee.isEligibleForFullBenefits())

//try - catch
private void startSending()
{
    try{
        doSending();
    }
    catch(SocketException e){
        //normal someone stopped the request
    }
    catch(Exception e){
        try{
            response.add(ErrorResponder.makeExceptionString(e));
            response.closeAll();
        }
        catch(Exception e){
            //give me a break;
        }
    }
}

/*
改进最后一个catch为一个函数 
 */

 private void startSending()
{
    try{
        doSending();
    }
    catch(SocketException e){
        //normal someone stopped the request
    }
    catch(Exception e){
       addExceptionAndCloseRespose(e);
    }
}

private void addExceptionAndCloseRespose(Exception e)
{
    try{
        response.add(ErrorResponder.makeExceptionString(e));
        response.closeAll();
    }
    catch(Exception e){
        
    }
}
3.2.格式遵守

(1)变量声明:尽可能靠近使用位置 循环语句中的变量放在循环中 (2)实体变量:java放在类的开头 C++放在类的 底部 (3)相关函数:若某个函数调用了另外一个 应该把他们放在一起 而且调用者应该放在被调用者上面 (4)概念相关:概念相关的代码放在一起 代码的相关性越强 彼此之间的距离越短

4.类结构体

4.1.过程和对象

面向过程设计:

代码语言:javascript
复制
public class Square{
    public Point topLeft;
    public double side;
}

public class Rectangle{
    public Point topLeft;
    public double height;
    public double width;
}

public class Circle{
    public Point center;
    public double radius;
}

public class Geometry{
    public final double PI = 3.1415926;

    public double area(Object shape) throws NoSUchShapeException{
        if (shape instanceof Square){
            Square s =(Square)shape;
            return s.side * s.side;
        }
        else if (shape instanceof Rectangle){
            Rectangle r = (Rectangle)shape;
            return r.height * r.width;
        }
        else if (shape instanceof Circle){
            Circle c = (Circle)shape;
            return PI * c.radius * c.radius;
        }
        throw new NoSUchShapeException();
    }
}

面向对象设计:

代码语言:javascript
复制
public class Square implements shape{
    private Point topLeft;
    private double side;

    public double area(){
        return side * side;
    }
}

public class Circle implements shape{
    private Point center;
    private double radius;
    public final double PI = 3.1415;

    public double area(){
        return PI * radius * radius;
    }
}

null值判断:

(1)别返回NULL; (2)别传递NULL;

4.2.类组织原则

Java约定:

类从一组变量列表开始, 变量出现顺序:

(1)public static (2)private static (3)private 实体变量 (4)public 实体变量很少有


本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-02-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码出名企路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.命名规范
    • 1.1.模糊的命名
    • 1.2.语境不明确
  • 2.函数规则
    • 2.1.抽象Switch
    • 2.2.函数参数
    • 3.3.异常处理
  • 3.注释格式
    • 3.1.多余清除
    • 3.2.格式遵守
  • 4.类结构体
    • 4.1.过程和对象
    • 4.2.类组织原则
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档