Share E-Book

24 Patterns for Clean Code. Techniques for Faster, Safer Code with Minimal Debugging (Robert Beisert) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Rating 3.5 AI initial rating

Log in to rate

Software
Language English

Evermore Instructional, 2016. There is the right way to do things, and there's the wrong way to do things. Unfortunately, most of us don't really take the time to figure out which way is which.Robert lays out 24 patterns of thought and design that tend to produce faster, more reliable, and easier to maintain code without noticeably increasing the difficulty or decreasing the speed of coding. 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.

Format PDF
Size 4.6 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
24 Patterns for Clean Code Techniques for Faster, Safer Code with Minimal Debugging By Robert Beisert Published January 2016 This work protected under U.S. Copyright Law
Page 3
Introduction Document as you go Treat your documentation as a contract Use VI operations to keep .h and .c files consistent Comments - your path back through history Leave the standards alone - avoid changing defaults (aliases and/or variables) 2. Debugging and Maintenance C “classes” using naming conventions Employ Meaningful Return Types Use Meaningful Names Always compile with -g Log Messages - the more content, the better Build around Errors, not Successes Employ the if-else chain Check the boundaries (including nonsense) 3. Code Conventions Create in order, Destroy in Reverse Order, Mutex in same order every time Yin and Yang - For every alloc, there is a free (and for every {, a } ) Use const to prevent functions from changing the inputs Don’t mangle your iterators (iterators are used only to iterate) Headers should not create object code Prototypes and Optimization - only convert when ready 4. Thought Patterns One Sentence Employ the 3-10 rule Logical Unity of Form and Function
Page 4
Design: Everything You Need, and Only What You Need Object Oriented C Conclusion
Page 5
Introduction When I was a child, I thought I could do any number of things. Before I could talk, I fancied that I was really good at running. In kindergarten, I was proud of my penmanship and math skills. In elementary school, I honestly thought I was an excellent video gamer. However, I was not that good at any of those things. It’s not like it was exactly my fault. After all, I was still new at these activities. I had not received the training and the merciless beatings that life throws at us to make us better. The same rule applies to programming. Early on, I became aware that there had to be better ways to do things. My code was unruly and difficult to read, much less debug. I didn’t know how some relatively simple things worked. I made the same mistakes again and again. But I learned. This book contains some relatively basic approaches for programming in languages such as C. In fact, although I preferentially work in C, these patterns demonstrate how to accomplish most tasks faster and easier in any language. I strongly suggest that you skim this work once, then go back to study the details. None of these are difficult, but all are essential for optimal programming.
Page 6
1. Simplifying Your Work Document as you go Ask any programmer what the most irritating part of programming is, and they’ll either say “debugging” or “documentation”. Admittedly, I am one of the rare exceptions (I dislike the “coding” part most, because it’s less about solving a problem than it is translating the solution), but I have a standard which removes the most irritating factors of documentation. The Classic Method During the programming phase, code authors sit together and draft up diagrams and flowcharts for how their code should function. They then sit down at their machines and, over a course of weeks and countless modifications, produce some quality code. After they’re done writing the code, they go off to do more coding. Because they’re programmers, this is their natural state. At some point, however, they have to sit down and create documentation which details the operations of their functions, the code’s basic assumptions, and requirements on the end- users. The thing is, at this point, even the authors don’t remember what the code does, or what the assumptions are. Even if they are documenting the code right after cleaning it up, there are functions whose purposes are now essentially erased from memory. This means that the authors have to sit down, re-read their code, figure out the assumptions and operations again, and remember what the requirements are. What a long, boring waste of a programmer’s time. Documenting as you go First, we have to remember a vital documentation rule: Everything which is related to the code is documentation. All your comments, graphs, doodles, and idle musings are valuable insights into the mind of the programmer which constructed this code (as opposed to the programmer who is currently reading the code). I highly recommend that, as you write your code, you place useful comments and tags in there. Something as simple as “THIS BLOCK IS FULL OF VARIABLES WE NEED FOR THIS OPERATION” can save you minutes of inquiry, while longer comments detailing the flowchart for a function (or subfunction) can save you hours. Also, if you use meaningful naming conventions and meaningful cross-referencing, you can skip around your code in
Page 7
seconds, connecting the spaghetti into a single whole. Of greatest importance to the end-user, always document your function’s purpose, return types, and arguments before you even start fleshing out the details. This will spare you confusion (as you never let the complexity of the function spiral beyond the defined purpose), and it will allow you to create your final documentation almost effortlessly. NATURALLY, IF YOU MAKE FUNDAMENTAL CHANGES TO A FUNCTION, YOU HAVE TO UPDATE YOUR DOCUMENTATION. IT MAY STILL BE WORTH LEAVING SOME OF THE OLD CODE COMMENTED OUT, JUST SO YOU HAVE EVIDENCE OF A USEFUL PATTERN OR IDEA. Doxygen I am a tremendous fan of the doxygen program. This program interprets declarations and specially-formatted comments to generate HTML documentation, complete with hyperlinks, graphs, and flow-charts. With this tool, you can rapidly convert useful source- code commentary into powerful documentation. The format is extremely minimal. All comments surrounded by /** … **/ blocks are interpreted by Doxygen, along with all in-line comments starting with ///. This means that a single-character addition in a regular comment results in a doxygen comment. The tag system in doxygen is also simple. Every line beginning with a particular tag will produce a section of meaningful output in the final documentation. These tags include (but are not limited to): @param – Describes a function input parameter @param[in] – Declares the parameter to be input only @param[out] – Declares the parameter to be output only @param[inout] – Declares that the parameter is read in, transformed, and passed back out @return – Describes the expected return value(s) @author – Lists a name as the author of a file, function, etc. @brief – Declares that the line which follows is a brief description of the function @detail – Declares that everything up to the next tag is part of a detailed function description We also can use ///< to describe enumerations, objects within a structure, etc. It is a tremendously powerful tool which encourages ample in-source commentary and provides rapid documentation on demand. For more information, check out the Doxygen user’s manual.
Page 8
Lesson: Documenting as you go improves the accuracy of your documentation, reduces the time it takes to generate documentation, and allows the programmer to spend more time on more valuable (or interesting) tasks.
Page 9
(This page has no text content)
Page 10
Treat your documentation as a contract When you commit to a set of documentation, you are telling all the users how your code will work and how they should use it. This has a trickle-down effect, such that any changes to the documented features can destroy entire suites of programs. Violation of the Rule Suppose you provide documentation for an early-release form of your code. Other teams and other companies start working your function calls and structures into their code. Perhaps these new codes are built into libraries, which are used to build large distributables. Then you add just one parameter to one major function. It’s mostly harmless, right? Unfortunately, you just broke everything. Now the groups that were using your code have to go through the entire design process again. They have to update all of their code to match your new definitions, and then they have to test everything to make sure it still works. Your 15 second change results in tens (or even hundreds) of hours of work across the board. Adherence to the Rule There are several ways we can preserve the documentation contract. 1. Employ modular design principles. All additions to the documentation are new modules, while the old modules remain intact. This allows your end-users to decide whether to accept your changes or not. 2. Hide what you’re doing. If you leave the function interfaces alone, you can make changes to the functionality without necessarily informing the end-users. This only really applies with runtime libraries, though. 3. Build from wide to narrow. Just like a pyramid, you start with functions that take all the arguments you can possibly think of. Then, you tighten the focus with each new function until you have the minimal function. This pattern is extremely useful when you have default inputs but you still want to be able to change those defaults if desired.
Page 11
Lesson: Your Documentation tells the world how to use your code. Make sure that you preserve the documented functionality and interfaces.
Page 12
(This page has no text content)
Page 13
Use VI operations to keep .h and .c files consistent Generally, I don’t much care for IDEs. In my experience, IDEs add increasingly specific features to maintain their relevance, resulting in bloated software which takes too many resources to accomplish a relatively simple task. However, as functions get more complex, it becomes increasingly difficult to make your code match the original prototypes. This is where Vi’s “yank” and “mark” features truly shine. Yank to Mark We know that the vi equivalent to “copy-and-paste” is “yank-and-put”. What many people do not realize is that you can open any number of files in a single vi instance, allowing you to yank from one file and put into another. The final piece of this puzzle is the “mark” feature. It is possible for us to create a mark on a given line with the following command: m<letter> EXAMPLE: ma We can then return to that line with the command: ‘<letter> EXAMPLE: ‘a This allows us to yank large sections of code from one place to another using the command: y’<letter> EXAMPLE: y’a This is the “yank to mark” feature. Application 1: Code Completion We can use the yank-to-mark feature to copy entire function prototypes back into our new code. To do this, we first navigate to the spot where our function call will go. We can then go to the header file containing the required function prototype and yank it out. Finally, we “put” the prototype into our new code, then swap the prototype values out for our new values. For example, suppose we have a prototype that looks something like this in a file FILE.H: int function(
Page 14
int Value_one, char *Value_two, struct astructure Value_three ) If we want to call this function in main.c, we can open vi like so: vi main.c file.h We then yank everything from “int function(” to “)” using our “yank-to-mark” feature and put it into main.c. At that point, it is a simple matter to replace the return value and all parameters with the values that we should pass into the function, all while ensuring that the types match. Application 2: Headers match Code For many programmers, it is a pain to ensure that your headers and code files match exactly. This is easily achieved with yank, however. We can copy all the code from the start to the end of the code file using the command: gg (go to start) yG (yank to end of file) We can then put everything from the code file directly into the header. We can delete all the code inside our function prototypes using the “go-to-matching” command. We can highlight the start of a code block (marked by the { brace) and hit the % key to go directly to its matching closing brace (}). Thus, we can delete all the code using the command: d% Then, we can insert a semicolon to complete the function prototype. Using this feature, we can create header files in seconds which EXACTLY match the code files to which they belong. NOTE: IF YOU’RE USING DOXYGEN-STYLE COMMENTS, YOU SHOULD WRITE THEM DIRECTLY INTO YOUR CODE FILES. THIS WAY, WHEN YOU UPDATE THE FUNCTION DEFINITIONS IN THE CODE, YOU CAN PERFORM ANOTHER SIMPLE YANK TO REPLACE THE OLD PROTOTYPE WITHOUT HAVING TO ADJUST YOUR COMMENTS AGAIN. IT IS A REAL TIME-SAVER AND IT ALLOWS YOU TO SEE YOUR COMMENTS WHEREVER THE FUNCTION IS DECLARED. Lesson: IDEs such as VI contain powerful tools while remaining minimally invasive. Learn to leverage these simple tools to speed up development.
Page 15
(This page has no text content)
Page 16
Comments - your path back through history Programmers are not unlike Dory from “Finding Nemo”, in that we have a limited memory. It seems like every time we sit down to code, and we are randomly struck by a lightning bolt of inspiration, we immediately lose it when we notice something shiny. That’s an extreme example, sure, but programmers do have a problem of forgetfulness. It’s the nature of the job – we have so many tasks to perform and so many paths to track that we can’t possibly hold on to all our thoughts. Thank God for comments. Level 0 Comments: In-line This practice, so common to college-age programmers, is often lost quickly in the “real world”. However, these comments are perhaps the most useful comments we can have. After all, which is faster: tracing all the calls and variables in a block of code, or reading a short sentence describing the intended function? While I generally recommend you not write useless comments (“This printf() function prints a line of text”), there are several key things you can do: Outline your code BEFORE you start writing, then use that outline to walk your way back through it later Explain why you chose one function over another Describe the operation of a library-based function, so you don’t have to keep looking it up Leave TODO markers in your code (vi will highlight these specifically, so they’re easy to find again) Comment out a “bad” line, so that you can see what it did before the fix Leave some tag that’s easy to search for later (like TODO, only without the convenient highlighting) etc. All of these comments improve readability by restoring some of the mindset you had when you were writing the code in the first place. Level 1 Comments: Flowerboxes Less common, but equally important, are flowerbox comments. These comments allow the author of a piece of code to relay more detailed information in a compact, highly-visible
Page 17
format. There are a number of uses for flowerboxes: Doxygen comments – these not only generate HTML documentation, but they also describe a function’s purpose, arguments, and return types inside of the code itself I cannot recommend Doxygen-style commentary enough Seriously, if you haven’t looked into it before, LOOK IT UP Flow descriptions – these comments describe a higher-level flow for a function or program, allowing the programmer to quickly get a deeper sense of how the program is supposed to work Disclaimers and Formalities – Want the world to know who designed the code, and what it’s for? Flowerboxes at the top of the page get it done Detail an event or conversation relevant to the code – Maybe an offhand quote from a fellow programmer inspired the design of the next segment of code. Recording that information helps future programmers understand not just what the code is doing, but why you chose to do it that way Level 2 Comments: Logs Some of my more recent work contains fewer comments than I usually employ. This is because, instead of using inline commentary to describe an event, I print out a string detailing what is supposed to come next. These are still basically comments, because they serve the purpose of a comment while providing information during runtime. It’s a win-win. Level 3 Comments: Code Segments Sometimes (usually) we decide to replace whole sections of code with new code. However, when we do a delete-and-replace, we run the risk of damaging functionality with no way to roll back the source. Using flowerboxes or #if statements, we can make sure that the old code is safely kept away from the final product while allowing us to restore that functionality if the time comes. Also, it’s interesting to see how the code has evolved over time.
Page 18
Level 4 Comments: Extra Documentation Strictly speaking, everything that happens during the development of a piece of code should be documented. All conversations, whiteboard diagrams, emails, flowcharts, and other documents should be retained, if only so you can see what decisions were made. Lesson: We put comment features into our languages for a reason. Use them liberally to spare everyone a lot of time and effort.
Page 19
(This page has no text content)
Page 20
Leave the standards alone - avoid changing defaults (aliases and/or variables) Fun fact: more than a few code conventions are inspired by the fact that everyone’s computer is set up differently. Problem 1: Non-standard tab spaces The standard UNIX/Linux tab standard is 8 spaces. That means that, to create a similar spacing to the default tab, you would have to hit the space bar eight times. This standard embraces the binary underpinning of computers, and it creates effective spacing comparable to a seven-character variable and a space. However, for one reason or another, people have been changing that standard value. I’ve seen everything from 2 spaces to 7 spaces (although no one seems to go over 8), but rarely do I see anyone employing the default tabs. This makes it harder to write “pretty” code, because notation that lines up nicely on one machine looks chaotic on another machine. Of course, you could always destroy your space bar to avoid tabs altogether, but I argue it’ll never be worth it. At worst, it makes your code harder to modify without being really obvious, and at best it takes time that you could spend anywhere else. BESIDES, IF YOU NEED TO REDUCE THE TAB SIZE TO MAKE YOUR CODE FIT ON THE LINE, YOU PROBABLY NEED TO SERIOUSLY REEVALUATE YOUR CODING PRACTICES. Problem 2: Aliasing Most beginning programmers are unaware that the UNIX/Linux systems allow you to assign an alias (new name) to a function or set of commands. These are stored in the system instead of in a code file. The problem here should be obvious: the other guy’s computer lacks your alias. This usually trips up programmers when they are helping out a friend, only to find that their aliases don’t work. Generally speaking, don’t use aliases unless you can comfortably operate without them. Problem 3: Other There are any number of customization options on machines these days, and most of them are harmless. At the end of the day, it usually doesn’t matter to me whether the machine has a GNOME, X, or KDE environment. I can even work with VI when someone’s fiddled
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay

Every 10 yuan is 1 year of VIP; the remainder counts as months (5 yuan is 5 months, 100 yuan is 10 years). Signed-in users are enabled immediately and both you and the admin get an email. Guests receive an ID and are sent to register.

← Back to List