Building Maintainable Software-java篇之Write Short Units of Code

Building Maintainable Software-java篇之Write Short Units of Code

Any fool can write code that a computer can understand. Good programmers write

code that humans can understand.

—Martin Fowler

Guideline:

? Limit the length of code units to 15 lines of code.

? Do this by not writing units that are longer than 15 lines of

code in the first place, or by splitting long units into multiple

smaller units until each unit has at most 15 lines of code.

? This improves maintainability because small units are easy to

understand, easy to test, and easy to reuse.

Units are the smallest groups of code that can be maintained and executed independ‐

ently. In Java, units are methods or constructors. A unit is always executed as a whole.

It is not possible to invoke just a few lines of a unit. Therefore, the smallest piece of

code that can be reused and tested is a unit.

Motivation

The advantages of short units are that they are easy to test, easy to analyze, and easy

to reuse.

Short Units Are Easy to Test

Units encapsulate the application logic of your system, and typically much testing

effort is spent on validating the application logic’s correctness. This is because the Java

compiler will not detect errors in the application logic automatically, and neither will

your editor or IDE (integrated development environment; e.g., Eclipse). Code with a

single responsibility is easier to test. In general, short units may do only one thing,

while long units do multiple things and tend to have more responsibilities. A unit

with one responsibility is easier to test, since it implements a single indivisible task.

That allows the test to be isolated (specific to the unit) and simple. Chapter 10 dis‐

cusses testing in more detail.

Short Units Are Easy to Analyze

It takes less time to read all the code in a short unit in order to analyze how the unit

works internally than it does in a long unit. This may not be apparent when you are

writing new code, but it makes all the difference when you are modifying existing

code. This is not an exceptional situation, since maintenance begins the day after the

project is started.

Short Units Are Easy to Reuse

A unit should always be invoked in at least one method (otherwise, the unit is dead

code). In a system, you can reuse a unit by invoking it in more than one method.

Small units are better candidates for reuse than long units. Long units tend to offer

specific details or provide a specific combination of functionalities. As a result, they

have more specialized functionality than short units. This makes reuse hard, because

it is not very likely that the specific functionality of a long unit is suitable. In contrast,

short units tend to be more generic. This makes reuse easier, because it is more likely

to fit your needs. Reusing code also helps keep the total code volume low。

How to Apply the Guideline

Following this guideline is not difficult when you know the right techniques, but it

requires discipline. This section presents two techniques that we find particularly

important. When writing a new unit, never let it grow beyond 15 lines of code. That

means that well before you reach 15 lines of code, you need to start thinking about

how to add further functionality. Does it really belong in the unit you are writing, or

should it go into its own unit? When a unit grows beyond 15 lines of code despite

your efforts, you need to shorten it.

Using Refactoring Techniques to Apply the Guideline

This section discusses two refactoring techniques to apply the guideline and achieve

shorter units of code.

Refactoring technique: Extract Method

One refactoring technique that works in this case is Extract Method

Refactoring technique: Replace Method with Method Object

Common Objections to Writing Short Units

While writing short units may sound simple, software developers often find it quite

difficult in practice. The following are typical objections to the principle explained in

this chapter.

Objection: Having More Units Is Bad for Performance

“Writing short units means having more units, and therefore more method calls. That

will never perform.”

Indeed, theoretically, there is a performance penalty for having more units. There will

be more method invocations (compared to having fewer, longer units). For each invo‐

cation, a bit of work needs to be done by the Java Virtual Machine (JVM). In practice,

this is almost never a problem. In the worst case, we are talking about microseconds.

Unless a unit is executed hundreds of thousands of times in a loop, the performance

penalty of a method invocation is not noticeable. Also, the JVM is very good at opti‐

mizing the overhead of method invocations.

Except for very specific cases in enterprise software development, you can focus on

maintainability without sacrificing performance. An example is when a method is

invoked hundreds of thousands of times in the case of certain algorithms. This is

probably one of the very few cases in a programmer’s life where you can have your

cake and eat it too. We are not saying that there are no performance issues in enter‐

prise software development; however, they seldom, if ever, are caused by excessive

method calling.

Do not sacrifice maintainability to optimize for performance,

unless solid performance tests have proven that you actually have a

performance problem and your performance optimization actually

makes a difference.

Objection: Code Is Harder to Read When Spread Out

“Code becomes harder to read when spread out over multiple units.”

Well, psychology says that is not the case. People have a working memory of about

seven items, so someone who is reading a unit that is significantly longer than seven

lines of code cannot process all of it. The exception is probably the original author of

a piece of source code while he or she is working on it (but not a week later).

Write code that is easy to read and understand for your successors

(and for your future self).

读书笔记:

Building Maintainable Software: Ten Guidelines for Future-Proof Code

by Joost Visser

Copyright ? 2016 Software Improvement Group, B.V. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are

also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/

institutional sales department: 800-998-9938 or [email protected]

Acquisitions Editor: Rachel Roumeliotis

Editor: Nan Barber

Production Editor: Matthew Hacker

Copyeditor: Rachel Monaghan

Proofreader: Marta Justak

Indexer: WordCo Indexing Services, Inc.

Interior Designer: David Futato

Cover Designer: Randy Comer

Illustrator: Rebecca Demarest

February 2016: First Edition

Revision History for the First Edition

2016-01-25: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781491940662 for release details.

时间: 2024-12-17 22:42:41

Building Maintainable Software-java篇之Write Short Units of Code的相关文章

Building Maintainable Software-java篇之Separate Concerns in Modules

Building Maintainable Software-java篇之Separate Concerns in Modules   In a system that is both complex and tightly coupled, accidents are inevitable. -Charles Perrow's Normal Accidents theory in one sentence Guideline: ? Avoid large modules in order to

Building Maintainable Software-java篇之 Write Clean Code

Building Maintainable Software-java篇之 Write Clean Code Writing clean code is what you must do in order to call yourself a professional. -Robert C. Martin Guideline: ? Write clean code. ? Do this by not leaving code smells behind after development wor

Building Maintainable Software-java篇之Keep Architecture Components Balanced

Building encapsulation boundaries is a crucial skill in software architecture. -George H. Fairbanks in Just Enough Architecture Guideline: ? Balance the number and relative size of top-level components in your code. ? Do this by organizing source cod

[转]有哪些值得关注的技术博客(Java篇)

有哪些值得关注的技术博客(Java篇) 大部分程序员在自学的道路上不知道走了多少坑,这个视频那个网站搞得自己晕头转向.对我个人来说我平常在学习的过程中喜欢看一些教程式的博客.这些博客的特点: 1.总结知识点相对比较全面 2.一般来说讲解知识点通俗易懂 3.路线比较清晰,不会有太多的冗余内容. 这样一来,对于自学的朋友来说,一些专业的博客不但大量的缩减了你得学习时间.提高了学习效率.更重要的是这些博客能培养你对编程的兴趣. 于是,这几期文章会主要推荐一些技术博客,目前计划打算主要分为: (已完) 

关于多线程的几个问题(面试小问题,Java篇)

面试官想考考我多线程方面的问题. 1.请说下线程与进程的关系. 答:<操作系统>中是这样说的 (1)一个线程只能属于一个进程,而一个进程可以有多个线程,但至少有一个线程.线程是操作系统可识别的最小执行和调度单位. (2)资源分配给进程,同一进程的所有线程共享该进程的所有资源.同一进程中的多个线程共享代码段(代码和常量),数据段(全局变量和静态变量),扩展段(堆存储).但是每个线程拥有自己的栈段,栈段又叫运行时段,用来存放所有局部变量和临时变量. (3)处理机分给线程,即真正在处理机上运行的是线

关于一些设计模式(面试小问题,Java篇)

今天在某公司(不透露了)写了一套Java面试题.有个题大概是这样的. Which design pattern used in Java.lang.Runtime? 就是说java.lang.Runtime里,用了什么设计模式 还有java.utils.collection里用了什么设计模式. 当时由于对这冷门知识了解的不够多,而且api也读的少,所以一时答不上来. 回到家搜了下. 答: Runtiome里 单例模式. 1)  每一个Java程序都有一个Runtime类的单一实例. 2)  通过

Tools:Installing and using the Required Tools for downloading and Building EDK II工具篇:安装/使用EDKII源码获取/

Tools:Installing and using the Required Tools for downloading and Building EDK II工具篇:安装/使用EDKII源码获取/编译工具[2.3] 2015-07   北京海淀区  张俊浩 2. Setting Up EDKII Development Environment(EDKII开发环境的搭建) ->2.1 The General Procedure Of Setting Up EDKII Development E

优秀的编程风格(Java篇)——高薪必看

今天突发奇想,对编码习惯和编程风格很感兴趣,于是乎,找了一下关于编程风格(Java篇)的资料,希望对爱好编码或者开始学习编码的同学有帮助! 来自<The Elements of Java Style>-<Java编程风格>一书,值得一读的书籍,会让你在细节上节省很多时间,合作之间更加愉快! 好处不多说了,但是有几个原则如下: 1.保持原有风格 2.坚持最小惊奇原则 3.第一次就做对 4.记录所有非规范行为 格式规范: 1.缩进嵌套的代码:在每个代码块和嵌套中加入缩进,缩进代码,加强

事件驱动模型实例详解(Java篇)

或许每个软件从业者都有从学习控制台应用程序到学习可视化编程的转变过程,控制台应用程序的优点在于可以方便的练习某个语言的语法和开发习惯(如.net和java),而可视化编程的学习又可以非常方便开发出各类人机对话界面(HMI).可视化编程或许是一个初学者开始对软件感兴趣的开始,也可能是一个软件学习的里程碑点,因为我们可以使用各类软件集成开发环境(IDE)方便的在现成的界面窗口上拖放各类组件(Component),这类组件包括我们常见的按钮(Button),单选按钮(Radio Button),复选框