Welcome to Part 4 of this review of the Pluralsight course Clean Code: Writing Code for Humans by Cory House.
Cory is a Microsoft MVP in C#, founder of OutlierDeveloper.com, avid tech reader, and speaker. He believes in clean code, pragmatic development, and responsive native UIs.
Here are the links to each part in this series:
Part 1 – Writing Code For Humans
Part 2 – Clean Code Principles
Part 4 – Clean Code Conditionals
In this episode, we reflect on our conditional logic.
“Which would you say in real life? If logged in equals true? Or if logged in?”
I don’t know about you, but this clip is making me hungry.
It’s also a reminder on how you can simplify your boolean assignments and increase your signal to noise ratio.
This is another good example of the power of reading out code in English. The redundancy jumps out at you, prompting you to eliminate it.
Don’t be anti-negative! Just the name “anti-negative” sounds strange – why not just say “positive”? Why not write conditionals positive?
The ternary operator is another opportunity to increase our signal to noise ratio.
Cory discusses the balance you should strike with the use of the ternary operator: not too much and not too little.
I love this name “Stringly” Typed. Sounds like Strongly Typed, but then wait, it’s NOT Strongly Typed.
Strongly Typed beats Stringly Typed, Cory gives four very good reasons why it is better to use an Enum.
Avoid magic numbers because they make the intent of your code much harder to understand.
Another code smell here. Cory describes some techniques for refactoring the smell away:
- Intermediate Variables
- Encapsulate complex conditionals in a well named method
Although it is usually better to write less rather than more code, the example that Cory gives for encapsulating complex conditionals shows that there are times when it is necessary to write some additional code to clarify intent.
Polymorphism vs Enums
Here we see a dirty switch statement and a cleaner solution using the Template Method pattern.
We see some of the benefits of learning LINQ here.
Something I either completely missed or forgot the first time I watched this course is Cory lists LINQ like implementations available languages other than C#:
- Java: LambdaJ (Java 8+ has it’s own implementation of Lamdas so I guess LambdaJ is obsolete now)
- Python: Pynq
Table Driven Methods
Here we see an example of dirty code that would be much more suited to existing in a database table.