clean code(一)

代码整洁之道对于程序的重构及可读性至关重要。开始整洁之道吧!!!

一、抽离try catch 模块

    public void delete(Page page){
        try {
            deletePageAndAllReference(page);
        }catch(Exception e){
            logError(e);
        }
    }

    private void deletePageAndAllReference(){
        deletePage();
        registry.deleteRefence(page.name);
        configKeys.deleteKey(page.name.makeKey());
    }

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

将try和catch代码的主体部分抽离出来。delete只与错误处理有关,容易理解。deletePageAndAllReference只与完全删除一个page有关。

 二、注释

  好的注释尽量利用方法名称来传递信息。注释提供了有关实现的有用信息,而且还提供了某个决定后面的意图。用于警告会出现某种后果的注释也是有用的

    //TODO-MdM these are not need
    //we expected this to go away when we do the checkout model
    VersionInfo makeVersion() throws Exception{
        return null;
    }

  TODO: + 说明:在标识处有功能代码待编写,待实现的功能在说明中会简略说明。

  对于代码中多余的注释应该删除,可能读注释的时间都比读代码花费的时间都长。能用函数或变量时就别用注释。

三、格式

  每个项目开始之前都应该提前定义好团队规则,包括在什么地方放置括号、缩进几个字符、如何命名类、变量和方法等。

四、对象和数据结构

  过程式代码(使用数据结构的代码)便于在不改动既有数据结构的前提下添加新函数,面向对象代码便于在不改动既有函数的前提下添加新类。

    public class Square{
        public Point topLeft;
        public double side;
    }
    
    public class Rectabgle{
        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.141592653589793;
        
        public double area(Object shape){
            if (shape instanceof Square){
                Square s= (Square) shape;
                return s.side*s.side;
            }
            ...
        }
    }

 

原文地址:https://www.cnblogs.com/award/p/10012817.html