zoukankan      html  css  js  c++  java
  • 程序中的魔鬼数字

      在代码中使用魔鬼数字(没有详细含义的数字、字符串等)将会导致代码难以理解,应该将数字定义为名称有意义的常量。

       将数字定义为常量的终于目的是为了使代码更easy理解,所以并非仅仅要将数字定义为常量就不是魔鬼数字了。假设常量的名称没有意义,无法帮助理解代码,相同是一种魔鬼数字。

       在个别情况下,将数字定义为常量反而会导致代码更难以理解,此时就不应该强求将数字定义为常量。

    案例

    // 魔鬼数字,无法理解3详细代表产品的什么状态

    if (product.getProduct().getProductStatus() != 3)

    {

        throw new PMSException(PMSErrorCode.Product.ADD_ERROR);

    }

    // 仍然是魔鬼数字,无法理解NUM_THREE详细代表产品的什么状态

    if (product.getProduct().getProductStatus() != NUM_THREE)

    {

        throw new PMSException(PMSErrorCode.Product.ADD_ERROR);

    }

    //样例中尽管将数字定义为了常量,但代码却并不easy理解

    Point drawCenter = new Point();

    drawCenter.x = parentWindow.x + (parentWindow.width - clientWindow.width) / HALF_SIZE_DIV;

    drawCenter.y = parentWindow.y + (parentWindow.height - clientWindow.height) / HALF_SIZE_DIV;

    return drawCenter;

    //直接使用数字,代码反而更easy理解

    Point drawCenter = new Point();

    drawCenter.x = parentWindow.x + (parentWindow.width - clientWindow.width) / 2;

    drawCenter.y = parentWindow.y + (parentWindow.height - clientWindow.height) / 2;

    return drawCenter;

  • 相关阅读:
    Q15格式表示负小数
    音频算法处理笔试面试题
    有符号和无符号之间的转化
    PE5 Smallest multiple
    PE3 Largest prime factor(最大素数因子)
    PE2 Even Fibonacci numbers(最大菲波那列偶数)
    PE 4 Largest palindrome product(最大回文)
    PE1 Multiples of 3 and 5
    Codevs高精度入门(减法、加法和乘法)解题报告
    计算机网络学习笔记(二) 计算机网络结构
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/3901129.html
Copyright © 2011-2022 走看看