140 likes | 927 Views
Stepwise Refinement. A Method for Program Design. Stepwise Refinement. An approach to creating a program by decomposing the problem into simpler sub-problems Start with the main method Identify any required classes/services Write classes/services Identify "helper" services.
E N D
Stepwise Refinement A Method for Program Design
Stepwise Refinement • An approach to creating a program by decomposing the problem into simpler sub-problems • Start with the main method • Identify any required classes/services • Write classes/services • Identify "helper" services
Advantages to Stepwise Refinement • When using this method, the final program is: • Easy to understand • Easy to debug • Easy to modify
Sample Problem • Create a Robot that can “harvest” a field of Things: • The Robot will alwaysstart at the top-leftcorner • The Robot must pickup all Things in thegrid
Repeat 6x Planning Using Stepwise Refinement Create the Main Method: • What does the Harvester need to do to pick up a field of Things? • Harvest each row • How do you harvest an entire row? • Move West --> East, picking things • How would you do the entire field? • Harvest Row • Turn around • Move to beginning of row • Move South
Evaluate Plan • Advantages: • Entire field is harvested • Meets requirements • Disadvantages: • “Empty trips” when Harvester returns to the beginning of the row • Improvements? • At the end of a row, move South and harvest on the way back
Repeat 3x Modify Plan • Harvest Two Rows • Move South
Evaluate Plan • Advantages: • Entire field is harvested • Meets requirements • More efficient (less trips) • Disadvantages: • Only works when there is an even number of rows
Stub Implement Plan Using Stepwise Refinement • Create the harvestField ( ) command: public void harvestField ( ) { this.harvestTwoRows( ); this.positionForNextHarvest( ); this.harvestTwoRows( ); this.positionForNextHarvest( ); this.harvestTwoRows( ); this.positionForNextHarvest( ); }
Implement Plan Using Stepwise Refinement • Stubs included in the harvestField method indicate sections of code that require refinement • Each stub should be given an empty header in the program so that the class can be compiled and tested • Code is then created for empty stubs
Notice this method is protected Implement Plan Using Stepwise Refinement • Create the harvestTwoRows( ) command: protected void harvestTwoRows ( ) { this.harvestRow( ); this.positionForReturnTrip( ); this.harvestRow( ); }
Implement Plan Using Stepwise Refinement • This pattern is continued until all methods have been completed • Notice that the terminology remains the same throughout the class (harvest, position, etc.)