标签:
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 corporate@oreilly.com.
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.
Building Maintainable Software-java篇之Write Short Units of Code
标签:
原文地址:http://blog.csdn.net/doctor_who2004/article/details/50654392