what is the meaning of data hiding

后端 未结 7 1841
小鲜肉
小鲜肉 2021-01-19 03:23

One of the most important aspects of OOP is data hiding. Can somebody explain using a simple piece of code what data hiding is exactly and why we need it?

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-19 04:16

    Information hiding (or more accurately encapsulation) is the practice of restricting direct access to your information on a class. We use getters/setters or more advanced constructs in C# called properties.

    This lets us govern how the data is accessed, so we can sanitize inputs and format outputs later if it's required.

    The idea is on any public interface, we cannot trust the calling body to do the right thing, so if you make sure it can ONLY do the right thing, you'll have less problems.

    Example:

    public class InformationHiding
    {
        private string _name;
        public string Name
        {
           get { return _name; }
           set { _name = value; }
        }
    
        /// This example ensures you can't have a negative age
        /// as this would probably mess up logic somewhere in
        /// this class.
        private int _age;
        public int Age
        {
           get { return _age; }
           set { if (value < 0) { _age = 0; } else { _age = value; } }
        }
    }
    

提交回复
热议问题