Thursday 14 May 2015

How Would I Change This?


Although as developers we don't like being asked to change the code we've written, you'll often hear things like
"That wasn't the original brief."
"Thats different to what was originally discussed."
The reality is that requirements are difficult to define and sometimes we get them wrong, this means good code has to be adaptable to change because at some point it will happen.
Personally when I'm evaluating a design I look to come up with the good answers to the following questions,
How can I limit the reasons for this code to change?
How can I make changing how this code behaves as straight forward as possible? 
If we accept at some point code will need to be changed how can we avoid a design that is like a ball of string that unravels when we pick it.
It turns out that the SOLID design principles can help with finding answers to these questions.
Single Responsibility Principle
If a class has a single responsibility it has a single reason to change, unless we have a need to change that aspect of the design then we won't have to revisit that class. 
If we do need to make a change the only knock on effects will be to classes that have a clear link to the functionality being changed, the need to change won't spread to other non-related areas of the code.
Open / Closed Principle
If a class is open for extension but closed for modification when we need to make a change we can do that by writing new code and not by having to modify code that already works and risk breaking other areas of the system.
Liskov Substitution Principle
The more complicated and opaque a hierarchy of classes we create the more it could come tumbling down when we need to make a change. If we change a super class that interferes with competing logic someone else has added to a sub-class chaos could ensue.
As an aside an even easier way to avoid this type of problem is to prefer composition over inheritance.
Interface Segregation Principle
Much like the SRP principle, limiting the scope of an interface limits its reason to change and consequently limits the reasons for change for all classes that depend on that interface. 
Dependency Inversion Principle
If we have code that depends only on abstractions we are shielded from all change that doesn't affect that abstraction, if we've also given ourselves a way to switch out these dependencies the scope of change can be predicated and limited.
As a believer in SOLID its not surprising that this is where I look for the answers but next time you write some code give some thought to how difficult a job it would be to change this later when your asked "We've looked at this again, how hard would it be too......".

No comments:

Post a Comment