Re: Blocks for scope control
ram@zedat.fu-berlin.de (Stefan Ram) writes:
alpha();
{ /* add a button to the frame */
final Button button = new Button();
frame.add( button ); }
beta();
I forgot to mention that there is an old software-engineering
principle: ?The scope of every identifier should be as small
as possible.? Blocks help to realize this.
Or, let's look at code posted into some other thread recently:
student <freenow12345@gmail.com> writes:
GOval g = makeCircle(centerX, centerY,radiusOuterCircle ,
Color.RED);
add(g);
g = makeCircle(centerX, centerY,radiusMiddleCircle ,
Color.WHITE);
add(g);
g = makeCircle(centerX, centerY,radiusInnerCircle ,
Color.RED);
add(g);
With blocks, ?g? can be made final:
{ final GOval g = makeCircle( centerX, centerY, radiusOuterCircle, Color.RED ); add( g ); }
{ final GOval g = makeCircle( centerX, centerY, radiusMiddleCircle, Color.WHITE ); add( g ); }
{ final GOval g = makeCircle( centerX, centerY, radiusInnerCircle, Color.RED ); add( g ); }
this also is more beautiful, because now there is more
symmetry between the the three actions, which then allows a
possible refactor to:
{ final CircleMaker circleMaker = new CircleMaker( g, centerX, centerY );
circleMaker.make( radiusOuterCircle, Color.RED );
circleMaker.make( radiusMiddleCircle, Color.WHITE );
circleMaker.make( radiusInnerCircle, Color.RED ); }
(this will probably not solve the actual problem of ?student?).
Or, to tell the story from its end:
The most important principle is ?DRY? - ?Don't repeat
yourself!?. To do this, we abstract repetitions of the same
principle into a single code location using abstractions.
But to do this, in turn, we need to be able to see
repetitions of the same principle. And to be able to see
them, the code needs to be made as symmetric as possible,
that is, to do the same thing, the same wording should be
used.
Or in a single line:
First, make the repetition obvious, then abstract it.