The podcast episode referenced in this blog post can be found here.
This podcast episode from CodingBlocks.NET discusses the SOLID design principles. I chose this episode because SOLID is a fairly early topic in the syllabus and appears to cover several important principles. The podcasters start by introducing SOLID as guidelines for well-designed code, defining “well-designed” as easy to change, easy to read, and easy to maintain. They suggest that you should usually code first and then refactor according to these design principles as the need arises, since following the principles can take a lot of work. Additionally, you probably can’t adhere to every single principle out there, so practicality comes first. Summarizing every principle discussed got long, so I’ll summarize the ones that affected me the most.
The Single-Responsibility Principle is fairly simple – it holds that a class should do one thing and do it well, i.e. objects should only have one reason to change. With this principle in mind, I will check my classes to see if I can think of two or more reasons I might need to modify them, and if I can, I’ll see if I can divide the responsibilities into multiple classes.
The Liskov Substitution Principle states that objects in a program should be replaceable with instances of their subtype. They talk about how making a square a subtype of a rectangle, while intuitive, would actually violate the Liskov Substitution Principle because of a square’s additional restrictions. You ought to be able to set a rectangle’s length and width to two different values, but this is impossible with a square. They conclude that if your subclass requires something a base class doesn’t, chances are you’ve violated this principle. This makes a lot of sense once spelled out, and in the future, I will make sure instances of my subclasses can be used whenever objects of the parent class are expected.
The Interface Segregation Principle holds that more specific interfaces are usually better than large, general interfaces. For instance, using a brake information interface where brakes are concerned would be more efficient than using an entire car interface. The podcasters say that according to this principle, if your interface requires a lot of methods in order to be implemented that often aren’t needed, your code smells. With this in mind, I will examine my interfaces for methods I’m not using most of the time and see if I can make smaller, more specific interfaces.
Additionally, the podcasters note that following the Single-Responsibility Principle and the Interface Segregation Principle make unit testing easier, so I’ll make sure to keep this in mind if I expect to do unit testing or pass my code on to a unit tester.
From the blog CS@Worcester – Fun in Function by funinfunction and used with permission of the author. All other rights reserved by the author.
