Writing the Inventory of a Method

If I were baking cookies, I would start by getting out all the ingredients -- butter, sugar, chocolate, eggs, more chocolate, baking powder, vanilla, more chocolate -- and arranging them on the counter. This way I can confirm that I have enough of everything I need, and it's all ready at hand when I need it. We'll do the same thing in writing a method: before we write any of the code for the method, we'll list (in comments) all the values we have available to use in writing that code. To remind us of what we can legitimately do with them, we'll write down the type of each one next to it.

For now, the only values we have available (other than literals) are the parameters of the method. However, if the method isn't static, it has an implicit parameter, which is always named this, and whose type is always the class we're in. Furthermore, if any of the parameters (including this is of a class type, we include in the inventory how to get at the fields or instance variables of that class. (If there are a lot of fields, and you know in advance that only a few of them are relevant to the method at hand, you can save typing by writing inventory entries only for the relevant fields.)

For example, if we had the following class, with three method skeletons:

class Posn
{
	double x;
	double y;
	
	public double distanceToOrigin ()
	{
	}

	public double scalePosn (double factor)
	{
	}

	public Posn addPosns (Posn other)
	{
	}
}
adding inventories to all three methods would give us
class Posn
{
	double x;
	double y;
	
	public double distanceToOrigin ()
	{
	// this    Posn
	// this.x  double
	// this.y  double
	}

	public double scalePosn (double factor)
	{
	// factor    double
	// this      Posn
	// this.x    double
	// this.y    double
	}

	public Posn addPosns (Posn other)
	{
	// this      Posn
	// other     Posn
	// this.x    double
	// this.y    double
	// other.x   double
	// other.y   double
	}
}

So far, this is pretty simple, and for many of you it may seem like a waste of time. However, the inventories will get more interesting and more useful as the course goes on.


Last modified: Tue Feb 10 22:52:07 EST 2009
Stephen Bloch / sbloch@adelphi.edu