4 ms·
> The C++ "app" layer was a different story. The worst part it was a 3000 line switch/case block with about 100 different cases, chock full of copy-and-pasted c
by OneWingedShark 6y ago
> The C++ "app" layer was a different story. The worst part it was a 3000 line switch/case block with about 100 different cases, chock full of copy-and-pasted code. It went on... and on... and on... I still have nightmares about it.
Ouch. That sounds brutal.
If I had to do something similar, or maintain that, in Ada I'd leverage nested subprograms, local type/subtype definitions, and mandatory case-coverage — and I've done similar with VMs, particular opcodes — so you get something like:
Type Opcode is ( NOP, Add_A, SUB_A, ..., Rem_D );
Procedure Execute_Instruction( State : in out Machine_State; Instructions : in Instruction_Stream ) is
Subtype A_Series is Opcode range Add_A..Sub_A;
Subtype B_Series is Opcode range Add_B..Sub_B;
Subtype C_Series is Opcode range Add_C..Sub_C;
Subtype D_Series is Opcode range Add_D..Sub_D;
Procedure Do_Add_A;
-- other subprograms.
Current : Opcode renames Decode( Next_Token( Instructions ) );
--...
Begin
Case Current is
when A_Series =>
case A_Series'(Current) is
when Add_A => Do_Add_A;
end case;
-- other series.
end case;
End Execute_Instruction;
Of course you could structure it so that all the Do_OPCODE subprograms are local to the top-level switch, or local to the nested switches, as best suits the design; or decompose along 'families' of operation (Add_A, Add_B, Add_C, Add_D), but the important thing there is keeping things local/nested for maintainability.