Where do objects come from?

01 Mar 2016

Kent Beck has a series of articles, describing various origins of objects, "Objects from States", "Objects from Variables", "Objects from Collections", "Objects From Methods".

I think it's an interesting question, and Kent Beck didn't exhaust it.

Let's talk about objects that you might find, when dealing with an annoying mechanical external reality.

First, let's talk about a plotter.

The plotter might have three axes (x, y, z), each of which might be controlled by a stepper motor. The z axis might be used for pen-up and pen-down.

To draw a little square we might want to do something like this

// move to 3, 3
x.inc();
x.inc();
x.inc();
y.inc();
y.inc();
y.inc();

// pen down
z.inc();

// top of square
x.inc();
x.inc();
x.inc();
x.inc();

// right side of square
y.inc();
y.inc();
y.inc();
y.inc();

// bottom side of square
x.dec();
x.dec();
x.dec();
x.dec();

// left side of square
y.dec();
y.dec();
y.dec();
y.dec();

// pen up
z.dec();

That is, we have three objects (the three stepper motors) that offer two methods each (step forward and step backward).

From this (toy, and therefore unrealistically convenient, but still moderately annoying) starting point, we might use the Composite and Command design patterns to generate something like this:

PlotCommands have an execute method.
North is-a PlotCommand.
North has-a next PlotCommand.
East is-a PlotCommand.
East has-a next PlotCommand.
West is-a PlotCommand.
West has-a next PlotCommand.
South is-a PlotCommand.
South has-a next PlotCommand.
PenDown is-a PlotCommand.
PenDown has-a next PlotCommand.
PenUp is-a PlotCommand.
PenUp has-a next PlotCommand.
Halt is-a PlotCommand.

Class diagram

With this much, we can build that program above as a chain of objects, and execute it.

Can we build a LineFromTo? A single object, that takes an absolute starting point and an absolute ending point in its constructor, and which when executed, draws a line from the starting point to the ending point?

The problem is that LineFromTo corresponds to different programs, depending on the starting position of the plotter. So if we added the starting position of the plotter to the Execute interface, could we write LineFromTo?

Yes.

We might express LineFromTo via something else. If we had LineTo, LineFromTo could be PenUp, LineTo(startpoint), PenDown, LineTo(endpoint).

Class diagram 2

I'm not sure how to conclude. Certainly objects can come from interfaces - that's the command pattern. However, you get a richer set of objects from a more awkward interface. The origin of the additional objects might actually be the gap between the interface that we have and the interface that we want.

There's an idea in Jackson Structured Programming of a "structure clash". Structure clashes are hard to talk about, because it's hard to exhibit a toy example of complexity - you need a certain amount of real complexity in order to exhibit a structure clash.