`

Clean Code: chapter 9~10

Go 
阅读更多

Yes, we’ve come a long way; but we have farther to go.

 

Then there’s the
ham-handed way that the request URL is built from a resource and an argument. (I helped
write this code, so I feel free to roundly criticize it.)

 

In the end , this code was not designed to be read. The poor reader is inundated with a
swarm of details
that must be understood before the tests make any real sense.
Now consider the improved tests in Listing 9-2. These tests do the exact same thing ,
but they have been refactored into a much cleaner and more explanatory form .

 

The BUILD-OPERATE-CHECK pattern is made obvious by the structure of these tests.
Each of the tests is clearly split into three parts. The first part builds up the test data, the
second part operates on
that test data, and the third part checks that the operation yielded
the expected results.
Notice that the vast majority of annoying detail has been eliminated. The tests get
right to the point
and use only the data types and functions that they truly need . Anyone
who reads these tests should be able to work out what they do very quickly, without being
misled or overwhelmed by details.

 

Domain-Specific Testing Language
The tests in Listing 9-2 demonstrate the technique of building a domain-specific language
for your tests
. Rather than using the APIs that programmers use to manipulate the system,
we build up a set of functions and utilities that make use of those APIs and that
make the tests more convenient to write and easier to read. These functions and utilities
become a specialized API used by the tests. They are a testing language that programmers
use to help themselves to write their tests and to help those who must read those
tests later on.
This testing API is not designed up front ; rather it evolves from the continued refactoring
of test code that has gotten too tainted by obfuscating detail. Just as you saw me
refactor Listing 9-1 into Listing 9-2, so too will disciplined developers refactor their test
code into more succinct and expressive forms.

 

@Test
public void turnOnHiTempAlarmAtThreshold() throws Exception {
    wayTooHot();
    assertEquals("hBCHl", hw.getState());
}

@Test
public void turnOnLoTempAlarmAtThreshold() throws Exception {
    wayTooCold();
    assertEquals("HBchL", hw.getState());
}
 

look at the phrase "At Threshold ", a threshold means the changing point.

 

That is the nature of the dual standard . There are things that you might never do in a
production environment that are perfectly fine in a test environment.

 

Notice that I have changed the names of the functions to use the common given-when-then
convention
. This makes the tests even easier to read.

 

You won’t feel as free to clean up the code.

 

When tests depend on each other, then the first one to fail causes a cascade
of downstream failures
, making diagnosis difficult and hiding downstream defects.

 

The tests need to be written in a timely fashion.

 

F.I.R.S.T.

Fast, Independent, Repeatable, Self-Validating, Timely

 

We have barely scratched the surface of this topic. Indeed, I think an entire book could be
written about clean tests. Tests are as important to the health of a project as the production
code is.
Perhaps they are even more important, because tests preserve and enhance the
flexibility , maintainability , and reusability of the production code. So keep your tests constantly
clean
. Work to make them expressive and succinct . Invent testing APIs that act as
domain-specific language
that helps you write the tests.
If you let the tests rot, then your code will rot too. Keep your tests clean.

 

So far in this book we have focused on how to write lines and blocks of code well. We have
delved into
proper composition of functions and how they interrelate . But for all the attention
to the expressiveness of code statements and the functions they comprise , we still
don’t have clean code until we’ve paid attention to higher levels of code organization . Let’s
talk about clean classes.

 

The name of a class should describe what responsibilities it fulfills .

 

No doubt we’ll want to update the version number if we change any of the Swing code, but the converse isn’t necessarily true : We might change the version information based on changes to other code in
the system.

 

Trying to identify responsibilities (reasons to change) often helps us recognize and
create better abstractions in our code . We can easily extract all three SuperDashboard
methods that deal with version information into a separate class named Version. (See
Listing 10-3.) The Version class is a construct that has a high potential for reuse in other
applications!

 

SRP is one of the more important concept in OO design. It’s also one of the simpler
concepts to understand and adhere to . Yet oddly , SRP is often the most abused class design
principle. We regularly encounter classes that do far too many things. Why?

 

Getting software to work and making software clean are two very different activities.
Most of us have limited room in our heads, so we focus on getting our code to work more
than organization and cleanliness. This is wholly appropriate . Maintaining a separation of
concerns is just as important in our programming activities as it is in our programs.

 

The problem is that too many of us think that we are done once the program works.
We fail to switch to the other concern of organization and cleanliness . We move on to the
next problem rather than going back and breaking the overstuffed classes into decoupled
units with single responsibilities
.

 

However, a system with many small classes has no more moving parts than a system
with a few large classes. There is just as much to learn in the system with a few large
classes. So the question is: Do you want your tools organized into toolboxes with many
small drawers each containing well-defined and well-labeled components? Or do you want
a few drawers that you just toss everything into ?

 

Every sizable system will contain a large amount of logic and complexity. The primary
goal in managing such complexity is to organize it so that a developer knows where
to look to find things and need only understand the directly affected complexity at any
given time
. In contrast , a system with larger, multipurpose classes always hampers us by
insisting we wade through lots of things we don’t need to know right now .

 

To restate the former points for emphasis : We want our systems to be composed of
many small classes
, not a few large ones. Each small class encapsulates a single responsibility,
has a single reason to change, and collaborates with a few others to achieve the
desired system behaviors.

 

This program, written as a single function, is a mess. It has a deeply indented structure ,
a plethora of odd variables , and a tightly coupled structure . At the very least, the one
big function should be split up into a few smaller functions.

 

The first thing you might notice is that the program got a lot longer. It went from a
little over one page to nearly three pages in length
. There are several reasons for this
growth. First, the refactored program uses longer, more descriptive variable names.
Second, the refactored program uses function and class declarations as a way to add
commentary to the code
. Third, we used whitespace and formatting techniques to keep
the program readable.

 

For most systems, change is continual . Every change subjects us to the risk that the
remainder of the system no longer works as intended . In a clean system we organize our
classes so as to reduce the risk of change.

 

here works as intended, how to resolve it? maybe works the way as is intended , it acts as a relational pronoun, or works as it is intended , like works as what? as it is intended. here the whole sentence acts as an adverb.

 

that appear to relate only to select statements.

 

Needs will change, therefore code will change. We learned in OO 101 that there are concrete
classes, which contain implementation details (code), and abstract classes, which
represent concepts only. A client class depending upon concrete details is at risk when
those details change. We can introduce interfaces and abstract classes to help isolate the
impact of those details
.

 

 

 

 

 

 

分享到:
评论

相关推荐

    Clean.Code.Summary.B01AAS8T4A.pdf

    Chapter 1 Clean Code Chapter 2 Meaningful Names Chapter 3 Functions Chapter 4 Comments Chapter 5 Formatting Chapter 6 Objects and Data Structures Chapter 7 Error Handling Chapter 8 Boundaries Chapter ...

    24.Patterns.for.Clean.Code

    In this book, you'll learn about Niklaus Wurth's 3-10 rule, speed-documenting tools, and the techniques that keep memory leaks out of your code. Table of Contents Chapter 1. Introduction Chapter 2. ...

    Clean Code

    But if code isn’t clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code. But it doesn’t have to ...

    Learn.CakePHP.With.Unit.Testing.1484212134

    Accelerate your development of ...Chapter 9: Controller Tests 1 Chapter 10: Mocks Chapter 11: Controller Tests 2 Chapter 12: Test Suites Chapter 13: Testing from Command Line Chapter 14: Goodies

    cleancode4noobs:清洁代码摘要(PT-BR)

    CleanCode4Noobs 罗伯特·塞西尔·马丁(Robert Cecil Martin)编写的《清洁代码:敏捷软件技巧手册》的摘要。 内容 参考 Robert C. Martin,“清洁代码:敏捷软件Craft.io手册” 如何贡献 贡献使开源社区成为了一...

    Apache.Maven.Cookbook.1785286129

    Over 90 hands-on recipes to successfully build and automate development life cycle tasks ...Chapter 9: Multimodule Projects Chapter 10: Java Development with Maven Chapter 11: Advanced Maven Usage

    Clean Architectures in Python A practical approach to better software design

    The first chapter discusses briefly the components and the ideas behind this software structure, while chapter 2 runs through a concrete example of clean architecture for a very simple web service....

    Learn.Mobile.Game.Development.in.One.Day.Using.Gamesalad

    Chapter 9: Behaviors Part 2 Chapter 10: Player Input Chapter 11: Game 2 – Space Shooter Chapter 12: Audio Chapter 13: The Expression Editor Chapter 14: Collisions and Physics Chapter 15: Camera ...

    C# Primer 中文版随书源码

    You may have to open your own, then copy in the form and code behind files. I’ll try to clean that up when I have time. The project listing under each chapter for this release looks as follows: ...

    R.Unleash.Machine.Learning.Techniques

    Chapter 9: Finding Groups of Data – Clustering with k-means Chapter 10: Evaluating Model Performance Chapter 11: Improving Model Performance Chapter 12: Specialized Machine Learning Topics Module 3:...

    Less.Web.Development.Essentials.2nd.Edition

    Chapter 4: Testing Your Code And Using Prebuilt Mixins Libraries Chapter 5: Integrating Less In Your Own Projects Chapter 6: Using The Bootstrap 3 Frontend Framework Chapter 7: Less With External ...

    Test-.Driven.Python.Development.1783987928

    Title: Test- Driven Python Development Author: Siddharta Govindaraj Length: 300 pages Edition: 1 ...Chapter 9. Unit Testing Patterns Chapter 10. Tools to Improve Test-Driven Development

    SCJP Sun® Certified Programmer for Java™ 6 Study Guide chapter 5

    ### SCJP Sun® Certified Programmer for Java™ 6 Study Guide Chapter 5: Flow Control, Exceptions, and Assertions #### Certification Objectives Overview In this chapter, we delve into the critical ...

    ASP.NET.Web.API.and.Angular.2.17864

    Key Features Learn how to design Single Page Applications (SPAs) with the latest versions of the popular frameworks...Chapter 9: User Registration and Account Edit Chapter 10: Finalization and Deployment

    Beginning PHP 5.3

    **Chapter 9: Handling HTML Forms with PHP** - **HTML Forms:** Explanation of HTML forms and how they work. - **Form Data Submission:** Description of form submission methods (GET and POST) and how to ...

Global site tag (gtag.js) - Google Analytics