Home > Back-end >  Navigating a organizational hierarchy, how to represent the top?
Navigating a organizational hierarchy, how to represent the top?

Time:08-11

I'm working with hierarchal organization data.

public class Position
{
  public string PositionCode { get; set; }
  public string Title { get; set; }
  public Position ReportsToPosition { get; set; }
}

Each Position has a property pointing to the Position it reports to. However, at the very top of the organization is the President, who doesn't report to a real Position. In its place, I've created a derived class named PositionNone.

public class PositionNone : Position
{
    private static PositionNone _positionNone;
    public PositionNone()
        : base(positionCode: "None",
               title: "None",
               reportsToPosition: _positionNone){}
}

This code will build, but it doesn't feel right.

  • we're using Nullable Reference Types and _positionNone is not initialized.
  • since there should only ever need to be a single PositionNone, I'd like to mark it static and have it self-reference, public static class PositionNone : Position, but that is not allowed.

I want to keep the rich model hierarchy below the president, but need to figure out how to represent the very top. I can deal with the possible infinite loop when walking up the hierarchy.

Any suggestions on how to implement this? Am I completely off base? Do I need to head in a different direction?

CodePudding user response:

I'd make PositionNone a static property (or field) of Position. Something like:

public class Position
{
    public Position(string positionCode, string title, Position reportsTo)
    {
        PositionCode = positionCode;
        Title = title;
        ReportsToPosition = reportsTo;
    }

    public string PositionCode { get; set; }

    public string Title { get; set; }

    public Position ReportsToPosition { get; set; }

    public static Position PositionNone => new Position(
        positionCode: "None", 
        title: "None", 
        reportsTo: Position.PositionNone);
}

CodePudding user response:

When someone has none to report to it means it is the president, do not be shy in using null even in a non-nullable environment.

Delete PositionNone and make ReportsToPosition explicitly nullable.

  • Related