Design Test 3 Comments
Summer 2001, CS 176 - Introduction to Computer Science II
Design
- Design in pieces.
- File open and close.
- Compute statistics.
- Read and count lines.
- Design down from the problem or up from the implementation.
- I recommend problem down - more focused.
- Why do this?
- Easier to do than one big design.
- Designs are easier to understand.
- The design process is important - it explains why.
Some Errors
- Incorrectly checking eof.
- Guessing before knocking.
- Misusing strings.
- String input is complicated.
- Multi-pass designs.
- Not incorrect but obviously inefficient.
- Little corners.
- Improper or missing initialization.
- Off-by-one errors.
- If it's important, it should be in the design.
- English is tough to use well.
Next it will check how many bytes are between each
newline. It
will check each line and determine
the largest and shortest line.
String I-O
- Reading strings is simpler than looping on newlines.
Replace
line_size = 0
while true
if (c = ins.get()) == EOF
break
line_size++
if c == newline
break
with
getline(ins, str)
if ins.eof()
line_size = -1
else
line_size = str.length()
Newlines and String Input
getline()
doesn't copy newlines.
- Counts are off by one.
- Easy to fix:
getline(ins, str)
if ins.eof()
line_size = -1
else
line_size = str.length() + 1
EOF and String Input
- What if there's no last newline?
-
getline()
reads anyway, sets an error.
- A bit harder to fix:
getline(ins, str)
line_size = str.length()
if ins.good()
line_size++
if ins.eof()
line_size = -1
good()
and EOF
-
good()
returns false for EOF.
- Missing newlines cause a format error.
- Don't know enough to deal with that.
- There's also the maximum string length too.
- Character arrays aren't any easier.
Morals
- Make sure you really understand C++ features.
- Not think you understand - really understand.
- First appearances are deceptive.
- Other examples
- some streams can't be seeked.
-
gcount()
doesn't work all the time.
- Make sure you're really making simplifications.
- Watch out for a succession of small fixes.
- Rule of thumb: if you can't get it right the first time,
it's not simple.
- Don't hesitate to scrap your improvements if called for.
This page last modified on 31 July 2001.