Search code examples
c#classrecursionself-referencedice

Best practice for recursive class


Problem:

I want to build a class for a custom dice. But it should also provide the following:

  1. Every side can contain an other dice
  2. The number of sides should be dynamically expandable, but must at least contain one
    • Logically the dice need to have a currentSide
  3. Every side has a property, which provides the content of this side (on a D6, it would be "4")

So far so good, I went and made two classes dice and side and gave them the properties I think they needed.

public class Side
{
    //public bool HasDice { get { return Dice != null; } } - Removed not needed
    public Dice Dice { get; set; }
    public string Value { get; set; }
}

public class Dice
{
    public ObservableCollection<Side> Sides { get; set; }
    public string Name { get; set; }
    public Side CurrentSide { get; set; }
}

Is this right, I never made any recursive classes so I'm not sure ?

Also how am I able to detect if the same dice and side are "endlessly" referring to them self.

Like:

D1.CurrentSide = Side1; Side1.Dice = D1;

Should I check this when building objects ?

Edit:

Example Dice Image

  • If D1 rolls S2 then D2 shouldn't be rolled. Also D2.Dice = Null.

  • If D1 rolls S1 then D2 should be rolled.

  • If D2 rolls S1 then D3 should be rolled.

  • If D2 rolls S2 then D4 should be rolled.

D3 and D4 shouldn't trigger any roll.


Solution

  • What you are making is called a state machine. Your program (the "machine") is always in some state, but can change the state as a consequence of performing some action. Depending on the logic it can be quite acceptable that the machine can be in the same state more than once. So, I wouldn't bother too much about loops in the machine's logic. If a user wants the loop then let him have it, as long as the machine can reach some final state and program reaches the end of execution.