EDIT: This post will be outdated the day of the Pharo 3.0 release (~ february 2014), this implementation is valid up to Pharo 2.0.

What is an inspector ?

The inspector is a tool that permits to inspect the object, meaning usually to see his instance variables. In Pharo you can display it by doing ‘object inspect’ or, while selecting an object, doing cmd + i. It’s also the tool that is at the bottom of the debugger, permitting to inspect the receiver and the context of the method currently executed.

Why should I implement an Inspector ?

Basically if you are used to inspect object, sometimes you think that the inspector is not efficient enough.  For example, if I have an object ‘TrafficLight’ that have 3 instances variables, lightGreen, lightYellow and lightRed, when you inspect it, and you want to see what light is on, you will have either to evaluate some code or to inspect all of the light. If you develop an inspector, which takes around 2 minutes to do, you will earn 5 seconds each time you want to know which light is on. If you develop a full city lighting project, you will need to do that around 2000 times during your future development, so the inspector worth it. Moreover, it helps the newcomer understanding how the project code works.

So let’s implement a very quick inspector for a TrafficLight.

Create the class Light :

Object subclass: #Light
instanceVariableNames: ‘color on’
Light>>color
^color
Light>>color: aColor
color := aColor
Light>>initialize
super initialize.
on := false
Light>>lightOn
on := true
Light class>>newWithColor: aColor
^self new
color: aColor;
yourself

Create the class TrafficLight :

Object subclass: #TrafficLight
instanceVariableNames: ‘green red yellow’
TrafficLight>>initialize
super initialize.
red := Light newWithColor: Color red.
yellow := Light newWithColor: Color yellow.
green := Light newWithColor: Color green.
{red . yellow . green} atRandom lightOn

Now on a workspace inspect (Cmd+i) the TrafficLight. You have no clue which light is on, and you can’t know it easily. Let’s add the method :

Light>>isOn
^on
TrafficLight>>whichIsOn
{red . yellow . green} do: [:light |
light isOn ifTrue: [^light color]]

Now create the inspector class :

Inspector subclass: #TrafficLightInspector
instanceVariableNames:
TrafficLightInspector>>fieldList
^super fieldList, #(#lightOn)
TrafficLightInspector>>selection
selectionIndex <= self numberOfFixedFields
ifTrue: [^ super selection].
^object whichIsOn

We now need to precise to the TrafficLight its new inspector

TrafficLight>>inspectorClass
^TrafficLightInspector

Now when you inspect ‘TrafficLight new’, you have one more field, lightOn, that prints the color of the light which is on. Of course, this example is very easy and not that useful. But dedicated inspectors are sometimes very useful.

Advertisements