#engineering #code #software #implementation
idea
The goal of producing clean code is to keep things simple, producing timely and adaptable code, producing dependable and yummy software[7]. This is done by making sure code is easy to read and understand, that it is logically sound. There are plenty of rules to help each of these, some of which are sometimes contradictory.
Clean code should be easy to read, leaving the reader or user with a clear understanding of what's happening, rather than having to dig one level deeper to understand ("one more thing to worry about")
Unit tests are useful on many levels with regards to code. They validate code and therefore, its function. They allow other people (including future-self) to change code with less stress. They force the writer to structure code in a way that is testable, which forces some logic in the code. They validate that the code is modular enough[3]. Test coverage can be checked using the "mutation testing" approach: change each line one by one and validate that a test breaks[8].
The SOLID principles are a set of principles
The onion architecture.
Separation of concerns
CUPID[11]:
Factorizing (i.e. putting similar code into the same function), and in particular DRY, is more complex than meets the eye: the coupling created by having a common piece of code serve two usages might be satisfying at first but create complexities down the road, that's especially true when the usages "look like" but are not identical at a conceptual level. Some advise to first duplicate the code, then group it if it gets reused[2].
Object calisthenics[1] are a set of rules aiming at code readability. They orbit around the concept of keeping things simple and small: one level of indentation, of object depth, small classes, and functions, encapsulation, etc. Decomposition into small bits also arguably makes it easier to delete code later[2].
Code smells are a set of indicators that something is wrong with the code[5]. An analysis[4] of when these are created in code indicates that they're usually appearing from the inception of the program, and are accentued under pressure. This highlights the importance of checking for these throughout the project, through automation and code reviews[6].
against clean code
There are detractors of Clean Code. One argument is saying that it is usually a useless cost. Another that the recommendations are not clean[10]. My take is that the main reason for writing quick & dirty code is when it doesn't require guaranteeing further modifications (either because working on disposable code, or through low ethics - "the next person will deal with it")
links
Conceptual integrity helps code cleanliness.
[6]: Code reviews are very useful to check for clean code and obtain cleaner code.
references
Code smells in Clean Code.
[1]: Jeff Bay / Object Calisthenicsref is a set of practices which help to write readable code invented by Jeff Bay of ThoughtWorks. (Also: William Durand / Object Calisthenics)
- Use only one level of indentation per
- Don't use
else - Wrap all primitives
- First class collections (Collections are their own classes)
- One dot per line (don't play with your toys' toys) (a.k.a Law of Demeter)
- Don't abbreviate
- Keep entities small (classes and methods)
- No classes with more than two instance variables
- No getters / no setters / no properties (logic of the class should be embedded in the class) - Related to OCP
[2]: Tef / Write code that is easy to delete, not easy to extend
[3]: Michael Feathers / Unit tests are tests of modularity
At the same time, it is harder to write tests as our units get larger. These two things make testing a good probe of design. When testing is painful, it’s worth looking at our modularity, or lack of modularity, and seeing what can be done to make it better. [...] Among all of the other things that unit tests are, they are also tests of modularity. If it’s difficult to write a test for a code change, your code could be more modular, and the modules should be relatively small. When they are, you can see the pieces by themselves; they are distinct, understandable, and they have behavior that is discoverable
[4]: Tufano, Palomba, Bavota, Oliveto, Di Penta, De Lucia, Poshyvanyk / When and Why Your Code Starts to Smell Badref
Summary for RQ1. Most of the smell instances are introduced when files are created. However, there are also cases, especially for Blob and Complex Class, where the smells manifest themselves after several changes performed on the file. In these cases, files that will become smelly exhibit specific trends for some quality metric values that are significantly different than those of clean files
[...]
Summary for RQ2. Smells are generally introduced by developers when enhancing existing features or implementing new ones. As expected, smells are generally introduced in the last month before issuing a deadline, while there is a considerable number of instances introduced in the first year from the project startup. Finally, developers that introduce smells are generally the owners of the file and they are more prone to introducing smells when they have higher workloads.
[...]
Lesson 1. Most of times code artifacts are affected by bad smells since their creation. This result contradicts the common wisdom that bad smells are generally due to a negative effect of software evolution. Also, this finding highlights that the introduction of most smells can simply be avoided by performing quality checks at commit time. In other words, instead of running smell detector time-to-time on the entire system, these tools could be used during commit activities (in particular circumstances, such as before issuing a release) to avoid or at least limit the introduction of bad code smells.
Lesson 2. Code artifacts becoming smelly as consequence of maintenance and evolution activities are characterized by peculiar metrics’ trends, different from those of clean artifacts. This is in agreement with previous findings on the historical evolution of code smells. Also, such results encourage the development of recommenders able of alerting software developers when changes applied to a code artifact result in worrisome metric trends, generally characterizing artifacts that will be affected by a smell.
Lesson 3. While implementing new features and enhancing existing ones are, as expected, the main activities during which developers tend to introduce smells, we found almost 400 cases in which refactoring operations introduced smells. This result is quite surprising, given that one of the goals behind refactoring is the removal of bad smells. This finding highlights the need for techniques and tools aimed at assessing the impact of refactoring operations on source code before their actual application (e.g., see the recent work by Chaparro et al.).
Lesson 4. Newcomers are not necessary responsible for introducing bad smalls, while developers with high workloads and release pressure are more prone to introducing smell instances. This result highlights that code inspection practices should be strengthened when developers are working underthese stressful conditions. These lessons learned represent the main input for our future research agenda on the topic, mainly focused on designing and developing a new generation of code quality-checkers, such as those described in Lesson 2
[5]: Code smells (See also Clean Code (Uncle Bob))
Haoda Wang / This is What Peak Hello World Looks Like is an example of whatever the opposite to KISS is
[7]: Butler Lampson / Hints and Principles for Computer System Designref discusses STEADY (goals) ART (techniques) and AID (process) {TODO: complete article}
[8]: Hernan Wilkinson / Mutation testing is an approach to validate that test coverage is sufficient: modify lines one by one, if test doesn't break then tests are not covering the "surviving mutant", and it needs to be killed. (i.e. improve coverage.)
[9]: Uncle Bob / REPL driven designref even Bob gets caught once in a while.
[10]: Qntm / It's probably time to stop recommending Clean Code :
[...] the major problem I have with Clean Code is that a lot of the example code in the book is just dreadful.