When instantiating the ICollection

1

I'm reviewing some programming approaches and fall into a dilemma as to where we should instantiate our navigation properties from EF ICollection .

Many cases I see that the personnel instantiates them in the constructor, would this be a good practice?

In a few cases I see instances that instantiate only when really necessary, which I think would be a more correct approach.

So, taking the example of the Pais entity that has a list of Estados

Parent Entity

[Table("Paises")]
[DisplayColumn("Nome")]
public class Pais : Entidade
{
    public Pais()
    {
        Estados = new HashSet<Estado>();
    }

    [Key]
    public Guid PaisId { get; set; }

    [Required]
    [StringLength(200)]
    public string Nome { get; set; }

    [Required]
    [StringLength(3)]
    public string Sigla { get; set; }

    public ICollection<Estado> Estados { get; set; }
}

State entity

[Table("Estados")]
    [DisplayColumn("Nome")]
    public class Estado : Entidade
    {
        [Key]
        public Guid EstadoId { get; set; }

        public Guid PaisId { get; set; }

        [Required]
        [StringLength(200)]
        public String Nome { get; set; }

        [Required]
        [StringLength(2)]
        public String Sigla { get; set; }

        public virtual Pais Pais { get; set; }

        public ICollection<Cidade> Cidades { get; set; }
    }

In the first approach I see in the parent constructor the creation of a HashSet

public Pais()
{
    Estados = new HashSet<Estado>();
}

In another approach I see only at the time of use, as shown in the following example

pais = new Pais();
if (pais.Estados == null)
    pais.Estados = new List<Estado>();

pais.Estados.Add(new Estado() { Sigla = "RS", Nome = "Rio Grande do Sul" });

In this second case, if the ICollection<Estado> creation was in the Pais entity, you would not need the if to check if the Estados object is null by simply adding more items in the collection. / p>     

asked by anonymous 26.07.2016 / 04:09

1 answer

1

I think the best approach is to check if it is null. I do not usually instantiate collections as in the first approach.

  • Somewhere in the program flow can cause the state of the "States" property to be null. Can you guarantee this will not happen?

  • For example if you use ReSharper it will suggest you to verify by null.

    / li>

  • If you do not always use it, you do not have to allocate space for the collection.

  • li>
  • 31.08.2016 / 01:38