what is the meaning of data hiding

后端 未结 7 1831
小鲜肉
小鲜肉 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:04

    Data or Information Hiding is a design principal proposed by David Paranas.

    It says that you should hide the design decisions in one part of the program that are likely to be changed from other parts of the program, there by protecting the other parts from being affected by the changes in the first part.

    Encapsulation is programming language feature which enables data hiding. However note that you can do data\information hiding even without encapsulation. For example using modules or functions in non Object Oriented programming languages. Thus encapsulation is not data hiding but only a means of achieving it.

    While doing encapsulation if you ignore the underlying principal then you will not have a good design. For example consider this class -

    public class ActionHistory
    {
        private string[] _actionHistory;
    
        public string[] HistoryItems
        {
            get{return _actionHistory; }
            set{ _actionHistory = value; }
        }
    }
    

    This calls encapsulates an array. But it does not hide the design decision of using a string[] as an internal storage. If we want to change the internal storage later on it will affect the code using this class as well.

    Better design would be -

    public class ActionHistory
    {
        private string[] _actionHistory;
    
        public IEnumerable HistoryItems
        {
            get{return _actionHistory; }
        }
    }
    

提交回复
热议问题