I've been self-studying C# as I dive into object-oriented programming. I have a simple game where a player navigates a board. Landing on Points boosts their score, while landing on Poison results in the player's demise. I created the following classes:
- Board
- Object
- Player (inherits from Object)
- Points (inherits from Object)
- Poison (inherits from Object)
The Board class includes a Move() method for player movement. If the player lands on Points or Poison, the Board calls a Collision() function. I'm seeking insights on which scenario is more aligned with proper object-oriented programming practices:
**Scenario 1:** Collision() calls the Object's Action() method. Points lead to Player's IncreasePoints() method, while Poison triggers Player's Die() method.
**Scenario 2:** Collision() invokes the Player's Take() function, which figures out the object type. Seconds Points increase the player's points, and Poison causes the player to die.
I'd love some feedback on this!
5 Answers
Instead of using 'Action()', perhaps name that function 'OnCollision()'. It keeps the structure organized. When a collision happens, the Board will call Object.OnCollision(Player player). For Points, this can lead to player.IncreasePoints(), and for Poison, just call player.Die(). It's cleaner and emphasizes clarity.
You might want to rethink calling your generic class 'Object' — that's a bit confusing, as many languages reserve that term. Instead, consider subclassing Object with a more generic name. Think of your player class as something that only holds player-specific functions, while points and poison should have their unique behavior. Essentially, keep shared functions at a higher level while specifying behaviors within subclasses. It's all about inheritance and ensuring each class only knows what it needs.
Avoid over-generalizing. The Points and Poison objects can be types of GameBoardField, with the player managing its position separately. When the player moves onto a new field, execute the field's action. This keeps the player, board, and fields distinct and flexible, allowing for various field types and player actions.
Have you checked out the SOLID principles? They could help guide your design. The Liskov Substitution Principle might be worth reviewing, especially as you consider super types and behaviors across your objects, ensuring that all subtypes act consistently.
I'd lean towards Scenario 1. This way, if you add new object types later, they can be self-contained without changing player code. The Board just calls Action(), and each object knows how to interact with the player. It helps keep your code modular and easier to maintain.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically