Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which design pattern to use (Active and passive methods)?

I have a player which can feed a dog or chop a tree.

Below are the classes I have written:

public class Dog {

    private int health;

    public void feed(Food food){
        health = health + food.getNutritionalValue();
    }
}

public class Player{

    public void feed(Dog dog, Food food) {
        dog.feed(food);
    }

Player and Dog both have methods that are "active".

Player feeds the dog and dog starts eating the food (I am not really sure if it is good to couple methods in this way).

On the other hand, I have tree. And player is able to chop the tree.

public class Player{

public void chop(Tree tree) {
        //At this point I am not sure
    }

I am not sure if I would use getters and setters of Tree class to interact with the Tree.

Or if I should write an own method for this because the tree gets chopped so it is nothing really active I would call.

So, in the end, there would be two or more kinds of implementations but the two I am thinking of are:

tree.setAmountofWood = x

or

tree.gettingChopped(Damage int)

I think I should make an own method for this chopping-process.

Or is there any design principle I should follow?

like image 454
user2742409 Avatar asked Jan 26 '26 08:01

user2742409


1 Answers

I see 3 principles here,

  1. SRP - It is the responsibility of the Tree to get chopped and fall down, but to cut is the responsibility of the Person!
  2. Demeter's law - looks good from my POV.
  3. OCP - The tree must be able to do further actions when get cut.

So you must use

tree.gettingChopped(Damage damage)

To your code:

  1. The method Dog.feed is wrong, rename it to Dog.eat because the Dog is not feeding, the dog is eating. By the way, the food must reduce its NutritionalValue.
  2. The health is an integer value, this is bad because in reality there is nothing like a numeral health. We may have a handicapped numeral value in percent, but this is more a byte who not can be in negative value. You should create a custom class for the Health! This way your code is open(OCP) for extensions like to be toxified or depresive.
like image 139
Grim Avatar answered Jan 27 '26 22:01

Grim