Wednesday, October 05, 2005
Spaghetti Code
最近在看Big Ball of Mud
想到之前在Java 2005有去聽介紹AntiPattern的場次
故在此整理一下之前聽到有關Spaghetti Code的資料
何謂AntiPatterns?
- AntiPatterns are Negative Solutions that present more problems than they address
- AntiPatterns are a natural extension to design patterns
- AntiPatterns bridge the gap between architectural concepts and real-world implementations
- Understanding AntiPatterns provides the knowledge to prevent or recover from them
Spaghetti Code–雜亂無章的程式碼 (Development AntiPattern)
Definition: Spaghetti code an undocumented piece of software source code that cannot be extended or modified without extreme difficulty due to its convoluted structureSymptoms
- Quick demonstration code that became operational
- "Lone Ranger" programmer (who was that masked man?)
- Obsolete or scanty documentation
- 50% of maintence spent on system rediscovery
- Hesitant Programmer Syndrome
- More likely to break it than extend it
- Easier to just rewrite it
- Cannot be reused
- System software and COTS packages can't be upgraded
- Performance cannot optimized
- User work around
Object-Oriented Spaghetti Code –非物件導向Code
- Many object methods with no parameters
- Suspicious class or global variables
- intertwined and unforeseen relationships between objects
- Process-oriented methods, objects with process-oriented names
- OO advantage lost - inheritance cannot be used to extend the system, polymorphism not effective either
Refactored Solution
- Refactor to generalize: Create an abstract superclass
- Make subclass function signatures compatible
- Add function signatures to the superclass
- Make function bodies and variables compatible
- Mirgate common code to the superclass
- Refactor to specialize: Simplify conditionals
- For each condition, create a subclass with matching invariant
- Copy the code into the subclass
- Simplify code based upon invariant
- Specialize the superclass constructor
- Refactor to combine: Capture aggregations and components
- Type A: Move members from an aggregate class to a components class
- Type B: Move members from component classes to aggregate class
- Type C: Convert inheritance into an aggregation
Strategy: Reform the software process
- Refactoring as you program
- incremental development
- Refactoring to improve structure
- Incremental test
- Iterate
- Use programming discipline
- Keep track of defects (metrics)
- Learn to avoid programming defects
- Use Architecture-Centered development
- Define enforceable system boundaried
- Use design patterns to document software