crap code indicators

本文讨论了多位开发者眼中构成糟糕代码的主要特征,包括错误处理缺失、语言特性使用不当、文档不足、函数过长等问题。
Roger:

These are some of my "crap" indicators:
- No error detection/handling.
- Incorrect or non use of language features/standard libraries.
- Non understanding/incorrect use of programming paradigms (e.g. "is a", "uses a" ...).
- Useless, lack of, or bad documentation.
- Massive functions or methods
- Obfuscated code.

I hate it when:
Someone recreates functions because they were too distracted/overworked/lazy/dumb to see if a working function already existed.
Someone codes 5 lines to do something that could have been done with 1.
There are no naming conventions.
Someone uses one name for an object in one section of code but a different name in another but the two sections relate or interact. Duh!
There is no way to know who wrote the code or who made changes to it.
There is no formatting or inconsistent formatting.

Reiterate:
"more than 2 instructions in a line" is crap.
"no documentation or poor docs/comments" is crap.

> What code characteristics would make you say: “Pardon my French, but this code is crap!”

This is actually one of my favorite interview questions. I think lots of you guys already nailed the big ones: Functions with side effects. Big classes. Low cohesion. High coupling. Cut-paste-tweak duplication. Meaningless comments. Premature optimization. Premature generalization. Nonexistent error handling. Error handling everywhere. Empty catch blocks. Lots of "if" statements (special cases). Shared state concurrency.

I'll buck the trend and say the following aren't code smells, however:

* m_ notation. There are many abuses of Hungarian, but this isn't one of them.
* Multiple instructions on a line.
* Superficial layout inconsistencies. I don't think code has to cater to OCD sufferers to be considered "readable".
* Few comments. Well-written code doesn't need a lot of comments. (No comments at all is definitely a problem, but it's also one I've never run into. I have seen lots of problematic heavily commented code, though).
* Long functions. I look more at the number of locals and the level of indentation. Sometimes you really do need to do A, then B, then C, all the way to Z -- and in many cases, arbitrarily chopping it up into funclets is actually the wrong thing to do.

### CRAP原则的定义 CRAP 是 Complexity and Replication Are Punished 的缩写,意指复杂性和重复性应受到惩罚。该原则强调在软件开发过程中减少不必要的复杂度和代码冗余的重要性。具体而言,CRAP 原则提倡通过简化设计、重构代码以及采用更清晰的设计模式来降低系统的维护成本和技术债务。 CRAP 分数是一种衡量代码质量的量化指标,它综合考虑了代码中的复杂度(Complexity)和测试覆盖率(Test Coverage)。较高的复杂度通常意味着更高的出错概率,而较低的测试覆盖率则表明缺乏足够的验证机制[^1]。计算公式如下: \[ CRAP = \text{complexity} * (1 - (\text{test coverage}/100))^2 \] 其中: - **complexity** 表示函数或模块的圈复杂度; - **test coverage** 表示单元测试覆盖的比例; 如果某个模块的 CRAP 得分过高,则说明该部分代码可能存在过多复杂的逻辑且未经过充分测试,从而增加了潜在风险。 --- ### CRAP原则的应用场景 #### 1. **代码审查** 在团队协作环境中,可以通过静态分析工具定期扫描项目源码并生成报告,帮助识别那些违反 CRAP 原则的部分。例如,当发现某些方法具有很高的圈复杂度却几乎没有对应的单元测试时,就应该优先对其进行重构以改善可读性和可靠性[^2]。 ```bash # 使用 SonarQube 或其他类似的工具执行静态代码分析 sonar-scanner \ -Dsonar.projectKey=my_project_key \ -Dsonar.sources=src/main/java \ -Dsonar.tests=src/test/java ``` #### 2. **持续集成/部署流程** 将 CRAP 指标的检测纳入 CI/CD 流程中,设置合理的阈值限制。一旦某次提交导致整体评分超出预定标准,则阻止此次构建成功直至问题得到解决为止。这种方法有助于保持长期稳定的高质量代码库状态。 #### 3. **遗留系统改造** 针对历史久远且文档稀少的老化应用程序来说,遵循 CRAP 准则是非常重要的一步操作策略之一。因为这类系统往往存在大量未经良好组织处理过的业务规则集合体,容易形成难以理解又脆弱易损的状态。通过对高危区域逐步实施现代化升级措施——比如引入新的框架组件或者调整现有架构布局等方式——可以有效缓解此类困境带来的挑战压力。 #### 4. **教学培训材料制作** 为了让初学者更好地掌握如何编写高效优雅而又易于管理维护的程序作品集锦范例展示环节里加入有关此主题的内容讲解也是很有必要的举措之一哦! --- ### 示例代码片段 下面是一个简单的 Python 实现例子用于演示如何手动估算给定函数可能产生的 CrapScore 数值大小情况: ```python def calculate_crap_score(complexity, test_coverage): """Calculate the CRAP score based on complexity and test coverage.""" if not (0 <= test_coverage <= 100): raise ValueError("Test coverage must be between 0 and 100.") crap_score = complexity * ((1 - (test_coverage / 100)) ** 2) return round(crap_score, 2) # Example usage of calculating CRAP Score example_complexity = 8 example_test_coverage = 75 score = calculate_crap_score(example_complexity, example_test_coverage) print(f"The calculated CRAP score is {score}.") ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值