Home > Software engineering >  Better approach: mixed enum or 2 enums
Better approach: mixed enum or 2 enums

Time:06-24

I have two kinds of moving objects — Box and Car — which move a bit different.

Box: when set to move right, left, up or down will move 1 pixel to the desired direction.

Car: when set to move right or left - will rotate clockwise/counterclockwise. And when set to move forward/backward - will move according to the face and back of the Car. So if the car is rotated by 45 degrees and we set it to move forward the car will go half a pixel to the right and half a pixel up (assuming the car is starting face up).

I would like to know which of the following is better approach or if there is a better way:

public abstract class MovingObject
{
    public abstract void Move();

    public enum Direction { UP, DOWN, LEFT, RIGHT, FORWARD, BACKWARD }

    public Direction CurrentDirection { get; set; }

    //some other fields and properties


    public class Box : MovingObject
    {
        public override void Move(){...}
        //some Box related things
    }


    public class Car : MovingObject
    {
        public override void Move(){...}
        //some Car related things
    }
}

public abstract class MovingObject
{
    public abstract void Move();

    //some fields and properties


    public class Box : MovingObject
    {
        public enum Direction { UP, DOWN, LEFT, RIGHT }

        public Direction CurrentDirection { get; set; }

        public override void Move(){...}
    }


    public class Car : MovingObject
    {
        public enum Direction { FORWARD, BACKWARD, LEFT, RIGHT }

        public Direction CurrentDirection { get; set; }

        public override void Move(){...}
    }
}

CodePudding user response:

I would suggest creating two enums and a generic base class that would take an enum, the code would look like this.

public enum BoxDirection
{
    UP,
    DOWN,
    LEFT,
    RIGHT
}

public enum CarDirection
{
    LEFT,
    RIGHT,
    FORWARD,
    BACKWARD
}

public abstract class MovingObject<T> where T: Enum
{
    public abstract void Move();

    public T CurrentDirection { get; set; }

    //some other fields and properties


    public class Box : MovingObject<BoxDirection>
    {
        public override void Move() { ... }
        //some Box related things
    }

    public class Car : MovingObject<CarDirection>
    {
        public override void Move() { ... }
        //some Car related things
    }
}
  • Related