当前位置:网站首页>The art of writing simple code

The art of writing simple code

2022-06-25 03:54:00 Blockchain research

Correct your attitude

You do everything You can make it beautiful , Or ugly —— Robert · m· Posig 《 Zen and motorcycle maintenance Art 》

This sentence is put in the field of programming , It can be understood in this way : You can make any code ugly , You can also write beautifully , And it's beautifully written , It is an art .

Before, I didn't think that writing code was such a high-end job , Some people call writing code a code farmer , If you don't correct your attitude , Everything has become perfunctory . You have to make high-quality software , The premise is to correct your attitude .

One might think , Things about code are a bit behind the times —— Code is no longer a problem ; We should focus on models and requirements . exactly , Someone said we were approaching the end of the code . Soon , The code will be generated automatically , There is no need to write . Programmers are totally useless , Because business people can generate programs directly from the specifications .

I don't think the code will disappear , Code is to programmers , Just as words are to writers . No matter how the times develop , Writers also need to write a work through words . Artists also need tools to express themselves . Code is the way programmers express .

remember , Code is really the kind of language we end up using to express requirements . We can create all kinds of languages close to our needs . We can create tools to help parse and aggregate requirements into a formal structure . However , We can never abandon the necessary accuracy —— So the code lasts forever .

What is neat code

grace

I like elegant and efficient code . The code logic should be straightforward , Defects are hard to hide ; Minimize dependence , Make it easy to maintain ; Refine error handling code based on a layered strategy ; Optimize performance , Save luring others to do unruly optimization , Make a mess . Neat code does only one thing .
------ Bjarne Stroustrup, C++ The inventor of language ,C++ Programming Language( Chinese translation 《C++ Programming language 》) Author of a Book .

Bjarne It was used “ grace ” The word" . Good point !
Bjarne It is obvious that clean code is pleasant to read . Read this code , It's like seeing a handmade music box or a well-designed car , Make you smile .
Bjarne Efficiency is also mentioned —— And mentioned twice . It comes from C++ The mouth of the inventor , Perhaps not surprisingly ; But I don't think we are simply pursuing speed . Wasted computing cycles are not elegant , Not pleasant . Attention Bjarne How to describe that kind of unsightly result . He used it “ lure ” The word . Sincere words . Bad code causes chaos ! When someone modifies bad code , It tends to get worse and worse .

This is the broken window theory . Buildings with broken windows seem to be left unattended . So others don't care anymore . They let the windows continue to break . Eventually, he also participated in sabotage activities , Graffiti on the outer wall , Let rubbish pile up . A broken window opened the way for the building to collapse .

Do only one thing

Bjarne With “ Neat code does only one thing ” Conclusion . Beyond all doubt , Many principles of software design will eventually come down to this aphorism . So many people have made similar remarks . Bad code wants to do too much , It's meant to be confusing 、 The purpose is ambiguous . Clean code strives to focus . Each function 、 Every class and every module is focused on one thing , Completely free from the interference and pollution of the surrounding details .

No repetition

1、 I care most about code repetition . If the same piece of code appears repeatedly , It means that an idea is not well reflected in the code . I tried to find out what it was , Then try to express it more clearly
2、 Eliminating duplication and improving expressiveness have benefited me a lot in terms of clean code , Just keep these two points in mind , When you improve dirty code, there is a big difference
Reduce duplicate code , Improve expression , Build simple abstractions early . This is how I write clean code .
----------- Ron Jeffries, Extreme Programming Installed( Chinese translation 《 Extreme programming implementation 》) as well as Extreme Programming Adventures in C#( Chinese translation 《C# Extreme programming adventure 》) author

Expressive

in my opinion , Meaningful naming is a way of expressing power , I often revise it several times before I make a name . With the help of Eclipse Such modern coding tools , Renaming is extremely inexpensive , So I have no scruples . However , Expressiveness is not only reflected in naming . I also check whether the object or method wants to do too much . If the object has too many functions , It is best to split into two or more objects . If the method has too many functions , I always use extraction (Extract Method) Reconstruction of , So as to get a more clear way to explain their own functions , And several other ways to implement these functions .
----------- Ron Jeffries, Extreme Programming Installed( Chinese translation 《 Extreme programming implementation 》) as well as Extreme Programming Adventures in C#( Chinese translation 《C# Extreme programming adventure 》) author

Someone cares

I can list all the features of neat code that I noticed , But one of them is fundamental . Neat code always looks like someone who cares about it . There is little room for improvement . The code author thought of everything , If you try to improve it , Always return to the origin , Admire the code someone left you —— The code left by someone who puts his heart into it .
----------Michael Feathers, Working Effectively with Legacy Code( Chinese translation 《 The art of modifying code 》) Author of a Book .

Michael Pierce to the heart of the matter . Clean code is the code that the author cares about . Someone took the time to keep it simple and orderly . They paid due attention to the details . They care about .

Have a good test

Neat code should be readable and supplemented by developers other than the author . Unit testing and acceptance . It uses meaningful names . It only provides one way to do one thing, not multiple ways . It has as few dependencies as possible , And clearly define and provide clarity 、 As little as possible API. The code shall express its meaning literally , Because of different languages, not all necessary information can be clearly expressed by the code itself .
--------Dave Thomas, OTI Company founder ,Eclipse The godfather of strategy .

Dave In readability and Grady Hold the same view , But there is one important difference .Dave Assertion , Clean code is easy for others to add . It seems obvious , However, it should not be overemphasized . After all, there is a difference between easy to read code and easy to modify code .
Dave Tie neatness to testing ! Ten years ago , It would be surprising . But test driven development (Test Driven Development) Has had a far-reaching impact in the industry , Become one of the basic regulations .Dave That's right . The code not tested is not clean . No matter how elegant it is , No matter how readable 、 How easy to understand , Microtest , Its uncleanness is also known .

Keep the code as small as possible

Dave Mentioned twice “ As far as possible ”. obviously , He advocates small pieces of code . actually , People have been emphasizing this point since the software came into being . The smaller the better. .
Dave It also mentions , The code should literally express its meaning . This view comes from Knuth Of “ Literal programming ”(literate programming. The conclusion is that the code should be written in a human readable way .

How to write simple code

Pay attention to naming

Naming is everywhere in software . We give variables 、 function 、 Parameters 、 Class and package naming . We name the source code and its directory . We give jar file 、war Document and ear File naming . We name 、 name , Keep naming . Since there are so many names to do , Do it well . Here are some simple rules for a good name .

Worthy of the name

It's simple to say . We want to emphasize that , It's serious . It takes time to choose a good name , But it saves more time than it takes . Pay attention to naming , And once you find a better name , Just replace the old . Do it , The person who reads your code ( Including yourself ) Will be happier .

Avoid misleading

Programmers must avoid leaving false clues that hide the meaning of the code . Words contrary to the original meaning should be avoided . for example ,hp、aix and sco Should not be used as variable names , Because they are all UNIX Platforms or classes UNIX The proper name of the platform . Even if you're writing a trigonometric program ,hp It looks like a good abbreviation [2], But that may also provide an error message .
Don't use it. accountList To refer to a group of accounts , Unless it's really List type .List The word has a special meaning for programmers . If the container containing the account number is not really List, It will lead to wrong judgment [3]. therefore , use accountGroup or bunchOfAccounts, Even directly accounts Everything will be better .

Use readable names

Humans are good at remembering and using words . A considerable part of the brain is used to hold and process words . Words can be read . Humans have evolved to have such a large part of the brain for processing speech , If you don't make good use of , It's a shame .
If the name doesn't read , You'll be like a silly bird when you talk about it .“ Ah , here , Snivel. Ah San likes to press and kick (bee cee arr three cee enn tee) above , There's a skinny one (pee ess zee kyew) Integers , See ?” It's not a small thing , Because programming is a social activity .

Use searchable names

There's a problem with single letter names and numeric constants , It's hard to find it in a large text .
look for MAX_CLASSES_PER_STUDENT be prone to , But looking for numbers 7 That's the trouble , It could be part of some file name or other constant definition , Appears in various expressions used to disagree with the graph . If the constant is a long number , He was wrongly corrected again , Will escape the search , To make a mistake .

How to name the class name

Class names and object names should be nouns or noun phrases , Such as Customer、WikiPage、Account and AddressParser. Avoid using Manager、Processor、Data or Info Such a class name . Class names should not be verbs .

How to name the method name

Method names should be verbs or verb phrases , Such as postPayment、deletePage or save. Property accessor 、 Modifiers and assertions should be named according to their values , Combined with Javabean standard [10] add get、set and is Prefix .

function

Short

The first rule of a function is to be short . The second rule is to be shorter . I can't prove this assertion . I can't give any better results for small functions . What I can say is , near 40 Over the years , I've written about functions of different sizes . I wrote about the abominable long 3000 The weariness of action , I've also written a lot about 100 Row to 300 The function of line , I wrote about it 20 Row to 30 Yes . After a long trial and error , Experience tells me , The function should be small .

Do one thing

Function should do one thing . Do it well . Just do this one thing .

Each function has an abstraction level

Make sure the function does only one thing , All statements in a function must be at the same level of abstraction .
Mixing different levels of abstraction in functions , Often confusing . Readers may not be able to judge whether an expression is a basic concept or a detail . What's worse is , Like a broken window , Once the details are mixed with the basic concepts , More details will be tangled in the function .

Function parameter

The ideal number of parameters is zero ( Zero parameter function ), The second is one ( One parameter function ), Again, two ( Two parameter function ), Three should be avoided as much as possible ( Three parameter function ). There are enough special reasons to use more than three parameters ( Multi parameter function )—— So don't do it anyway .

When there are too many function arguments , You should encapsulate it as an object .

No side effect

The side effect is a lie . The function promises to do only one thing , But still do other things that are hidden . Sometimes , It makes unexpected changes to variables in its own class . Sometimes , It turns variables into parameters passed to functions or global variables of the system . In either case , It's all destructive , It can lead to weird temporal coupling and sequence dependence .

Pull away try/cache block

Try/catch Code blocks are ugly . They mess up the code structure , Confuse error handling with normal processes . It's better to try and catch The main part of the code block is pulled out , In addition, it forms a function .

Function should do only one thing . Error handling is one thing . therefore , The wrong function should not do anything else . This means that if the keyword try Exists in a function , It should be the first word of this function , And in catch/finally There shouldn't be anything else behind the code block .

Don't repeat yourself

Repetition can be the root of all evil in software . Many principles and rules of practice are created to control and eliminate duplication . for example , All database paradigms serve to eliminate data duplication . I want to see , How object-oriented programming centralizes code into base classes , Thus, redundancy is avoided . Aspect oriented programming (Aspect Oriented Programming)、 Component-oriented programming (Component Oriented Programming) It is more or less a strategy for de duplication . It seems , Since the invention of subroutines , All innovation in software development is a constant attempt to eliminate duplication from source code

Format

When someone looks at the underlying code implementation , We want them to be neat 、 Shocked by consistency and perceived attention to detail . We want them to raise their eyebrows , Look all the way down . We want them to feel the professionals who work for them . But if all they see is a bunch of the ghost symbols written by drunken sailors , Then most of them will come to the conclusion , Think that any other part of the project is equally indifferent to details .

Learn from newspapers

The newspaper consists of many articles ; Most are short and vigorous . Some are a little longer . Few people fill a whole page . To do so , Newspapers are available . If a newspaper only publishes a long story , It's full of unorganized facts 、 date 、 Name, etc , No one will read it .

Source files should be like newspaper articles . The name should be simple and clear at a glance . The name itself should be enough to tell us if it's in the right module . High level concepts and algorithms should be given at the top of the source file . The details should unfold gradually , Until you find the lowest level of functions and details in the source file .

Objects and data structures

Object oriented and procedural code

Procedural code ( Code using data structures ) It is convenient to add new functions without changing the existing data structure . Object oriented code is convenient for adding new classes without changing existing functions .
On the contrary, it makes sense :
Procedural code is difficult to add new data structures , Because all functions have to be modified . It is difficult to add new functions to object-oriented code Count , Because all classes have to be modified .
therefore , For the more difficult things about object orientation , It's easier for procedural code , vice versa !

In any complex system , There will be times when you need to add new data types instead of new functions . At this time , Object and object-oriented are more suitable . On the other hand , There will also be times when you want to add new functions instead of data types . under these circumstances , Procedural code and data structures are more appropriate .

Demeter's law

The famous Demeter law (The Law of Demeter) Think , The module should not understand the internal situation of the object it operates on . As seen in the previous section , Object hiding data , Exposure operation . This means that objects should not expose their internal structure through accessors , Because it's more like exposing rather than hiding its internal structure .
More precisely , Demeter's law holds that , class C Methods f Only the methods of the following objects should be called :
• C
•  from f Objects created ;
•  Pass as parameter to f The object of ;
•  from C Object held by entity variable .
Method should not call the method of an object returned by any function . In other words , Just talking to friends , Don't talk to strangers .

unit testing

TDD The three law

Everyone knows that TDD We are required to write unit tests before writing production code . But this rule is just the tip of the iceberg . Look at the following three laws :
Law one   Before writing unit tests that fail , Do not write production code .
Law two   You can only write unit tests that just fail , If you can't compile, you can't pass .
Law three   You can only write production code that is just enough to pass the current failing test .
These three laws limit you to about 30 Second by second . Tests are written with production code , Tests are written only a few seconds before production code .
Write the program like this , We write dozens of tests every day , Write hundreds of tests every month , Write thousands of tests every year . Write the program like this , The test will cover all production code . The amount of test code is enough to match the amount of production code , Leading to daunting management problems .

Keep the test clean

Test code is as important as production code . It's not a second-class citizen . It needs to be thought about 、 Designed and cared for . It should be as neat as production code .

Five principles of neatness test

The neat test also follows the following 5 Bar rule , this 5 The first letter of this rule constitutes the title of this section :
Fast (Fast) The test should be fast enough . Tests should run fast . The test runs slowly , You don't want to run it frequently . If you don't run tests frequently , You can't find the problem as soon as possible , Nor can it be easily corrected , It is not easy to clean up the code . Final , The code will rot .
Independent (Independent) Tests should be independent of each other . One test should not set conditions for the next . You should be able to run each test individually , And run the tests in any order . When tests are interdependent , The first failure will lead to a series of test failures , Make problem diagnosis difficult , Hidden subordinate errors .
repeatable (Repeatable) The test should be repeatable in any environment . You should be able to 、 Run tests in a quality inspection environment , It can also run the test on the train without network with notebook computer . If the test cannot be repeated in any environment , You will always have an interface to explain its failure . When environmental conditions are not available , You will also not be able to run tests .
Self contained verification (Self-Validating) The test should have Boolean output . Whether it's pass or fail , You shouldn't check the log file to make sure the test passed . You should not manually compare two different text files to confirm that the test passed . If the test is not self-sufficient , The judgment of failure will become subjective , Running the test also requires longer manual operation time .
In time (Timely) Tests should be written in time . Unit tests should be written just before the production code that makes them pass . If you write tests after writing production code , You will find production code hard to test . You may think that some production code itself is difficult to test . You may not design testable code .

原网站

版权声明
本文为[Blockchain research]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210537010378.html