What are the best practices for managing properties / fields (and data) and methods in classes?

advertisements

Q: What are the best practices for managing Properties/Fiels and their data and methods used to grab and set properties with data in C#?

I've seen two common scenarios:

  1. Put Properties/Fields and methods used to load their data in one class. Usually, method(s) are called in Constructor and so whenever this class is instantiated, data loading methods would be called immediately. A simple Example can be like this:

    public class MetaData
    {
        public MetaData()
        {
            LoadData();
        }
    
        public string Id { get; set; }
        public string Name { get; set; }
        public Double PrivateKey { get; set; }
    
        private void LoadData()
        {
            var rnd = new Random();
            Name= "Farhan";
            Id = Name + '_' + rnd.Next();
            PrivateKey = rnd.NextDouble();
        }
    }
    
    
  2. Put Properties/Fields in the separate class (may call as Storage Class) and another class containing methods used to load Properties/Fields of that class.

    public class MetaData
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public Double PrivateKey { get; set; }
    }
    
    public class DataContext
    {
        public MetaData metData = new MetaData();
        public void LoadData()
        {
            var rnd = new Random();
            metData.Name = "Agha";
            metData.Id = metData.Name + '_' + rnd.Next();
            metData.PrivateKey = rnd.NextDouble();
        }
    }
    
    

I personally feel that 1st approach is better, but I would like to get knowledge about best practices keeping in view of code management/readability and performance related things.


Its preference. Some like one way other like other ways. Some follows certain guidelines and other doesn't follow industry standard guidelines. Taking SOLID principle's S which says Single Responsibility for a class you may just declare properties and create another file where you write Save Method only.

While other may write all CRUD operation in single file related to specific entity. But I recommend sticking with SOLID principles and there are numbers of other recommendation and principles that you should consider.