Stinky Duck – We’ve been doing some fantastic exercises centered around design smells. These are the seven primary design smells: ● Rigidity ● Fragility ● Immobility ● Viscosity ● Needless Complexity ● Needless Repetition ● Opacity I’m not going to waste your time giving you the definitions. Where’s the fun in that, do a little research and find out why your code may smell a little funky. But I do want to talk about ducks. Not just any ducks, stinky ducks. Some of the exercises we’ve been doing have been centered around “The Duck Simulator”. What does a duck do? Well that depends on the duck, right? Mallard Ducks can fly, swim, and quack. But a Decoy Duck does not fly, does not quack, and does not swim. Though Decoy Duck can float. How do ducks relate to Object Oriented Programming? Let’s imagine a Duck as a JAVA class. In our first pass of designing a duck we made a Duck super class with sub-classes of each type of duck. What’s wrong with having a duck super-class and sub-classes for each type of duck? Look back at the seven smells. can you see it? What’s going to happen when we start adding more duck types? We’ll end up with a lot of repetitive code. What’s the quickest way to reduce repetitive code? What about using inheritance? Inheritance will help but now we’re overriding a bunch of methods for the different duck types. Decoy duck doesn’t need a quack method. We would have to override the quack method. In fact for every duck type we would have to override methods that are inherited from the super-class. You know, because they are inherited. We could look at our super class (Duck) and see where we can improve the code. Well look at that, all the duck types have something in common. They exhibit specific behaviors. They fly (or not) and quack (or not). We can take these behaviors and create interfaces. Our goal should be to make the super class fixed but extensible. Now if we keep adding new types of ducks (Ghost ducks and Rocket Ducks anyone?) we will be able to identify additional areas for clean up. See, our simple Duck went from a slight smell to a real funk quickly. The design smells can be reduced to a manageable level by following the prinicples of clean code. We’ll talk more about design smells and clean code next week. #CS@Worcester #CS343
From the blog Home | Michael Duquette by Michael Duquette and used with permission of the author. All other rights reserved by the author.