Skip to content

Instantly share code, notes, and snippets.

@lbfalvy
Created May 7, 2023 01:23
Show Gist options
  • Save lbfalvy/56858fbe93053b9ac4db58aa65abd37b to your computer and use it in GitHub Desktop.
Save lbfalvy/56858fbe93053b9ac4db58aa65abd37b to your computer and use it in GitHub Desktop.

Interfaces

Context

This doesn't have to correspond to a concrete program element, but it helps clarity (and also forces teammates to do the right thing) if you encode contracts like this in interfaces (or pure abstract classes in the case of C++)

Program's contract with subclasses of Command. It exposes:

  • read/write variable by name (probably string& get_var(const string&) and void set_var(const string&, string))
  • read/write program counter (probably int get_icnt() and void set_icnt(int))

    It's possible to represent the instruction counter as a variable which makes this interface smaller at the cost of some performance due to string comparisons

  • read command by index (probably const Command& get_cmd(int))

Command

Capabilities exposed to Program

  • execute operation (probably void exec(Context&))

Implementors

Program (implements Context)

This class is responsible for holding shared data and dispatching commands.

Stores

  • Command instances in a polymorphic structure (probably vector<unique_ptr<Command>>)
  • program counter (probably int)
  • variables (probably unordered_map<string, string>)

Exposes

  • a function for running one execution step and showing whether the program halted (probably bool step())

    This function should resolve the next command, increment the program counter, and pass itself to exec on the command. The order of these operations matters.

  • probably functions that call step repeatedly for convenience.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment