NCL 507: Handlers
We've spent the last several lessons looking closely at how subroutines work.
We've passed arguments and results, defined interfaces, protected state, cleaned up temporary memory, and even given each invocation its own stack frame.
All of that machinery lets us build increasingly capable subroutines.
But there's another question worth asking:
What should one subroutine actually do?
Doing Everything
Suppose we're writing a game.
When the player enters a move, we need to:
- Read the move.
- Check whether the move is valid.
- Place the piece.
- Redraw the board.
- Report an error if the move wasn't valid.
We could put all of that in one subroutine:
:handle_move
-- Read the move.
-- Validate it.
-- Place the piece.
-- Redraw the board.
-- Report any error.
RET
There's nothing inherently wrong with the CALL or RET.
The routine could have a perfectly good interface. It could use Scratch correctly. It could clean up everything it touched.
But try describing what it does:
:handle_movereads a move, validates it, places the piece, redraws the board, and reports errors.
That's quite a collection of responsibilities hiding behind one name.
One Useful Operation
Instead, we can identify the useful operations inside it:
:read_move
-- ...
RET
:validate_move
-- ...
RET
:place_piece
-- ...
RET
:draw_board
-- ...
RET
Each subroutine now has a much simpler description.
| Handler | Job |
|---|---|
:read_move |
Reads a move from the user. |
:validate_move |
Determines whether a proposed move is valid. |
:place_piece |
Places a piece on the board. |
:draw_board |
Draws the current board on the Display. |
A subroutine responsible for a particular operation is often called a handler.
A good handler represents one useful operation.
The names often naturally take the form:
verb_object
For example:
:draw_board
:validate_move
:place_piece
:read_command
:print_error
:find_item
This isn't an NCL syntax rule.
It's just a useful naming pattern.
If you can give a subroutine a name like :draw_board and describe what it does in one sentence, you've probably found a reasonably clear operation.
Putting the Operations Together
Splitting the work into handlers doesn't mean the overall job disappeared.
Something still needs to coordinate them.
A higher-level handler might look roughly like this:
:handle_move
CALL :read_move
CALL :validate_move
-- Decide whether to continue.
CALL :place_piece
CALL :draw_board
RET
Now :handle_move has a much clearer role.
It handles a move by coordinating the operations involved.
It doesn't need to contain every detail of reading input, validating the move, placing a piece, and drawing the board itself.
Those jobs have names of their own.
This also means those operations can be used somewhere else.
If the board needs redrawing for another reason:
CALL :draw_board
We don't need to pretend a player just made a move.
If an automated player proposes a move, we can still:
CALL :validate_move
without first asking a human to enter one.
The operations have become useful independently.
Smaller Interfaces
Focused handlers also tend to need less information.
Imagine that the original :handle_move needed all of this:
| Value | Used for |
|---|---|
| Player input | Reading the move |
| Board state | Validating and placing |
| Current player | Validating and placing |
| Display position | Drawing |
| Error text | Reporting problems |
A :validate_move handler doesn't need to know where the board is drawn.
A :draw_board handler doesn't need the text the player originally entered.
A :place_piece handler doesn't need to know how the move was obtained.
Each handler only needs the values required for its own operation.
A smaller job often means:
- fewer arguments;
- less temporary state;
- less state to preserve;
- fewer cleanup paths.
The calling conventions we've spent the last several lessons building become easier to follow when each call has a focused purpose.
What's This Subroutine's Job?
There's a useful informal test when a subroutine starts getting complicated:
Can you describe what it does without using a pile of “and”s?
Consider:
:draw_boarddraws the current board.
Pretty clear.
Now:
:process_turnreads input, validates a move, updates the board, checks for a winner, redraws the screen, changes the current player, and prints any errors.
That may be a sign that several useful operations have become bundled together.
It isn't an absolute rule.
Sometimes one operation genuinely involves several steps.
:draw_board might clear an area, loop through every cell, choose characters, move the cursor, and write them to the Display.
It still has one coherent job:
Draw the board.
The question isn't how many instructions are inside the handler.
The question is what operation those instructions collectively perform.
Getters and setters
One particularly common naming pattern is to have small operations that get or set some piece of state.
You may encounter names such as:
get_position
set_position
get_score
set_score
These are commonly called getters and setters.
The pattern became especially visible in programming styles where some state isn't accessed directly. Instead, code asks one operation to retrieve it or another to change it.
NCL doesn't require this style. If a value is ordinary memory and there's no reason to put a subroutine in front of it, you can simply access it.
But getters and setters are good examples of handlers whose names make their jobs extremely obvious:
Get this value.
Set this value.
Sometimes the boring name is the good name.
Not Every Three Instructions
Once you've learned to split work into handlers, it's possible to go too far.
This is technically a subroutine:
:add_one
ADD $000 $000 1
RET
That doesn't necessarily make it useful.
We could keep going:
:add_one_to_x
-- ...
:compare_x_to_limit
-- ...
:increment_loop_counter
-- ...
:jump_if_more
-- ...
Soon a straightforward calculation has been scattered across a dozen tiny subroutines.
A handler should represent a useful operation, not an arbitrary chunk of instructions.
There is no magic instruction count where code should become a subroutine.
A useful handler might contain five instructions.
Another might contain fifty.
The boundary comes from what the code does, not how long it is.
Families of Handlers
Handlers become especially interesting when several of them perform related operations.
Imagine a program that accepts commands:
:command_look
-- ...
RET
:command_take
-- ...
RET
:command_open
-- ...
RET
:command_quit
-- ...
RET
Each handler has one clear job:
| Handler | Job |
|---|---|
:command_look |
Handles the LOOK command. |
:command_take |
Handles the TAKE command. |
:command_open |
Handles the OPEN command. |
:command_quit |
Handles the QUIT command. |
Better still, related handlers can use compatible interfaces.
Perhaps every command handler receives the same basic information and returns its result in the same way.
The program can then treat them as a family of operations.
There's one more thing these handlers have in common:
:command_look
:command_take
:command_open
:command_quit
Those labels are addresses.
And addresses are values.
We'll come back to that.
Try It
Suppose a program has grown this subroutine:
:handle_item
POP #item
S.BEQ :missing #item ""
D.TXT "Selected: "
D.TXT #item
D.TXT "\r\n"
PUSH #item
CALL :item_exists
POP #exists
BEQ :missing #exists 0
PUSH #item
CALL :item_price
POP #price
D.TXT "Price: "
S.MOVE $000 #price
D.TXT $000
D.TXT "\r\n"
PUSH #item
CALL :add_to_cart
D.TXT "Added to cart.\r\n"
FREE $000
RET
:missing
D.TXT "Item not found.\r\n"
FREE $000
RET
It works, but :handle_item is doing several useful operations itself.
Refactor it into focused handlers.
There isn't necessarily one correct set of boundaries.
For each handler you create, try to give it:
- a name that describes an operation;
- a clear interface;
- one sentence describing its job.
Don't split instructions merely to make the handlers shorter.
Look for verbs
Read through :handle_item and describe the things it does.
Names often become easier once you can identify the verbs.
Still stuck?
Some of the work could be described as:
show item
check item
show price
add item
report missing item
You don't necessarily need a separate handler for every one of these.
Look for reusable operations
Ask whether some piece of the routine would make sense to call independently.
Displaying an item's price, for example, might be useful somewhere other than this particular sequence.
Still stuck?
A handler such as:
:display_price
has an operation we can describe without referring to the rest of :handle_item:
Display the price of an item.
Don't atomize it
The goal isn't to produce the largest possible number of subroutines.
If several instructions together perform one clear operation, they can stay together.
Still stuck?
These instructions don't need separate handlers:
D.TXT "Selected: "
D.TXT #item
D.TXT "\r\n"
Together they perform one perfectly understandable operation: displaying the selected item.
Show me one approach
One possible decomposition is:
handle_item
coordinates the overall item operation
display_item
displays the selected item
display_price
obtains and displays an item's price
report_missing_item
displays the missing-item message
:item_exists, :item_price, and :add_to_cart were already focused handlers, so there is no reason to split them further.
The important part isn't arriving at exactly these four names.
It's that each handler represents an operation we can name, describe, and call independently where that operation is useful.
We've seen how handlers give useful operations their own names, interfaces, and entry points.
In the next lesson, NCL 508: Jump Tables, we'll take advantage of something unusual about those entry points: their addresses are values, and values can live in arrays.