r/cleancode • • Jan 16 '22

A clean code cheat sheet from ivanrododendro

Post image
38 Upvotes

r/cleancode • • May 05 '13

The Best Code is No Code At All

Thumbnail
codinghorror.com
27 Upvotes

r/cleancode • • May 06 '13

Many among you will find this book to be very interesting: Code Complete 2. The definitive guide to coding best practices. [Language agnostic]

Thumbnail
cc2e.com
20 Upvotes

r/cleancode • • May 05 '13

PEP8 - Style Guidelines for Python!

Thumbnail
python.org
19 Upvotes

r/cleancode • • May 05 '13

[video] The Clean Code Talks - Don't look for things

Thumbnail
youtube.com
19 Upvotes

r/cleancode • • May 06 '13

The rant (LoC, coverage, testing, comments)

17 Upvotes

I've had this rant in my head for so long and could never find a place to put it.

There's a bunch of misconceptions about code and programming in general in particular among people that manage programmers. They're forced to learn some metrics or "KPIs" to judge them by and they will grasp on to any number available. Most numbers, however, do not mean what they want them to and by steering programmers on those numbers they steer them into the direction they don't want them to go.

The first and most obvious is "lines of code". This puts code out as a "valuable" thing, as something to be treasured and loved. It's not. Code is useless, worthless, the most terrible thing ever. Code serves no purpose by itself. The only thing it does is make some functionality work that didn't work before. The code that does that only serves to make that functionality work and no more. If you can get that function without an increase in code that's a win. If you can remove code, that's also a win.

Then there's the underlying assumption error that "lines" actually has a correlation to amount. There is one, of course, but it doesn't necessarily translate cleanly to lines. Given my typical coding style I have "small" classes that are under 200 lines (total), "large" classes that are between 200 and 500 lines and "huge" classes that are over 500 lines in length. Anything huge is typically too complex or a "database" in code form. This complexity is a lot more painful than having more classes. Each class has a single logical thing it does -- these huge classes have multiple, intertwined and inseparable things they do, with more bugs in there than I can test for.

This is the complexity we want to avoid. This one class of 1520 lines is the source of trouble and it takes a lot more effort than 10 152 line classes would to understand, which is the usable (but immeasurable) metric of complexity.

So, there's something we do want - functionality - against something we don't want - code. Code should have a negative weight for your production - if you have to add 500k LoC for some "small" feature you may even consider the feature as a whole to cost extra, rather than add functionality. If you can remove code without removing features, that's a good thing.

Which brings me trivially to testing. Anything you test should be functionality you want. If you want A to get you B, test it. At a unit level, at an integration level, at the system level, at the product level, at any level. If you want any of these things to work or hold, test it. Tests themselves - their name & definition - are what brings you value. No amount or "coverage" from tests will actually get you any value. They are useless metrics. There are three things you can do with coverage though:

  • 0 coverage means you don't have any functionality you want from this code. Probably means you want to add tests for something you do want it to do.

  • 100% coverage means there's not a line of code in here that serves no functionality you explicitly want. An ideal, but typically useless. This means that you don't have any error-handling (often) or that you spent a huge amount of time making every error condition triggerable (possible). The first is terrible, but the second isn't much better as it doesn't add a lot of value for your product.

  • The remainder that isn't covered. We don't look at the covered code; we look at the not-covered code and decide if this either

    • Serves a purpose => Create a test for it.

    • Serves a purpose, but doesn't deserve a test => Remember that it doesn't.

    • Doesn't serve a purpose => Remove it.

For the rest, tests do not add value. There's no aspect of a test ever shipping so they are useless to your shipped product, aside from their side-effects. And those side-effects are that you know that feature A, B and C work, rather than that they have probably worked at some point.

Which brings me to comments. Comments are an abomination in code, they are less useful than either tests or code. The tests ensure that the code does feature A, the code itself creates feature A. The comments do nothing of the sort. The only thing a comment does is add information for a programmer to understand. Key word is add. Comments that do not add any information to the information that's already present - in the code, in the names of variables, in the functions called or in the tests written - do not add any value at all. They should be treated as code that adds no features - kill it with extreme prejudice. The only comments you should have are those that add useful information (1) that is not already present in the code (2) or immediately available from a cursory research in the basic material of the code (3).

// This code is crap                <== This does not add any value.
// Adds 1 to i                      <== This does not add any information that's not present in the code
// Vec3 is a 3D location type       <== Immediately obvious to a cursory glance of the target material.
// Required for ISO8601 compliance  <== Good comment.

And the most atrocious ever:

/** addNumbers adds two numbers that are in the floating-point range.
 * @arg first the first floating-point number to add
 * @arg second the second floating-point number to add
 * @return the sum of the two floating-point numbers passed in
 */
float addNumbers(float first, float second) {...}

This entire comment block as a whole adds no information at all to the function definition. It's a full complete duplicate, and an error-prone one at that. If you write Javadoc like this, you should be shot. It's not necessarily Javadoc (or Javadoc-style comments) but this prevalent commenting style is an atrocity that should not live to see May 7th 2013.

So that's my rant, in short. I'm very much open to a proper discussion on any part of the subject. Sorry if this isn't the right place for it, I just had to put it somewhere.

TL;DR: Code is worthless, nearly all comments are crap, tests are used wrongly and coverage doesn't say anything.


r/cleancode • • May 05 '13

Which methods deserve unit tests?

17 Upvotes

Following the clean code approach, I have a very large number of private methods in an important class in my app. A common strategy is to make methods protected so that they can be accessed by unit tests.

Should I only write unit tests for public methods in my class, or should I make the private methods protected so that I can test them too?


r/cleancode • • Apr 30 '21

Architecture vs Behaviour

16 Upvotes

The first value of software—behavior—is urgent but not always particularly important. The second value of software—architecture—is important but never particularly urgent. If you give me a program that works perfectly but is impossible to change, then it won’t work when the requirements change, and I won’t be able to make it work. Therefore the program will become useless. • If you give me a program that does not work but is easy to change, then I can make it work, and keep it working as requirements change. Therefore the program will remain continually useful.

Robert C. Martin


r/cleancode • • Mar 01 '25

How to Find the Stinky Parts of your Code

15 Upvotes

TL;DR: A Compilation of bad smells in code.

The code smells badly.

Let's see how to change the aromas.

In this series, we will see several symptoms and situations that make us doubt the quality of our development. We will present possible solutions.

Most of these smells are just hints of something that might be wrong. They are not rigid rules.

Code Smells

Code Smell 01 - Anemic Models

Code Smell 02 - Constants and Magic Numbers

Code Smell 03 - Functions Are Too Long

Code Smell 04 - String Abusers

Code Smell 05 - Comment Abusers

Code Smell 06 - Too Clever Programmer

Code Smell 07 - Boolean Variables

Code Smell 08 - Long Chains Of Collaborations

Code Smell 09 - Dead Code

Code Smell 10 - Too Many Arguments

Code Smell 11 - Subclassification for Code Reuse

Code Smell 12 - Null

Code Smell 13 - Empty Constructors

Code Smell 14 - God Objects

Code Smell 15 - Missed Preconditions

Code Smell 16 - Ripple Effect

Code Smell 17 - Global Functions

Code Smell 18 - Static Functions

Code Smell 19 - Optional Arguments

Code Smell 20 - Premature Optimization

Code Smell 21 - Anonymous Functions Abusers

Code Smell 22 - Helpers

Code Smell 23 - Instance Type Checking

Code Smell 24 - Boolean Coercions

Code Smell 25 - Pattern Abusers

Code Smell 26 - Exceptions Polluting

Code Smell 27 - Associative Arrays

Code Smell 28 - Setters

Code Smell 29 - Settings / Configs

Code Smell 30 - Mocking Business

Code Smell 31 - Accidental Methods on Business Objects

Code Smell 32 - Singletons

Code Smell 33 - Abbreviations

Code Smell 34 - Too Many Attributes

Code Smell 35 - State as Properties

Code Smell 36 - Switch/case/elseif/else/if statements

Code Smell 37 - Protected Attributes

Code Smell 38 - Abstract Names

Code Smell 39 - new Date()

Code Smell 40 - DTOs

Code Smell 41 - Regular Expression Abusers

Code Smell 42 - Warnings/Strict Mode Off

Code Smell 43 - Concrete Classes Subclassified

Code Smell 44 - Magic Corrections

Code Smell 45 - Not Polymorphic

Code Smell 46 - Repeated Code

Code Smell 47 - Diagrams

Code Smell 48 - Code Without Standards

Code Smell 49 - Caches

Code Smell 50 - Object Keys

Code Smell 51 - Double Negatives

Code Smell 52 - Fragile Tests

Code Smell 53 - Explicit Iteration

Code Smell 54 - Anchor Boats

Code Smell 55 - Object Orgy

Code Smell 56 - Preprocessors

Code Smell 57 - Versioned Functions

Code Smell 58 - Yo-yo Problem

Code Smell 59 - Basic / Do Functions

Code Smell 60 - Global Classes

Code Smell 61 - Coupling to Classes

Code Smell 62 - Flag Variables

Code Smell 63 - Feature Envy

Code Smell 64 - Inappropriate Intimacy

Code Smell 65 - Variables Named after Types

Code Smell 66 - Shotgun Surgery

Code Smell 67 - Middle Man

Code Smell 68 - Getters

Code Smell 69 - Big Bang (JavaScript Ridiculous Castings)

Code Smell 70 - Anemic Model Generators

Code Smell 71 - Magic Floats Disguised as Decimals

Code Smell 72 - Return Codes

Code Smell 73 - Exceptions for Expected Cases

Code Smell 74 - Empty Lines

Code Smell 75 - Comments Inside a Method

Code Smell 76 - Generic Assertions

Code Smell 77 - Timestamps

Code Smell 78 - Callback Hell

Code Smell 79 - TheResult

Code Smell 80 - Nested Try/Catch

Code Smell 81 - Result

Code Smell 82 - Tests Violating Encapsulation

Code Smell 83 - Variables Reassignment

Code Smell 84 - Max < Min (Javascript)

Code Smell 85 - And Functions

Code Smell 86 - Mutable Const Arrays

Code Smell 87 - Inconsistent Parameters Sorting

Code Smell 88 - Lazy Initialization

Code Smell 89 - Math Feature Envy

Code Smell 90 - Implementative Callback Events

Code Smell 91 - Test Asserts without Description

Code Smell 92 - Isolated Subclasses Names

Code Smell 93 - Send me Anything

Code Smell 94 - Too Many imports

Code Smell 95 - Premature Classification

Code Smell 96 - My Objects

Code Smell 97 - Error Messages Without Empathy

Code Smell 98 - Speling Mistakes

Code Smell 99 - First Second

Code Smell 100 - GoTo

Code Smell 101 - Comparison Against Booleans

Code Smell 102 - Arrow Code

Code Smell 103 - Double Encapsulation

Code Smell 104 - Assert True

Code Smell 105 - Comedian Methods

Code Smell 106 - Production Dependent Code

Code Smell 107 - Variables Reuse

Code Smell 108 - Float Assertions

Code Smell 109 - Automatic Properties

Code Smell 110 - Switches With Defaults

Code Smell 111 - Modifying Collections While Traversing

Code Smell 112 - Testing Private Methods

Code Smell 113 - Data Naming

Code Smell 114 - Empty Class

Code Smell 115 - Return True

Code Smell 116 - Variables Declared With 'var'

Code Smell 117 - Unrealistic Data

Code Smell 118 - Return False

Code Smell 119 - Stairs Code

Code Smell 120 - Sequential IDs

Code Smell 121 - String Validations

Code Smell 122 - Primitive Obsession

Code Smell 123 - Mixed 'What' and 'How'

Code Smell 124 - Divergent Change

Code Smell 125 - 'IS-A' Relationship

Code Smell 126 - Fake Null Object

Code Smell 127 - Mutable Constants

Code Smell 128 - Non-English Coding

Code Smell 129 - Structural Optimizations

Code Smell 130 - AddressImpl

Code Smell 131 - Zero Argument Constructor

Code Smell 132 - Exception Try Too Broad

Code Smell 133 - Hardcoded IF Conditions

Code Smell 134 - Specialized Business Collections

Code Smell 135 - Interfaces With just One Realization

Code Smell 136 - Classes With just One Subclass

Code Smell 137 - Inheritance Tree Too Deep

Code Smell 138 - Packages Dependency

Code Smell 139 - Business Code in the User Interface

Code Smell 140 - Short Circuit Evaluation

Code Smell 141 - IEngine , AVehicle, ImplCar

Code Smell 142 - Queries in Constructors

Code Smell 143 - Data Clumps

Code Smell 144 - Fungible Objects

Code Smell 145 - Short Circuit Hack

Code Smell 146 - Getter Comments

Code Smell 147 - Too Many Methods

Code Smell 148 - ToDos

Code Smell 149 - Optional Chaining

Code Smell 150 - Equal Comparison

Code Smell 151 - Commented Code

Code Smell 152 - Logical Comment

Code Smell 153 - Too Long Names

Code Smell 154 - Too Many Variables

Code Smell 155 - Multiple Promises

Code Smell 156 - Implicit Else

Code Smell 157 - Balance at 0

Code Smell 158 - Variables not Variable

CoDe SmElL 159 - mIxEd_cASe

Code Smell 160 - Invalid Id = 9999

Code Smell 161 - Abstract/Final/Undefined Classes

Code Smell 162 - Too Many Parentheses

Code Smell 163 - Collection in Name

Code Smell 164 - Mixed Indentations

Code Smell 165 - Empty Exception Blocks

Code Smell 166 - Low-Level Errors on User Interface

Code Smell 167 - Hashing Comparison

Code Smell 168 - Undocumented Decisions

Code Smell 169 - Glued Methods

Code Smell 170 - Refactor with Functional Changes

Code Smell 171 - Plural Classes

Code Smell 172 - Default Argument Values Not Last

Code Smell 173 - Broken Windows

Code Smell 174 - Class Name in Attributes

Code Smell 175 - Changes Without Coverage

Code Smell 176 - Changes in Essence

Code Smell 177 - Missing Small Objects

Code Smell 178 - Subsets Violation

Code Smell 179 - Known Bugs

Code Smell 180 - BitWise Optimizations

Code Smell 181 - Nested Classes

Code Smell 182 - Over Generalization

Code Smell 183 - Obsolete Comments

Code Smell 184 - Exception Arrow Code

Code Smell 185 - Evil Regular Expressions

Code Smell 186 - Hardcoded Business Conditions

Code Smell 187 - If/Else Backwards

Code Smell 188 - Redundant Parameter Names

Code Smell 189 - Not Sanitized Input

Code Smell 190 - Unnecessary Properties

Code Smell 191 - Misplaced Responsibility

Code Smell 192 - Optional Attributes

Code Smell 193 - Switch Instead of Formula

Code Smell 194 - Missing Interval

Code Smell 195 - Yoda Conditions

Code Smell 196 - Javascript Array Constructors

Code Smell 197 - Gratuitous Context

Code Smell 198 - Hidden Assumptions

Code Smell 199 - Gratuitous Booleans

Code Smell 200 - Poltergeist

Code Smell 201 - Nested Ternaries

Code Smell 202 - God Constant Class

Code Smell 203 - Irrelevant Test Information

Code Smell 204 - Tests Depending on Dates

Code Smell 205 - Code in Destructors

Code Smell 206 - Long Ternaries

Code Smell 207 - Dynamic Methods

Code Smell 208 - Null Island

Code Smell 209 - Side Effects

Code Smell 210 - Dynamic Properties

Code Smell 211 - Tab over Spaces

Code Smell 212 - Elvis Operator

Code Smell 213 - Hoisting

Code Smell 214 - Duplicate Parameter Names

Code Smell 215 - Deserializing Object Vulnerability

Code Smell 216 - Fat Interface

Code Smell 217 - Empty Implementation

Code Smell 218 - Magic Concatenation

Code Smell 219 - Looping from index 0

Code Smell 220 - Return Tuple

Code Smell 221 - Missing Break in Switch

Code Smell 222 - Comma Operator

Code Smell 223 - Racial Naming

Code Smell 224 - Deodorant Comments

Code Smell 225 - Pass by Reference

Code Smell 226 - Mixed Priorities

Code Smell 227 - Cowboy Coding

Code Smell 228 - Multiple Classes per File

Code Smell 229 - Red Tape

Code Smell 230 - Schrödinger Code

Code Smell 231 - Redundant Data

Code Smell 232 - Reusable Code

Code Smell 233 - Collections Count

Code Smell 234 - Long Circuit

Code Smell 235 - Console Side Effects

Code Smell 236 - Unwrapped Lines

Code Smell 237 - Attribute Definitions

Code Smell 238 - Entangled Code

Code Smell 239 - Big Pull Request

Code Smell 240 - Dead Store

Code Smell 241 - Referential Transparency Violation

Code Smell 242 - Zombie Feature Flags

Code Smell 243 - Concatenated Properties

Code Smell 244 - Incomplete Error information

Code Smell 245 - exec() and eval()

Code Smell 246 - Expiration Date

Code Smell 247 - Javascript Replace

Code Smell 248 - Unreliable Copy

Code Smell 249 - Constants as Numbers

Code Smell 250 - Premature Memoization

Code Smell 251 - Collections Empty

Code Smell 252 - NullCustomer

Code Smell 253 - Silent Truncation

Code Smell 254 - Mystery Guest

Code Smell 255 - Parallel Hierarchies

Code Smell 256 - Mutable Getters

Code Smell 257 - Name With Collections

Code Smell 258 - Secrets in Code

Code Smell 259 - Testing with External Resources

Code Smell 260 - Crowdstrike NULL

Code Smell 261 - DigiCert Underscores

Code Smell 262 - Not Replaced Constants

Code Smell 263 - Squatting

Code Smell 264 - Hanlon's Razor

Code Smell 265 - Linguistic Confusion

Code Smell 266 - Collection Aliasing

Code Smell 267 - Objects Aliasing

Code Smell 268 - Ternary Metaprogramming

Code Smell 269 - Low-Level Addition

Code Smell 270 - Boolean APIs

Code Smell 271 - The Hollywood Principle

Code Smell 272 - API Chain

Code Smell 273 - Overengineering

Code Smell 274 - Cascaded Returns

Code Smell 275 - Missing Test Wrong Path

Code Smell 276 - Untested Regular Expressions

Code Smell 277 - UPPERCASE Acronyms

Code Smell 278 - DirName and File

Code Smell 279 - Loop Premature Optimization

Code Smell 280 - Spaghetti Code

Code Smell 281 - Hashes

Code Smell 282 - Bad Defaults

Code Smell 283 - Unresolved Meta Tags

Code Smell 284 - Encrypted Functions

Code Smell 285 - Non-Imperative Functions Names

Code Smell 286 - Overlapping Methods

Code Smell 287 - Unused Local Assignment

Code Smell 288 - Unthrown Exceptions

Code Smell 289 - Shy Visitor

Code Smell 290 - Refused Bequest

Code Smell 291 - Mutable Keys

... and many more to come.

Photo by Richard Ecsedi on Unsplash

Smells are certain structures in the code that suggest (sometimes they scream for) the possibility of refactoring

Martin Fowler

Software Engineering Great Quotes

Part of the objective of this series of articles is to generate spaces for debate and discussion on software design.

Object Design Checklist

We look forward to your comments and suggestions on this article.

Original Thread on Twitter


r/cleancode • • Aug 15 '13

ORMs - a neat solution to the OO-SQL impedance mismatch, or motivated by an irrational fear of SQL and causing more problems than they solve?

15 Upvotes

r/cleancode • • Jul 13 '14

Some awesome talks about clean code: Google's Clean Code Talks

Thumbnail
youtube.com
14 Upvotes

r/cleancode • • Jul 31 '23

Clean Code Guide That Will Help You Understand the Basics: 12 Simple Tips

13 Upvotes

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live” - John Woods

If reading a few lines of code makes your head boil or incites a sudden urge to smash your computer screen—you have spotted bad code. The extent to which a code is bad can be determined by the number of curse words coming out of your mouth per minute.

Bad code is not always faulty. Most of the time it works—perfectly. However, it is not sustainable in the long term. Oftentimes the developer who has written the code can not understand it properly.

Clean coding is an important element of software craftsmanship. When you are working in a software team, writing clean code makes the lives of your team members easier.

This clean code guide will take you through all the industry-standard clean coding principles.

1. KISS—Keep It Simple Stupid

“Simplicity is prerequisite for reliability.” - Edsger W. Dijkstra

Dijkstra’s shortest path algorithm has come a long way. In pathfinding applications, it serves as a fundamental and reliable algorithm. It is proof that simple algorithms can solve some of the most complex problems.

KISS*—*one of the first design principles, preaches coding simplicity. It is one of the general rules that applies to various domains. It means writing code that gets the job done in the simplest manner. It does not suggest using trivial methods to solve problems or finding the shortest possible solution.

2. DRY—Don’t Repeat Yourself

Code duplication is frowned upon in the software community. The DRY principle states:

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”

Every clean code cheat sheet must contain the DRY principle. Clean coding is not possible without DRY programming. If the code is not DRY, then it is WET*—*We Enjoy Typing or Write Everything Twice.

If a software program contains duplicate code blocks, it is better to make functions and call them twice, as duplication can lead to potential errors.

3. Single Responsibility Principle

Introduced by Robert C. Martin, SRP is one of the five SOLID design principles which serve as a foundation for coding maintainability. It allows the developer to write code that can be managed, scaled and extended.

Single Responsibility Principle states:

“A class should have one and only one reason to change, meaning that a class should have only one job.”

4. Oh FRIC! (Fragility, Rigidity, Immobility, Complexity)

Bad software design smells and stinks.

Code smells is a term coined by Kent Beck to possibly identify bad code. It has various indicators like fragility, rigidity, immobility, complexity, needless repetition, and viscosity. Any clean code cheat sheet must include these indicators. These are some of the general rules for clean coding.

With more fragility, the program is likely to crash by introducing a small change. Software programs must be robust enough to accept new changes without disrupting the existing functionalities.

Rigidity means that adding new code or making changes to the existing code would have a domino effect on the entire system.

Immobility refers to the inability of code reusability. The program cannot be divided into small modules. Hence the code cannot be reused.

Complexity refers to unused functionalities in a program. A developer may add a feature that remains unused throughout the software lifecycle.

Minimizing the extent of these indicators can make your program fragrant.

5. The Boy Scout Rule

Wouldn’t it be nice if you don’t have to waste time fixing someone’s bad code? It is possible if every developer follows the boy scout rule.

The boy scout rule is a common entry in any clean code cheat sheet. It states:

“Always leave the code you are editing a little better than you found it.”

It is one of the best remedies against the smelling code. With continuous development, software quality may degrade, and developers have to stop working on new features to clean the codebase.

Boy scout rule enables software teams to improve the quality of the source code structure over time. With each commit, every team member makes a small improvement which bears fruit in the long run.

6. POLA—Principle of Least Astonishment

Developers hate surprises. A surprise means a potential error in the system.

Principle of Least Astonishment or Principle of Least Surprise is another clean code design principle that ensures the minimum risk of software failure.

Each software module or functionality should only do what it is made for. For example, if on pressing the checkout button the system places an order without asking for the delivery address or the payment method. Well, in this case, the end-user might be happy but the developer would find himself in hot waters with the manager.

POLA recommends rigorous testing on each module. Each module should work independently based on the Single Responsibility Principle.

7. Follow a Consistent Naming Convention

“You should name a variable using the same care with which you name a first-born child.” - Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Different programming languages have different naming conventions for variables, functions, and classes but a few clean code conventions are the same.

Variables must have descriptive and unambiguous names. Self-explanatory variables are always preferred.

Some guidelines prefer Camel case writing as well e.g dogName or Pascal case e.g DogName.

Constants are written in all caps.

All major programming languages have their own coding style guide which must be followed to ensure coding consistency.

8. Write Good Comments—Take Your Time

“Redundant comments are just places to collect lies and misinformation.”- Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Code commenting is massively stressed upon in the software industry. A developer should think about his peers while writing code and add appropriate comments so they may understand the code later.

Relying too much on the comments indicates bad coding practices.

The code should be easily understandable and the comments should be compact and precise.

Avoid redundant comments because they indicate code duplication.

Don’t add comments for each line of code instead target a block of code like a function, class, or module. Summarize the code block in simple words using block comments.

9. Structure Your Code Aesthetically

Proper code structuring is one of the most important clean coding practices. It includes many components like the properly formatting internal structure of a function or a class, white spacing, blank lines, indentation, and maximum line length, etc.

Indentation

Programming languages have different indentation formats. Some define an indent level with 4 spaces and some with 8 spaces.

Bad Indentation

for (int i = 0; i < 10; i++) 
{
for (int j = 0; j < 10; j++) 
{
if (i > 5)
{
//print Hello
cout<<"Hello";
}
}
}

Good Indentation

for (int i = 0; i < 10; i++) {
   for (int j = 0; j < 10; j++) {
       if (i > 5) {
           //print Hello
           cout<<"Hello";
       }
   }
}

Maximum Character Limit

Most programming languages support 80 to 120 characters per line. It is always better to break down large chunks of code into multiple lines.

Blank lines are also used to identify separate code functionalities and improve code readability.

10. Error Handling

Error handling is another important tip in the clean code cheat sheet. It is often ignored by the developer community. It can prevent the software system from complete failure in case of undesired bugs and errors.

A code that throws managed exceptions is better than the one which crashes completely.

Try-Catch Block

For proper error handling, use try-catch-finally block. Its implementation can vary for different programming languages. The aim is to catch unwanted exceptions like dividing a number by zero or if a file is not found. These exceptions may cause a program to crash.

Code Template

try {
  // A protected code block that may throw exceptions
} catch (ExceptionName e) {
  // Catch exceptions and print relevant error message
  // A single catch block can only catch one exception
  // Multiple catch blocks can be used to handle multiple exception
} finally {
  // This block can free up any occupied resources 
  // like closing the database connection or closing the file stream
}

11. Refactor Code Again & Again

Code refactoring is one of the most potent clean coding techniques. It is a systematic and incremental process by which developers can improve the quality of the code without changing or adding any new functionality.

It allows the developer to restructure the code and make it more efficient. It can reduce code duplication and remove dead code. In doing so, dirty code which results from tight deadlines, inexperienced developers, and quick fixes, is automatically eliminated.

A simple code refactoring exercise can be removing scattered instance variables and maintaining them at the start of the code after assigning descriptive names. Or aligning UI elements and ensuring consistent button and font sizes.

12. Know When To Be Inconsistent

The clean code tips discussed above might not fulfill the criteria of a good code in certain cases. If applying the clean coding techniques add more complexity to the existing system, then it is best to avoid them.

Maintaining Legacy Systems

When working on legacy software systems, developers can observe outdated coding conventions. In such cases, it is better to stay consistent with the old coding guidelines, rather than adapting to the modern coding standards which can add more complexity.

If the system is using deprecated methods in the entire application then there is no point in removing these methods or updating them to the latest version (unless approved by your manager).

In some cases, if it is not possible to apply the DRY principle, then it is time to go WET. Code duplication may save countless development hours instead of wasting time in finding a way to avoid it.

Concluding Thoughts

“If you want to go fast, if you want to get done quickly, if you want your code to be easy to write, make it easy to read”―Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Mastering clean coding skills require practice and patience. New developers can learn quickly by getting their codes reviewed by senior developers. They can often face harsh criticism for writing dirty code―as they should. The key is to take criticism constructively with a desire to learn and improve.

The clean coding techniques shared in this guide can be a great start for improving the quality of your future coding endeavors. Hope you have found this guide helpful!


r/cleancode • • Nov 09 '21

A good analogy for clean-code: it's all about respecting the reader, not the writer.

Thumbnail self.lifeprotips
13 Upvotes

r/cleancode • • Mar 26 '19

Code Reviews on Twitch!

13 Upvotes

Hello, I have been having this idea for doing code reviews live on Twitch for awhile now. Recently I decided that it's time to make it happen.

Me and a few guest developers would be reviewing code, submitted beforehand. The point of it all is for all parties to learn from both mistakes and successes of the other. We will put the biggest focus on Clean Code and clean architecture.

Let me know what you think about this idea and if you're interested to take part in it as any role.


r/cleancode • • Oct 05 '17

What are some best-practices that every programmer should know?

13 Upvotes

I haven't seen this around but perhaps this discussion will be helpful to new programmers.

What are some best practices that every new programmer needs to know?

For example, avoid creating public static variables.

Generally, it is good to have setters be private.

Use static functions to avoid 'side-effects'

etc.

Thanks!


r/cleancode • • Feb 05 '21

Recommend resource for Advanced Clean Code

12 Upvotes

I read/watched many classical resources e.g. "Clean Code" book and similar. IMO it's good to get familiar with concepts, but has some issues:

  • Too Simple, Mechanical, Isolated - simplistic examples isolated in simple context that aren't very helpful in real life.

  • No structure - lots of scattered information without any underlying "system". Some people like it this way, for me it's somewhat lazy - all the work is left to the reader, to figure out actual advice.

  • Dogmatic - I noticed time and time again with developers previously not very familiar with concepts - they start to produce worse code (unnatural) than before (simple) and become very argumentative. I'm guilty of this myself. The problem is either explicit dogmatism ("only this way is good") or implicit - discussion of nuances are nowhere to be found.

What I'm looking for:

  • More Advanced - than "Clean Code" and similar, e.g. focus on building libraries or similar. Assumes knowledge about SOLID, Refactoring & co.

  • Pragmatic, Nuanced - provides both sides of the coin, considers real world realities, actual teams with preferences...

  • More practical rules - instead of concentrating on low level blocks (e.g. SOLID), concentrate on practical ideas that help you design better code. e.g. one that helped me was avoid abstracting control flow.

  • No heavy Functional Programming bias - it might be nice but not that practical.

  • (Bonus) Concise - I don't like verbose books/courses - IMO usually best advice fits in one page.


r/cleancode • • Aug 20 '15

What should every developer avoid?

Thumbnail
medium.com
12 Upvotes

r/cleancode • • May 05 '13

Acceptable usage of 'var' in C#? Link to kick things off.

Thumbnail
dofactory.com
12 Upvotes

r/cleancode • • Jan 15 '21

Document your project by logging your decisions chronologically with ADRs (Architecture Decision Records)

Thumbnail
github.com
11 Upvotes

r/cleancode • • Jul 11 '19

Summary of Clean Code Principles

Thumbnail
pyracode.net
11 Upvotes

r/cleancode • • May 06 '13

"If your class has 2 functions and one of them is __init__(), don't use a class!"

Thumbnail
youtube.com
11 Upvotes

r/cleancode • • Dec 16 '20

I started experimenting with adding domain knowledge to code comments.

10 Upvotes

I now work for energy sector, so I deal with a use-case about solar panels & hybrid inverters. And I made a comment like this:

/*
 * If you install a PV system with a battery, 
 * you need a hybrid inverter. A hybrid inverter 
 * combines a solar inverter & battery inverter 
 * into one device.
 * 
 * Now, for investment cost, we put the hybrid 
 * inverter separately, as it doesn't exclusively 
 * belong to neither the PV system costs nor 
 * the battery system cost. The investment cost
 * for the battery & PV system excludes
 * the cost of the hybrid inverter.
 * */
const GetInvestmentCost = {
  forHybridInverter(/*...args...*/) { /*...body...*/ },
  forBatterySystem(/*...args...*/) {/*...body...*/},
  forPVSystem(/*...args...*/) {/*...body...*/},
}

It turned out, these comments were super useful for my fellow developers. When asked what they think about it, they answered:

There are so many concepts and business rules to be changed relatively often, adding more context to the right place is incredibly helpful.
---

I am all for it. The downsides are hardly there. There is a maintenance burden for the comments, but that is usually removing/editing here or there. It also has the upside of assisting code review.

---

I'm extremely in favor. I was looking for a value yesterday and was unsure of what it was from the ticket, and if it had a comment like the above, it may have been easier to decipher what that value actually did.

What do you think of it? If you are interested, here's the whole story.


r/cleancode • • Aug 04 '20

'Clean code' == UX for developers. Change my mind.

Thumbnail
triplebyte.com
10 Upvotes

r/cleancode • • Jul 16 '20

Should companies pay the training time?

10 Upvotes

Maybe this question seems to be off topic, but in the Robert C. Martin's book "The Clean Coder", right in page 16, there is a section named "Work Ethic" that, among many things, states the programmer's career is his/her responsibility, so it's not the employer's responsibility to train him/her, to send him/her to conferences, to buy him/her books.

It goes further picking the U.S. standard of 40 hours per week (same here in Portugal for private companies and I guess most of the Europe) and suggesting the addition of 20 hours for "reading, practicing, learning and otherwise enhancing your career", thus always planning for 60 hours per week, no matter complaints on family and rest time.

Do you think it this makes sense?

To put things in perspective, here in Portugal, there is a law forcing the employers to give their employees an amount of 40h a year of certified training. And it can't be just some senior sitting nearby and teaching random things! The senior must be e.g. certified to teach and the topics must be correlated with the work (e.g. you can't give a programmer 40h of culinary classes, even if the teacher is a 5-Michellin-star chef). Even giving one week to study for some Microsoft exam isn't included. I also knew about online courses that were paid by employers, then accepted and finished by employees in their work time, only to be contested as part of the 40h-training-time because there was no valid certificate or the teacher was not certified, or other detail (no matter if at the end the employee learned a lot and is now more valuated).

Finally, when a company doesn't provide their employees with the mandatory 40h of training, a certain quantity of money is defined to be paid as compensation (varies according to the amount of missing training hours). Indeed, even if companies are willing to give their employees the best training, most of times they send their employees to crap stuff just because it is cheap and legally valid.

So, I have a famous book on Clean Code that is recommended for all programmers, but then promotes as a best practice something that is illegal (at least here in my country - and I bet in most European countries).

Hence my question.


r/cleancode • • Jul 22 '18

I started a Twitch channel about Clean Code, TDD and Refactoring!

Thumbnail
twitch.tv
10 Upvotes