To teach the use of accessors and mutators for accessing an object's private data.
Motivation:
Students have difficulty remembering to use accessors and mutators (i.e.
getters and setters) to retrieve and modify an object's data. It is
useful to illustrate that to avoid doing so is dangerous to the object's
health, and hence to the application. The WDYEFB pedagogy provides a
somewhat graphic, physical metaphor that will clarify the proper use of
accessing methods and make students gulp when reminded of the
althernative.
Applicability:
Use the What Did You Eat For Breakfast pattern to reinforce the use of accessors and mutators.
Structure:
The instructor asks a student (named Greg for purposes of
illustration here), "Greg, what did you eat for breakfast?". Greg
answers, say "A bagel and coffee." The instructor points out that Greg's
public interface has been properly invoked, and Greg is induced to answer
in an acceptable format, while hiding his implementation.
The instructor then describes that the visceral alternative is
tipping Greg's head back, shoving one arm arm down his throat and
grabbing a piece of the bagel. That violates the privacy of Greg's data,
bypassing his public interface. (Note: while it may be more palatable
to some to slice the student's stomach open to determine its contents,
you don't want to kill the object.)
Obviously, it is equally hard for Greg to obtain or modify this
information without also using accessing methods.
Throughout the class, anytime a student attempts to bypass using
accessors and mutators, the insturctor need only remind them that they
are reaching down Greg's throat.
Consequences:
The WDYEFB pattern:
concretely emphasizes the private nature of an object's data
grosses students into using accessors and mutators
Implementation:
Issues to consider:
This pattern has only been used in classes whose students have
already demonstrated a sense of humor, however slight.
If groans and looks of disgust are the only responses, the instructor
may want to avoid reiterating it later, although the reminder is not
quite so graphic and may be more palatable.