vendredi 30 novembre 2018

Example of the Object Calisthenics First Class Collection rule in C#?

I am playing with the Object Calisthenics rules and I am having some troubles to see when to use the first class collections when using C#.

I mean I hardly see when it's supposed to be used, for example it would be hard to apply that rule to an EF DbContext.

Let's say, we design a Board class.

public class Board
{
    public IList<BoardRow> Rows { get; }
    public IList<BoardColumn> Columns { get; }

    public Board()
    {
        Rows = new List<BoardRow>();
        Columns = new List<BoardColumn>();
    }
}

So according to that rule, we would have to turn the code above into:

// Is it really that better than just using List<BoardRow>?
public class BoardRowCollection : IEnumerable<BoardRow>
{
    public void Add(BoardRow row) { /*...*/ }
    public void Remove(BoardRow row) { /*...*/ }

    // IEnumerable<BoardRow> Impl goes here...
}

// Is it really that better than just using List<BoardColumn>?
public class BoardColumnCollection : IEnumerable<BoardColumn>
{
    public void Add(BoardColumn column) { /*...*/ }
    public void Remove(BoardColumn column) { /*...*/ }

    // IEnumerable<BoardRow> Impl goes here...
}

public class Board
{
    public BoardRowCollection Rows { get; }
    public BoardColumnCollection Column { get; }

    // Rest of the impl, ctor, etc.
}

I am not really sure to get the point of this rule when you already have base classes that can be leveraged to achieve your goals.

Maybe the code above is not the best but I would like to see one example which can shed the light on the purpose of that rule.

Aucun commentaire:

Enregistrer un commentaire