Bad Smells in Code
Dr. Kevan Buckley6CS002, Dr K Buckley 2
Lecture Outcomes
• To be familiar with Bad Smells
– Indicators that your code is structured poorly
• By the end of this session you should be able to
start
...
Bad Smells in Code
Dr. Kevan Buckley6CS002, Dr K Buckley 2
Lecture Outcomes
• To be familiar with Bad Smells
– Indicators that your code is structured poorly
• By the end of this session you should be able to
start evaluating code with respect to bad
smells.6CS002, Dr K Buckley 3
References
• The material presented here is covered in:
– Refactoring: Improving the Design of Existing Code by Martin
Fowler.
• Available from Safari and in the Harrison Library
• Concentrate on pages 75 to 88 (http://www.laputan.org/pub/patterns/fowler/smells.pdf)
• See http://sourcemaking.com/refactoring/bad-smells-in-code
• An alternative perspective is presented in:
– Clean Code: A Handbook for Agile Software Craftsmanship by
Robert C. Martin
• Some useful additions, but a lot that is out of the scope of our work
• Try to use Fowler as the primary reference, but if there
are things that you do not understand try reading the
alternative book.6CS002, Dr K Buckley
Bad Smells in Code
• Smells are the symptoms of bad code
• Fowler (1999) provides a catalogue of smells and
refactorings
– When you identify a smell, you select one of the suggested
refactorings then carefully follow a step by step process to
safely refactor the code.
• Code should be self-documenting
– There should be no need for comments
– If you can't understand it there are probably bad smells
• See the following for a summary
– http://wiki.java.net/bin/view/People/SmellsToRefactorings
• See the following for Fowler's catalogue
– http://www.refactoring.com/catalog/index.html6CS002, Dr K Buckley
Bad Smells in Code
• Duplicate code
– Results from "cut and paste" coding or poor design
– Common code can be put into methods that can be called from many
places.
– Breaks the DRY principle
• Long method
– The longer a method is, the more difficult it is to understand.
– Short methods with good names improve readability.
– Methods may be reusable elsewhere in the program
– Poor cohesion breaks SRP
• (you can apply these principals to structured programming)
• Large class
– When a class is trying to do too much it can have too many instance
variables and is susceptible to duplication and confusion.
• e.g. a complex GUI application could be split into separate classes for the
data and behaviour (see http://java.sun.com/blueprints/patterns/MVC.html)
– Poor cohesion breaks SRP6CS002, Dr K Buckley
Bad Smells in Code
• Long parameter list
– Hard to understand (and remember) lots of parameters
– Often better to pass a small number of objects
– Indication that a metho
[Show More]