Stepwise Refinement - AP Computer Science

Download Report

Transcript Stepwise Refinement - AP Computer Science

Ch.3
Classes & Stepwise Refinement
STEP 1 Define a new class of robot (see next slide)
When designing a new class (whether that’s
robots, cars, bank accounts, etc.), the first question we are
asking ourselves is “What can I steal?” !! In other words,
one big benefit of OOD is the concept of code-reuse. There
is no need to reinvent the wheel.
(by the way, that doesn’t mean to copy your friend’s lab!! )
1
Ch. 3
import kareltherobot.*; subclass
superclass
public class MileWalker extends UrRobot
{
constructor
public MileWalker (int st, int av, Direction dir, int beeps) {
super(st, av, dir, beeps);
invokes superclass’ constructor
}
public void moveMile( ) {
move(); move(); move(); move();
move(); move(); move(); move();
}
note: no object names preceding methods
(why not?) - let’s look at client code to see
}
why
2
INHERITANCE
Ch. 3
Inserting MileWalker into the
Inheritance Hierarchy
UrRobot
If you have an
object (say, bob) of
type MileWalker,
what methods are
available to bob?
move()
turnLeft()
pickBeeper()
putBeeper()
What if bob were of
type UrRobot?
turnOff()
MileWalker
moveMile()
the is-A relationship
a MileWalker is-A UrRobot
3
Ch. 3
STEP 2
write application(client) to use new class(server)
(a.k.a. a driver)
import kareltherobot.*;
public class MileWalkerDriver implements Directions
{
public static void main(String args[]) {
MileWalker bob = new MileWalker(2, 1, East, 0);
bob.moveMile(); // new instruction
bob. move();
// inherited instruction
bob.turnOff();
// inherited instruction
}
}
Ch. 3
4
Misc. Note
(don’t sweat this – it’s not computer science)
• These 4 method invokations may be necessary and
may be placed first within the main() of the driver
–
–
–
–
World.reset();
World.readWorld(“c:\\first.kwld");
World.setDelay(50);
World.setVisible(true);
– Alternatively: you can place them in a static block (no
need to understand what a “static block” is) within your
driver class
5
Ch. 3
STEP 3
• Put each class in its own file making sure that
the file name matches the class name Exactly
(convention: class names begin with a capital
letter, method names begin with a lowercase
letter – if an identifier combines several words,
use the “interCap” technique. We will follow
convention.)
• We’ll now demo the whole process in BlueJ
6
Ch. 3
Now You Try!
• we want a BetterTurnerRobot class
– turnRight, turnAround, stepBackward
7
Ch. 3
Now, try something a bit more!
1. Design an HBot class on paper right now (yes, it should
do the same thing as our non-class version in Ch.2)
–
–
In 10 minutes, we’ll pass the wireless keyboard & mouse and
we’ll build/test the class together
In addition, where does it go in the Inheritance Hierarchy?
2. Why is putting all the same code into one method within a
class (encapsulation) better than just leaving it in the
driver – i.e., what do we gain?
(let’s informally discuss before I give you the fancy cs language)
8
Ch. 3
Benefits of Encapsulation
• So, we just learned that encapsulation promotes Code
Reuse. By putting the code into a method, we no longer
need to write that code again. In addition, from the client’s
point of view, she is no longer concerned with how to draw
the H – she’s the beneficiary of a concept called Abstraction
(can focus on WHAT, not HOW).
• In general, if you find yourself doing a cut-and-paste, then
there is a better way to do things – i.e., use procedural
abstraction and abstract out the common code, putting it
into a method
• In that light, how should we now modify our
9
current 1-method(if that’s how
you
wrote
it)
HBot?
Ch. 3
Improving HBot
• Yep, find the common code and create other methods.
– drawLine() and turnRight() might be what you choose –
you might choose others depending on how you see the problem
being decomposed (stepwise refined)
– Should they have public or private visibility?
• That depends on whether we believe a client would be calling
drawLine() and turnRight() – let’s discuss public/private, then
you guess/justify
• I’ll argue, No. I’ll argue like this: the name of the class is HBot
– so I (the client) am trying to have some object draw H’s for
me – how that object gets it done is of no concern of
mine(abstraction) – so I don’t need (and shouldn’t be allowed)
to see the other helper/auxiliary methods. Therefore, they
should be private, helper-like methods for the class’ use only.
10
Ch. 3
Stepwise Refinement
• technique for writing modules which are concise, correct,
easy to read/modify/understand
– Would a general contractor just start building a house – or would
she break up the task into foundation, frame, electrical,
plumbing, etc.? Makes sense, doesn’t it. Explain why from the
contractor’s view – use our cs terms we’ve been learning.
• write main task first, breaking up the BIG task into smaller
tasks (using methods) – then take each method one at a
time and also break it up --- continue until each method is
compact and singular in focus (cohesion)
• Look back at what we just did – do you see this
re-factoring?
11
Ch. 3
Practicing Stepwise Refinement
• Let’s write a class called DiamondPlanter together using
stepwise refinement. It’s like Harvester except the field is
diamond shaped. There are always 4 beepers on a diagonal.
Assume the robot is facing North to begin, has 16 beepers,
and is standing on the corner where the bottom of the
diamond is to be.
– What are we asking ourselves first?
– Now, using some sort of pseudocode, write the top level
method(call it, plantDiamond() ). While writing it, pretend
any helper methods you’d like to use already exist (abstraction)
and work already (automagically, if you will). After we
pseudocode plantDiamond(), we’ll take each helper method
in turn and repeat this stepwise-refinement process until we have
12
cohesion.
Ch. 3
Debriefing DiamondPlanter
• So, we wrote DiamondPlanter. More than likely
we wrote a turnRight() and maybe even a
turnAround() to help us plant. Anyone want
to make any comments about that?
• I don’t know about you, but I found it
ANNOYING to write the same thing again! Let’s
look at the Inheritance Hierarchy and see if we can
come up with a solution. Let’s discuss possible
solutions before going on…
13
Ch. 3
Improving overall object design
turnRight()
Discuss what our
modifications would
be to the HBot and
DiamondPlanter
classes
turnAround()
– in terms of syntax
UrRobot
BetterTurnerBot
HBot
DiamondPlanter
- in terms of
concepts we’ve been
discussing
14
Ch. 3
Now YOU try! But be efficient!
design a robot class that would be conducive to
solving the following diagrammed situation (robot
should climb and pick up all beepers – always 3/stair)
also, different clients need to be able to climb different
numbers of stairs:
starts
off
facing
East
When designing, keep
in mind everything
we’ve been discussing.
15
Ch. 3
Why create a Class?
• Why reinvent the wheel? You’re allowed to be lazy
in my class – but you have to be smart to be lazy!
• Code Reuse
• Abstraction – free your mind from the irrelevant and
work on the relevant!
– Ex. If I’m going to write a system to have a bot climb
stairs in several buildings, I’m going to use the
StairClimber class so I can call climbStair() – I can work
on a bigger/better/harder problem and free my mind from
the irrelevant details of taking a step and picking beepers
16
Ch. 3
Why use Inheritance?
• You get stuff for free! You can be lazy! (cs term?)
• Use things without knowing/caring how they work!
(cs term?)
• Why reinvent the wheel! (cs term?)
• Localize changes to one class/method (localization)
UrRobot
BetterTurner
StairClimber
MileWalker
Harvester
DiamondPlanter
17
Ch. 3
Sample Inheritance Questions
How many times does each Bot below move?
public class MysteryBot1 extends
UrRobot {
}
public class MysteryBot2 extends
MysteryBot1 {
/* constructor not shown */
/* constructor not shown */
public void step1()
{ move(); }
public void step1()
{ move(); }
public void move()
{
super.move();
super.move();
}
public void move()
{
super.move();
super.move();
}
}
MysteryBot1 john = new RobotStuff(10, 10 , North, 0);
john.step1(); // where is the bot now?
john = new MoreRobotStuff(10, 10 , North, 0);
john.step1(); // where are both bots now?
Ch. 3
18
Another Inheritance Question
Give the state (location and Direction) of each Bot below?
public class ABetterBot
extends UrRobot {
public class AnEvenBetterBot
extends ABetterBot {
/* constructor not shown */
/* constructor not shown */
public void step1()
{ move();
super.step1();
step2();
}
public void step1()
{ move(); }
public void step2()
{
turnLeft(); }
public void step2()
{
turnLeft();
super.step2();
}
}
} 10 , North, 0);
ABetterBot ucla = new ABetterBot(10,
ucla.step1();
AnEvenBetterBot usc = new AnEvenBetterBot(10, 10 , North, 0);
usc.step1();
19
Ch. 3
A final Inheritance Question
Give the state (location and Direction) of each Bot below?
public class TestBot extends
UrRobot {
public class HarderTestBot extends
TestBot {
/* constructor not shown */
/* constructor not shown */
public void step1()
{ move();
step2(); }
public void step1()
{ move();
super.step1(); }
public void step2()
{
turnLeft();
}
public void step2()
{
turnLeft();
super.step2();
}
}
}
TestBot ucla = new TestBot(10, 10 , North, 0);
ucla.step1();
HarderTestBot usc = new HarderTestBot(10, 10 , North, 0);
usc.step1();
20
Ch. 3
Is-A questions
• “A” is-a Letter
• Letter is-a Symbol
• Semicolon is-a
PunctuationMark
• “@’ is-a Symbol
• PunctuationMark is-a
Symbol
• The classes that are
inherited (either directly or
indirectly) by:
–
–
–
–
–
–
PunctuationMark
“A”
Semicolon
Symbol
“@”
Letter
21
Ch. 3