#onenote# practice

Code Review

here are the 11 practices in a simple list that’s easy to keep on file:

 

      1. Review fewer than 200–400 lines of code at a time.
      2. Aim for an inspection rate of fewer than 300–500 LOC per hour.
      3. Take enough time for a proper, slow review, but not more than 60–90 minutes.
      4. Be sure that authors annotate source code before the review begins.
      5. Establish quantifiable goals for code review and capture metrics so you can improve your processes.
      6. Use checklists, because they substantially improve results for both authors and reviewers.
      7. Verify that the defects are actually fixed.
      8. Foster a good code review culture in which finding defects is viewed positively.
      9. Beware of the Big Brother effect.
      10. Review at least part of the code, even if you can’t do all of it, to benefit from The Ego Effect.
      11. Adopt lightweight, tool-assisted code reviews.

 

Pasted from <http://www.ibm.com/developerworks/rational/library/11-proven-practices-for-peer-review/>

 

How to adopt

http://blogs.atlassian.com/2010/03/code_review_in_agile_teams_part_ii/

 

 

Process-wise

      • Unit Test, comment , Java Standard

Tool

      • PMD/Findbugs/CheckList ->  Use Sonar to measure code quality ->  use Fisheye/crucible to collaborative code review (Clean Code)

Clean Code

 

Some tools which help in bringing greater objectivity and focus to the review process, like

    • JDepend for design quality
    • PMD for code cleanliness
    • JavaNCSS for code quality and
    • Emma for test coverage  ( or coveralls.io)

 

PMD

PMD scans Java source code and looks for potential problems like:

PMD is a source code analyzer. It finds common programming flaws like unused variables, empty catch blocks, unnecessary object creation, and so forth. 

      • Possible bugs – empty try/catch/finally/switch statements
      • Dead code – unused local variables, parameters and private methods
      • Suboptimal code – wasteful String/StringBuffer usage
      • Overcomplicated expressions – unnecessary if statements, for loops that could be while loops
      • Duplicate code – copied/pasted code means copied/pasted bugs

Machine generated alternative text:
Su ni ni a rv
Rule name
UnusedLocalVariable
Duplicatelmports
UncommentedEmptvConstructor
Unusedimports
UnusedPrivateField
Detail
Number of violations
1
1
1
,
PMD report
Problems found
File
1 corndevcrumb App java
2 corn devcrurnb App.java
3 corndevcnwb App.java
4 comdevcnirnb Appjava
5 corn devcnirnbApp.java
6 corn devcnmib model Person java
Line Problem
7 Avoid duohcate imnorts such as 慾ava io FileNotFoundExcettion?
8 Avoid unused imports such as 慾avaioIOException
S Avoid unused uDorts such as ?iavaioiOExcer&n?
24 Avoid unused orivate fields such as 慶ount.
28 Avoid unused local variables such as reade?
22 Douinenr jjptj cnsmctcr

Refactoring Java Code

Refactoring is a powerful Agile technique for improving existing software. Having Java source code that is understandable helps ensure a system is maintainable and extensible

Pasted from <http://www.methodsandtools.com/archive/archive.php?id=4>

Who needs refactoring?

Software starts on a small scale, and most of it well-designed. Over time, software size and complexity increases, with that bugs creep in, and thus code reliability decreases. Software developers, particularly when they are not the original authors, are finding it increasingly difficult to maintain the code, and even harder to extend. The code base, which in any software company should be a valuable asset, at some point may become a liability.

What is needed to prevent the software from ageing prematurely? Strategically, attention of management and software developers is the most important factor. On the practical side, application of sound development methods will slow this ageing down. However refactoring can reverse this ageing when applied properly, preferably with good software tools that aid in the detection, analysis, and characterisation of the problems, and ultimately allow fixing them.

What exactly is refactoring?

Refactoring simply means “improving the design of existing code without changing its observable behaviour”.

When should one consider refactoring?

Ideally, refactoring would be part of a continuing quality improvement process. In other words, refactoring would be seamlessly interwoven with other day-to-day activities of every software developer.

Often, however, schedule pressures do not permit to implement a clean solution right away. A feature may have to be added in a hurry, a bug patched rather than fixed. In these cases, the code in question should be marked with a FIXME /TODO note

Refactoring adds to the value of any program that has at least one of the following shortcomings:

  • Programs that are hard to read are hard to modify.
  • Programs that have duplicate logic are hard to modify
  • Programs that require additional behaviour that requires you to change running code are hard to modify.
  • Programs with complex conditional logic are hard to modify.

A refactoring operation proceeds roughly in the following phases:

Action

Questions to ask, actions to take

Detect a problem

Is there a problem? What is the problem?

Characterise the problem

Why is it necessary to change something? What are the benefits? Are there any risks?

Design a solution

What should be the “goal state” of the code? Which code transformation(s) will move the code towards the desired state?

Modify the code

Steps that will carry out the code transformation(s) that leave the code functioning the same way as it did before.

Example Refactorings:

  • Rename
  • Move Class
  • Extract Method
  • Extract Superclass
  • Replace Conditional with Polymorphism

Clean Code

Clean Code

  • Elegance
  • Simple, direct, prose散文
  • Literate 精通文学的
  • Care ( clean code always looks like it was written by someone who cared)
  • Small, Expressive, simple

Goals

  • Readable, maintainable and extendable code

 

Principle

  1. Meaningful names
  • A class name should be a verb
  • Method should have verb or verb phrase names
  • Avoid using the same word for two purposes

 

  1. Functions
  • Functions should do one thing only
  • Function should be small
  • Function arguments (The ideal number of argument for a func is zero)
  • Don’t repeat yourself
  1. Comments
  • Don’t comment bad code, rewrite it

 

  1. Formating
  • Each blank line is a visual cure that identifies a new and separate concept
  • Vertical density implies close association
  • Variables should be declared as close to their usage as possible
  • Instance variables should be declared at the top of the class
  • Dependent functions
    • If one function calls another, they should be vertically  close, and the caller should be above the called
  • Every programmer has his own favorite formating rules, but if he works in a team, then the team rules
  1. Objects and Data Structures
  • Objects hide their data behind abstractions and expose functions that operate on that data
  • Data structure expose their data and have no meaningful functions
  1. Error handling
  • Prefer exceptions to returning error code
  • Don’t return null
  1. Unit Tests
  • Test code is just as important as production code
  • Readability makes a clean code
  • One assert per test
  • FIRST (Fast, Independent, Repeatable, Self-validating, Timely)

如何使代码审查更高效

      • 代码审查者在审查代码时有非常多的东西需要关注。一个团队需要明确对于自己的项目哪些点是重要的,并不断在审查中就这些点进行检查。
      • 人工审查代码是十分昂贵的,因此尽可能地使用自动化方式进行审查,如:代码格式、代码样式、检查常见bug、确定常见安全问题以及运行自动化测试。

设计

      • 如何让新代码与全局的架构保持一致?
      • 代码是否遵循SOLID原则,是否遵循团队使用的设计规范,如领域驱动开发等?
      • 新代码使用了什么设计模式?这样使用是否合适?
      • 基础代码是否有结合使用了一些标准或设计样式,新的代码是否遵循当前的规范?代码是否正确迁移,或参照了因不规范而淘汰的旧代码?
      • 代码的位置是否正确?比如涉及订单的新代码是否在订单服务相关的位置?
      • 新代码是否重用了现存的代码?新代码是否可以被现有代码重用?新代码是否有重复代码?如果是的话,是否应该重构成一个更可被重用的模式,还是当前还可以接受?
      • 新代码是否被过度设计了?是否引入现在还不需要的重用设计?团队如何平衡可重用和YAGNI(You Ain’t Gonna Need It)这两种观点?

可读性和可维护性

      • 字段、变量、参数、方法、类的命名是否真实反映它们所代表的事物。
      • 我是否可以通过读代码理解它做了什么?
      • 我是否理解测试用例测了什么?
      • 测试是否很好地覆盖了用例的各种情况?它们是否覆盖了正常和异常用例?是否有忽略的情况?
      • 错误信息是否可被理解?
      • 不清晰的代码是否被文档、注释或容易理解的测试用例所覆盖?具体可以根据团队自身的喜好决定使用哪种方式。

功能

      • 代码是否真的达到了预期的目标?如果有自动化测试来确保代码的正确性,测试的代码是否真的可以验证代码达到了协定的需求?
      • 代码看上去是否包含不明显的bug,比如使用错误的变量进行检查,或误把and写成or

你是否考虑过……?

      • 是否需要满足相关监管需求?
      • 作者是否需要创建公共文档或修改现存的帮助文档?
      • 是否检查了面向用户的信息的正确性?
      • 是否有会在生产环境中导致应用停止运行的明显错误?代码是否会错误地指向测试数据库,是否存在应在真实服务中移除的硬编码的stub代码?
      • 你对性能的需求是什么,你是否考虑了安全问题?这些是需要覆盖到的重大区域也是至关重要的话题,下面让我们仔细看下这两点。

正确性

这些不一定影响系统的性能,但是它们与多线程环境运行关系密切,所以和这个主题有关:

      • 代码是否使用了正确的适合多线程的数据结构。
      • 代码是否存在竞态条件(race conditions)?多线程环境中代码非常容易造成不明显的竞态条件。作为审查者,可以查看不是原子操作的getset
      • 代码是否正确使用锁?和竞态条件相关,作为审查者你应该检查被审代码是否允许多个线程修改变量导致程序崩溃。代码可能需要同步、锁、原子变量来对代码块进行控制。
      • 代码的性能测试是否有价值?很容易将小型的性能测试代码写得很糟糕,或者使用不能代表生产环境数据的测试数据,这样只会得到错误的结果。
      • 缓存:虽然缓存是一种能防止过多高消耗请求的方式,但其本身也存在一些挑战。如果审查的代码使用了缓存,你应该关注一些常见的问题,如,不正确的缓存失效方式

审查者可以轻松找出的警告信号

一些代码一眼就能看出存在潜在性能问题。这依赖于所使用的语言和类库。

      • 反射:Java的反射比正常调用要慢。如果你在审查含有反射的代码,你就要问下是否必须使用它。
      • 超时:当你审查代码时,你可能不知道一个操作合适的超时时间,但是你要想一下“如果超时了,会对系统其他部分造成什么影响?”。作为审查者你应该考虑最坏的情况:当发生5分钟的延时,应用是否会阻塞?如果超时时间设置成1秒钟最坏的情况会是怎么样的?如果代码作者不能确定超时长度,你作为审查者也不知道一个选定的时间的好坏,那么是时候找一个理解这其中影响的人参与代码审查了。
      • 并行:代码是否使用多线程来运行一个简单的操作?这样是否花费了更多的时间以及复杂度而并没有提升性能?如果使用现代化的Java,那其中潜在的问题相较于显示创建线程中的问题更不容易被发现:代码是否使用Java 8新的并行流计算但并没有从并行中获益?比如,在少量元素上使用并行流计算,或者只是运行非常简单的操作,这可能比在顺序流上运算还要慢。

代码级优化

对大部分并不是要构建低延时应用的机构来说,代码级优化往往是过早优化,所以首先要知道代码级优化是否必要。

      • 代码是否在不需要的地方使用同步或锁操作?如果代码始终运行在单线程中,锁往往是不必要的。
      • 代码是否可以使用原子变量替代锁或同步操作?
      • 代码是否使用了不必要的线程安全的数据结构?比如是否可以使用ArrayList替代Vector
      • 代码是否在通用的操作中使用了低性能的数据结构?如在经常需要查找某个特定元素的地方使用链表。
      • 代码是否可以使用懒加载并从中获得性能提升?
      • 条件判断语句或其他逻辑是否可以将最高效的求值语句放在前面来使其他语句短路?
      • 代码是否存在许多字符串格式化?是否有方法可以使之更高效?
      • 日志语句是否使用了字符串格式化?是否先使用条件判断语句校验了日志等级,或使用延迟求值?

From <http://www.infoq.com/cn/articles/effective-code-reviews>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s