How to implement DMG (Game boy) cpu’s register using OOP patterns/principles to max code reusability?

  softwareengineering

I-m looking to learn better use of OOP principles/patterns so I decided to start implementing at least the basics of a GB emulator (technical part is widely covered on diff sites).

So I started with an empty CPU class, then decided to try to implement the 8bit registers A,B,C,D,E,F,H,L we also have pseudo 16bit registers AF,CD and HL (seen in GB registers), I was about to use just a dictionary and make some methods to implement them but that goes against the purpose of my initial motivation.

So, I’m wondering if a Factory Pattern is suitable to implement the registers or how would you tackle this in such a way that allow me to have some flexible code to create as many registers as I need of any type (8bit, pseudo 16bits or real 16bits) as I would like the code to be re-usable for let’s say another CPU emulation, this code/class will be somehow loosely couple to my CPU class (currently empty).

Please consider this more like an abstraction learning project than actually building a fully functional DMG emulator, but pursuing a DMG emulator seems quite suitable for learning and put in practice some adv OOP concepts.

2

I would like the code to be re-usable for let’s say another CPU emulation, this code/class will be somehow loosely couple to my CPU class (currently empty).

This may be a contortion of OOP. Registers are entwined with a CPU. Almost nothing happens that doesn’t involve a register in some way. And there are typically many many many ways they interact. While I appreciate the goal of learning OOP with a project, you may be having trouble implementing registers in an OOP style because they’re simply not a good match for OOP. A very important skill when it comes to paradigms like OOP is knowing when your paradigm of choice just isn’t the right one.

The same goes for the register file (the collection of registers and their names). Your loop that executes machine code is going to be intimately entwined with the registers that the opcodes operate on.

If you wanted to make OOP registers, my recommendation would be to make a register class which is Gameboy Only (don’t worry about other architectures), but make it so you can add features to it. Watchpoints are a very important tool in debugging, letting you break the execution when a value changes. Having a “normal” register which is fast and a “debugging” register which has support for debugging features like watchpoints may be a good use of OOP. Maybe have a third which logs out all of the changes that occur.

3

LEAVE A COMMENT