Clean Code: A Handbook of Agile Software Craftsmanship

Author: Robert C. Martin
All Stack Overflow 184
This Year Reddit 166
This Month Reddit 11

About This Book

Even bad code can function. 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 be that way.

Noted software expert Robert C. Martin presents a revolutionary paradigm with Clean Code: A Handbook of Agile Software Craftsmanship . Martin has teamed up with his colleagues from Object Mentor to distill their best agile practice of cleaning code "on the fly" into a book that will instill within you the values of a software craftsman and make you a better programmer--but only if you work at it.

What kind of work will you be doing? You'll be reading code--lots of code. And you will be challenged to think about what's right about that code, and what's wrong with it. More importantly, you will be challenged to reassess your professional values and your commitment to your craft.

Clean Code is divided into three parts. The first describes the principles, patterns, and practices of writing clean code. The second part consists of several case studies of increasing complexity. Each case study is an exercise in cleaning up code--of transforming a code base that has some problems into one that is sound and efficient. The third part is the payoff: a single chapter containing a list of heuristics and "smells" gathered while creating the case studies. The result is a knowledge base that describes the way we think when we write, read, and clean code.

Readers will come away from this book understanding

  • How to tell the difference between good and bad code
  • How to write good code and how to transform bad code into good code
  • How to create good names, good functions, good objects, and good classes
  • How to format code for maximum readability
  • How to implement complete error handling without obscuring code logic
  • How to unit test and practice test-driven development

This book is a must for any developer, software engineer, project manager, team lead, or systems analyst with an interest in producing better code.


by tschellenbach   2019-07-12
This book is a great read for writing maintainable code:
by raiflip   2019-07-12
Another few books I've found incredibly helpful: Clean Code: Clean Architecture: Domain Driven Design:
by CodeSheikh   2019-01-20
Nice list. Appreciate it. But I see there are a few amazing software books missing from the list such as:

- Clean Code (by "Uncle Bob")) []

- Design Patterns (by "Gang of 4") []

- Introduction to Algorithms (by "CLRS") []

by anonymous   2019-01-13

In addition to "effective java" (as mentioned in another answer), another classic book also suggests:

Prefer static factory methods (with names that describe the arguments) to overloaded constructors.

Eg. don't write

Complex complex = new Complex(23.0);

but instead write

Complex complex = Complex.fromRealNumber(23.0);

The book goes as far as to suggest making the Complex(float) constructor private, to force the user to call the static factory method.

by anonymous   2019-01-13

First, you're right to be concerned. You definitely don't want your classes to assume responsibilities which are outside of their primary function. Your classes should each have a specific, and limited in scope, purpose. I would recommend reading Uncle Bob's Clean Code for a great discussion on this.

To your question: I assume you are currently receiving user-actions on QButtons, QLineEdits, etc, by connecting their various signals to your own slots (see Qt Signals and Slots). What you may be missing is that you are not limited to connecting a given signal to just a single slot - you can connect them to multiple slots, across multiple classes.

So, if you have two classes, one UI related and one for data collecting, which both need to receive the click of a button, just connect the click to both slots. Make your data collecting class inherit QObject so that it has the signal/slots mechanism.

As an example, here's a mock-up of the image (borrowed from the Qt link above). I added the signal drawn in red:

enter image description here

by anonymous   2019-01-13

Try to follow SOLID principles, from your code focus on Dependency Inversion Principle: Try to depend on abstractions (for example interface Database) and not your current implementation of Database.

I suppose that you should have some enums as unit type for Unit, I suppose you have different kind of Units. I suppose Unit should be abstract or even an interface because always you should have an specific unit (soldier, tank, ...), each kind of Unit should implement some kind of interface with actions (methods) as move, attack. Is not the same to move a soldier than to move a tank. as other configuration values that you will have I would use a file

Do not forget to test, TDD will do your classes easier to test and you will understand what you want to do before than implementing It.

Use some Control Version and commit/push with useful comments, will be easier to see why you have done some changes, in some days you will not remember why you have written these lines.

I recommend you to read and check in the following order the books: Effective Java and Clean Code

by anonymous   2019-01-13

The five principles of Object Oriented Design come from developer and author Robert C. Martin (Uncle Bob). He originally made a list of eleven principles, but the first five five were later turned into the acronym SOLID by Michael Feathers.

However, the four principles you listed above are generally used in an academic setting. They are very simple concepts for student developers to grasp, and they cover some of the most important principles at a very basic level.

You can read more about Uncle Bob's thoughts on SOLID principles here.

He's a great author, and I recommend his books. My favorite is Clean Code. Hope this helps clear things up :)

by anonymous   2019-01-13

It is fairly straightforward. Define your response structure using composition of classes. It is unfortunate to use capitalised fields in JSON, which out-of-the-box requires capitalised field names in the Java DTO. Still those can be easily mapped to conventional low-case names either by using the ACCEPT_CASE_INSENSITIVE_PROPERTIES modifier on the ObjectMapper or by annotating fields with corresponding names. I prefer a property on the ObjectMapper as it keeps the DTO independent of the serialisation code and this technique is used in the test below (the test is green):

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestDeserialization50386188 {

    public static class Response {

        public static class ResponseDataType {
            public String name;
            public String siteId;
            public String type;
            public long x;
            public long y;

        public int statusCode;
        public String message;
        public long executionTime;
        public List<ResponseDataType> ResponseData = new ArrayList<>();

    private static final String data = "{\"StatusCode\":0,\"Message\":null,\"ExecutionTime\":0,\"ResponseData\":[{\"Name\":\"name1\",\"SiteId\":\"1234\",\"Type\":\"Type1\",\"X\":\"1234567\",\"Y\":\"123456\"},{\"Name\":\"Name2\",\"SiteId\":\"2134\",\"Type\":\"Type2\",\"X\":\"1234567\",\"Y\":\"1234567\"},{\"Name\":\"Name3\",\"SiteId\":\"3241\",\"Type\":\"Type3\",\"X\":\"1234567\",\"Y\":\"1234567\"},{\"Name\":\"Name4\",\"SiteId\":\"4123\",\"Type\":\"Type4\",\"X\":\"123456\",\"Y\":\"123456\"}]}";

    public void deserialize_response_withJackson_ok() throws IOException {
        ObjectMapper mapper = new ObjectMapper()
          .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

        Response response = mapper.readValue(data, Response.class);

        assertEquals(4, response.ResponseData.size());
        assertEquals(1234567, response.ResponseData.get(2).x);
        assertEquals(1234567, response.ResponseData.get(2).y);

You fill find the project with the executable test on this dedicated GitHub repo.

The "Clean Code" book by Uncle Bob does not really recommend the overuse of getters and setters so common in Java for DTOs, which a Response class is. Still you can replace all public fields with getter/setter pairs if you like but the clarity will suffer with no obvious gain on quality.

by anonymous   2019-01-13

I agree that this "special case" discussion, in the Define Normal Flow section of the Error Handling chapter of Martin's excellent Clean Code, is a bit unswifty.

As you point out, part of Martin's rationale is to excise the repeated use of Java's "awkward" (his words, not mine) try-catch pattern, especially if you're repeating it a lot. But in Swift, if there are no expenses, you would probably not pursue an error throwing pattern, but rather just return an optional. And, as you say, the Swift nil-coalescing pattern is comparably elegant to the try-catch pattern. (As an aside, Swift optionals renders irrelevant the next two sections in that chapter, too, Don't Return Null and Don't Pass Null.)

Robert Martin credits Martin Fowler in this discussion, but in Refactoring, Fowler discusses "special case" pattern in the context the challenges of null checks in Java and all the problems that entails. But Swift handles optionals so much more gracefully and it renders much of Fowler's defensive-null discussions moot.

So, I agree, that MealExpenses is not a particularly good candidate for the "special case" pattern in Swift. (Frankly, I'm not sure it's a great candidate in general, regardless.) Optionals would be a more natural Swift solution. Now, if I were littering my code with the identical nil coalescing pattern all over the place, I'd look for ways to avoid repeating it, but I wouldn't necessarily jump to introduce the "special case" pattern solely for this purpose.

It's worth noting that in Refactoring, Fowler offers an expanded "special case" example, where a landlord's "customer" for some random building might be "no customer" (e.g. the building is vacant), an "unknown customer" (you know that there is a tenant, but you don't know who it is), or a particular customer. This ternary state is one where we have to start to think beyond a simple Swift optional. But at that point we might use an enum with associated values, or you could conceivably use the "special case" pattern (but now needing to introduce a protocol). It depends upon particular situation. With all of that said, I've yet to encounter scenarios where I've felt inclined to add "special case" pattern in my Swift code.

by anonymous   2019-01-13

To quote the great uncle bob, author of 'Clean Code' and famed engineer, 'never let the readers of your code scroll sideways', and 'your code should read like well written prose'.

Instead of placing the if statement within the with block, why not separate them.

if src_name:
    with open(src_name, 'r') as f:
        pass #do something
    pass # do something else

Also, consider using better names for your variables, i.e. instead of src_name use file_path > makes more sense.

I highly recommend 'Clean Code' by Robert C. Martin - it changed my life.

by anonymous   2019-01-13

The short answer is no, not out of the box. There is an open source tool that will be able to do this in a future release

If you have a lengthy procedure you may what to ask yourself if it does more than one thing. As a general rule, a procedure should only do one thing. If you break up each separate "thing" into individual procedures, then you can call each procedure in a parent subroutine. A good book on this is "Clean Code: A Handbook of Agile Software Craftsmanship"

Sub ParentSub()
End Sub
by anonymous   2019-01-13

I don't know a pattern that would fit your description, but using Maps over entity classes also has disadvantages.

You can easily add any data to the map in the business logic layer before map gets passed to the presentation tier, and it becomes part of the form with only changes to the template itself.

What you see as an advantage means that you can never be sure in which state the Map is. If you load an entity through service 1 the map might contains some values. If you load the same entity through another service 2 it might not contains some values. The state of the Map is use case specific.

Since you are using a Map it also means that from a client's perspective each property has the same type, e.g. Map<String, Object>. So if you see an entity map in your code you also have to know which type it has. Without knowing that it would be hard e.g. to calculate an orders total.

As long as you are the only one that works on the code and you know all Map states you will think that it is flexible and fast. If you haven't worked on such code for some time you might forget the different states that the Map can have. You have then to go through the whole code for each use case to see if some piece of code adds or removes properties or just replaces the properties type.

So try to think of that design from a documentation perspective. The big advantage of a dedicated entity class is that it is named. You can give a class a name and therefore a meaning. E.g.

public class PlacedOrder { ... }
public class Refund { ... }

You can also easily add javadoc to the class to give a bit more detailed information of what this class means in your context. This is usually called the Ubiquitous Language. I often just use the term domain language, because it's easier to speak.

In my experience such design often lead to a hard to maintain system. At the beginning when the code base is small you are really fast. But this is not amazing, because you often save documentation time by not applying clean code principles.

Since types can't be checked by the compiler you will find type problems only at runtime. This means that you must create a big test harness, because the tests must also uncover the bugs that otherwise a compiler would report. Or you just develop the trial and error way, but this is not my way and does not satisfy me.

by anonymous   2019-01-13

It does not matter what coding language you use, the name of a function should be as informative as possible. A function name like onClick does not describe what the function does. If you want to call this function from another place the name onClick would not help you understand the purpose of the function. You would have to view the code to understand it.

It would be better to be more descriptive and call it something like this :

  1. sendPrivateMessage()
  2. clientAddress
  3. doSomething()

The name you choose depends on what this function does.

If you are interested in "clean code standards" I think this is the best book about clean coding and naming standards : clean code

by anonymous   2019-01-13

I think refactoring the expression to a function and giving it a good name would make it more elegant:

if (isValidOperator(operator_list) ) {
 // Do something

function isValidOperator(operator) {
  return operator == "=" || operator == "<>" || operator == ">" || operator == "<" || operator == ">=" || operator == "<=";

This way you explain to the readers of your code what it is meant to do. In a later stage someone can refactor the function to make it easier to understand.

Other reads:

  • Some other examples:
  • Clean Code book
by ducdetronquito   2019-01-13

I think you are good to go !

Last advice: even if you are not primarily a developer, try to read how to code well. For example, this book is gold: Clean Code: A Handbook of Agile Software Craftsmanship )

by whereisspacebar   2019-01-13
by Senipah   2019-01-13

Most language style guides are broadly similar so there are generally accepted standards for how and when to indent code. Generally speaking indentation is used to denote control flow blocks. Each nested block is indented.

So for example you would indent any time you have one of the following:

  • For...Next
  • If...Else...End If
  • While...Wend
  • With...End With
  • Select Case...Case...End Select
  • Function...End Function
  • Sub...End Sub

There is a VB6 style guide available.

>Because many programmers still use VGA displays, screen space should be conserved as much as possible while still allowing code formatting to reflect logic structure and nesting.

>Standard, tab-based, nested blocks should be indented four spaces (the default).

>The functional overview comment of a procedure should be indented one space. The highest level statements that follow the overview comment should be indented one tab, with each nested block indented an additional tab.

If you look at the style guides for most other languages they will generally give the same advice.

In certain languages, such as Python, it is particularly important to be familiar with this as correct indentation is used by the interpreter to run the code correctly (for example, there is no End If or End Function, the interpreter knows when the control block has ended by the change in indentation).

It may seem like a pedantic thing for me to have even brought up (and it may well have been) but when you are used to reading code to certain conventions it makes it significantly easier to parse a function at a glance.

Many would argue that vertical whitespace should be restricted to separating only blocks of related code but others (myself included) would argue further still that this should be a redundant argument as your code should follow the Single Responsibility Principle and thus if your function/method is doing more than one thing it should be broken down into constiuent function/methods anyway.

I highly recommend Code Complete and Clean Code for a more in-depth dissection of these principles.

by scarface74   2019-01-03
(None of these are affiliate links)

And just because it’s asked at every interview.

I’m focused on AWS these days, but a lot of these principals are universal.

by Yevon   2018-11-10

I recommend reading Clean Code if you haven't already.

Otherwise you need to be more specific about the question and how you solved it.