Question

Code Complete (2nd ed.) says:

"If you pass a parameter to a routine, use it. If you aren't using it, remove the parameters from the routine interface."

However, in the past I sometime had to do that. Consider the following example:

Assume that we have an abstract base class called Food, containing a pure virtual function called getEaten. We derive two separate classes from it:

class Apple : public Food
{
    void getEaten(const Utensil &utensil);
    // otherstuff
};

and

class Soup : public Food
{
    void getEaten(const Utensil &utensil);
    // otherstuff
};

When we call mySoup.getEaten(spoon), the function makes use of the spoon parameter in order to perform the action. However, an apple does not need a utensil, and in those cases I have to send a dummy utensil to myApple.getEaten(emptyUtensil).

Yes, this is ugly, and has the overhead of unnecessarily creating and passing a dummy object. I can generalize the problem like this:

"When we have two concepts, which are represented as two classes, have the same action applied on one of them, and one needs more information than the other when requesting to execute those actions, I tend to pass dummy information to the less information requesting objects."

So my questions are:

1) How can we change the design of this somewhat silly example, so that we don't need to pass the dummy utensil?

2) If there is a nice simple solution to the first question, would there be a way to generalize it to the generalized problem above (like solutions as "in those cases create a new x such that it interacts with the less informating demanding class like this" etc.)

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top