I'm writing a virtual CPU, and I decided to create a class for each command, to make it easier to replace/add/remove commands without changing too much.

The original idea was that ICommand would be given an ICPUState to operate on, but then I released I'll have more than one type of virtual CPU. Most of the VCPUs will have some identical commands and some identical data (for example, registers array and a command that sums registers) but if I'd follow that idea, I wouldn't be able to share commands between different CPUs (because command for one CPU type will take ICPUState1, and not ICPUState2).

So I decided that no class CPUState will be presented. Instead, each command would be given what it needs upon construction (a reference for array of registers and the program's code in the example above). So far so good, but now I want to split CPU state from its CPU (so that one CPU instance could be used to operate on multiple distinct states) and it's impossible. Is there a third way, which will allow to share commands between different CPUs type, but also allow one CPU operate on multiple distinct states?

Also, I wonder if splitting the state of the CPU into multiple pieces considered legit - for some reason, I feel that the state of a cpu should be contained in one class and not splitted over many.

  • 1
    "I feel that the state of a cpu should be contained in one class and not splitted over many" - the state of the real world CPUs I know manifests itself in the content of several registers, flags and modes - why do you think lumping that all together in one large god class would make a better design? I mean, yes, a CPU class which holds all state variables together makes sense, but those state variables could be still modeled as classes themselves, this is no contradiction.
    – Doc Brown
    Apr 23, 2022 at 18:56
  • 1
    It might help to change your perspective a little bit. Don't split the class based on data. Split based on behavior. Apr 25, 2022 at 17:38


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.