Avoid Write-only Code(MATLAB编程风格学习)

官方文档

命名规约

变量

  • 大小写混合的变量名以小写字母开头
  • 尽量不使用下划线
  • 名字长度和作用域范围正相关
  • 前缀n表示对象个数; m表示行数, 如mRows
  • 变量单复数的区分point, pointArray, PointList, thisPoint(一般不用thePoint)
  • entity number: tableNo, employeeNo; named iterator: iTable, iEmployee
for iFile = 1:nFiles
    for jPosition = 1:nPositions
        :
    end
    :
end
  • 避免使用否定变量名: isNotFound, 而是使用isFound~isFound
  • 专有名词的全大写特性被削弱: html, isUsaSpecific, checkTiffFormat(), 而不是hTML, isUSASpecific, checkTIFFFormat()
  • 避开保留字, 可以使用iskeyword命令查看.
>> iskeyword
ans =
    {'break'     }
    {'case'      }
    {'catch'     }
    {'classdef'  }
    {'continue'  }
    {'else'      }
    {'elseif'    }
    {'end'       }
    {'for'       }
    {'function'  }
    {'global'    }
    {'if'        }
    {'otherwise' }
    {'parfor'    }
    {'persistent'}
    {'return'    }
    {'spmd'      }
    {'switch'    }
    {'try'       }
    {'while'     }
  • 使用圈里人的行话: roi, regionOfInterest, 而不是imageRegionForAnalysis
  • 避免和标准函数重名, 如alpha, angle, axes, axis, balance, beta, contrast, gamma, image, info, input, length, line, mode, power, rank, run, start, text, type 增加单位后缀或者形容词/名词前缀: lengthCm, armLength, thisLength
  • 避免使用匈牙利命名法(1 or 2 prefixes, a name root, and a qualifier suffix)

    常量

  • m-文件中使用全大写和下划线的组合
  • 函数输出常量命名全小写或者大小写混合
  • 可添加常见类型名字前缀COLOR_RED, COLOR_GREEN, COLOR_BLUE

结构体

  • 大写字母开头
  • 不应包含域名
  • 注意避免新建当作修改

函数

  • 小写或者大小写混合
  • 使用有意义的函数名,避免令人费解的缩写, 约定俗成的缩略形式除外: max, gcd(在头部注释中详细说明)
  • 按照输出命名
  • 如果没有返回参数或者只返回句柄应在执行之后命名
  • 前缀:get, set, compute, initialize; 不建议使用find(除非真的是查找功能), make, init
  • 布尔类型: isOverpriced, iscomplete, hasLicense, canEvaluate, shouldSort
  • 互补的名字:
    get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, open/close, show/hide, suspend/resume, etc
  • 检查重载: which -all or exist, 多态

通用

  • Consider a unit suffix
  • Minimize abbreviations
  • Consider making names pronounceable
  • Write names in English

语句

变量和常量

  • 变量不应该重用除非受内存限制
  • 在文件开头以注释的形式说明

全局量

  • 尽可能少使用全局变量和常量

循环

  • 在循环前初始化——预分配
result = nan(nEntries,1);
for index = 1:nEntries
result(index) = foo(index);
end
  • 尽可能少使用breakcontinue
  • 在循环体最后一步增加必要的注释

条件

  • 避免复杂的条件语句
  • if-else语句中, 常见的情况写在if分句
  • 不使用if 0
  • switch一定使用otherwise
  • if表达式; switch变量

通用

“A month from now, if I look at this code, will I understand what it’s doing?”

  • 使用小括号
  • 减少表达式中数字的数量
  • 小数点前要有数字
  • 注意浮点数的比较, 尤其是很小的数
  • 使用自然直接的逻辑表达式
  • 异常处理机制
  • 使用函数输入合法性检查
  • 尽量避免使用eval
  • 尽可能写成函数
  • 尽量减少键盘输入

层次、注释和文档

层次

  • 80列
  • 分行: 逗号、空格、操作符、连续操作符(…)
  • 3或4格缩进
  • 每行一条执行语句
  • if, for, while每行一条

空格

  • 逗号后
  • 关键词后
  • 逻辑语句群
  • 分离语句块%%
  • 对齐增加可读性

注释

  • 易读
  • 英文
  • 头注释
    1. 函数行下%
    2. 函数前
  • 函数语法
  • 输入输出参数
  • 副作用
  • 函数名大小写不变
  • 不写版权和版本变更历史
  • why or how rather than what
  • 缩进格式同代码
  • 尽可能少使用循环末代码
  • 头注释: 用户
  • 内嵌注释: 程序员

文件与组织

m文件

  • 模块化
  • 清晰的交互
  • 划分
  • 使用存在的函数
  • 在多个文件中出现的代码写成函数
  • 使用结构体代替函数参数
  • 函数的通用性
  • 尽量减少使用定义在m文件外的子函数(尤其仅使用一次的函数)
  • 为每一个函数构造测试脚本
    “More than the act of testing, the act of designing tests is one of the best bug preventers known.”

输入和输出

  • 将输入输出模块化
  • 格式化输出以便于使用: 易于解析+格式化函数
  • 使用feof读文件

工具箱

  • 合理使用工具箱

风格箴言

Martin Fowler: “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
愚蠢的人写的代码是给计算机读的,优秀的程序员写的代码是给人读的。
“In matters of style, swim with the current; in matters of principle, stand like a rock.” Thomas Jefferson
风格上跟住潮流,原则上坚若磐石。
“You got to know the rules before you can break ‘em. Otherwise it’s no fun.” Sonny Crockett in Miami Vice
在打破规则之前先熟知规则,不然不好玩。
Patrick Raume, “A rose by any other name confuses the issue.”
不叫玫瑰的玫瑰会坏了事。
Plato, “Nothing has its name by nature, but only by usage and custom.”
没有什么的名字是自然而然的,唯独用法和习惯例外。
Unknown, “All general statements are false.”
真理掌握在少数人手里。
Try to avoid the situation described by the Captain in Cool Hand Luke, “What we’ve got here is failure to communicate.”
交流的终止是十足的失败。
Kreitzberg and Shneiderman: “Programming can be fun, so can cryptography; however they should not be combined.”
编程是妙趣横生的,密码学也是,但是二者联系在一起就不这样了。
Jay Rodenberry, “Space…the final frontier.”
空格,是最后的底线。
Napoleon Hill, “First comes thought; then organization of that thought into ideas and plans; then transformation of those plans into reality.”
想法为先,计划次之,实现为末。
“Change is inevitable…except from vending machines.”
改变是不可避免的,除了自动贩卖机。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值