通过在阅读代码的sight来关注code的优化问题,有意思的视角
Line of sight is “a straight line along which an observer has unobstructed vision”
good code, The idea is that another programmer (including your future self) can glance down a single column and understand the expected flow of the code.
Most people focus on the cost of writing code (ever heard “how long will this take to finish?”) But the far greater cost is in maintaining code — especially in successful projects. Making functions obvious, clear, simple and easy to understand is vital to this cause.
Tips for a good line of sight:
- Align the happy path to the left; you should quickly be able to scan down one column to see the expected execution flow
- Don’t hide happy path logic inside a nest of indented braces 成功路径显而易见
- Exit early from your function 尽早退出你的功能
- Avoid else returns; consider flipping the if statement 避免无谓的else
- Put the happy return statement as the very last line
- Extract functions and methods to keep bodies small and readable extract的必要性
- If you need big indented bodies, consider giving them their own function 分拆own function