Let us code clean! January 17th, 2025
Clean coding is a concept that is constantly at the forefront of my mind on a daily basis while smashing keys and trying to change the world. How often have you gone out to create or update a method or function and realized very quickly there was an easy way to do it and there was a harder way to do it? And then how many of those times was the harder way the right way that creates clean code, and the easy way creates those smelly codes. This post will attempt to describe one of the most recent clean coding principles that I have run across, single responsibility principle (SRP). SRP is defined by Caltech as each module or class should only do one thing [a]. This often starts off as simple additions a line or two here and there to an existing methods until you eventually have a 300 line long method that originally started out as 15 longs line [b]. I can honestly say that this has happened to me more times than you would think. And I find it is easy to do this unless you are constantly of the mindset that you should write the code as a test driven approach. If I had to write a unit test for that method that was 300 lines long how complex or nearly impossible would it be to test every branch and every possibility? So text driven coding practices I believe really help to avoid these situations.
Another way to help aid in the trap of bloating out your methods is dependency injection. With dependency injection I can create an interface that has the method definitions, and then inject that interface into my classes and functions to perform the tasks that I need to do. For instance below we a simple code that I have written to show this. We create our dependency ILoveToLogStuff and inject it into the constructor of the LetsDoSomeWork class and assign it to the logger variable in our class. Now we can use that logger anywhere in the class! There’s no overhead of instantiating an instance of the logger class or anything. And if you want to change the logger now, you just change the simple logger and don’t have to refactor your working method! It’s really a great thing once you really start getting into dependency injection and it’s power.
Well that pretty well wraps up this iteration of Scripts of the Shire, and as Gandalf would say to some bad code smells “You shall not pass!”.
public class ILoveToLogStuff
{
public bool LogMe(string stuff)
{
// log some stuff
return true;
}
}
public class LetsDoSomeWork(ILoveToLogStuff logger)
{
public ILoveToLogStuff logger { get; } = logger;
public bool WorkWork(MoreWork work)
{
// Do some work on things
logger.LogMe(work.IDid);
}
}
Citations
[a] Caltech, “Clean code principles,” Caltech Professional Education. [Online]. Available: https://pg-p.ctme.caltech.edu/blog/coding/clean-code-principles. [Accessed: 16-Jan-2025].
[b] Refactoring Guru, “Code smells,” Refactoring Guru. [Online]. Available: https://refactoring.guru/refactoring/smells. [Accessed: 16-Jan-2025].
Read the post...