When/why to make function private in class?

后端 未结 7 812
攒了一身酷
攒了一身酷 2020-12-28 15:50

When should i make a function private and why is it good idea?

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 16:26

    I usually make the helper functions private. But what is helper seems to be vague. So let me give you an example. Suppose you've the following class Sample; it exposes few public functions, one of them, say, is DoWork(). This function takes one parameter. But it doesn't assume that the parameter will always be valid, so it first checks the validity of parameter for which it has lots of code in the beginning of the function. Something like this:

    class Sample
    {
       public:
          void DoWork(SomeClass param)
          {
                   /*
                    *lots of code related to validation of param
                    */  
    
                    //actual code that operates on the param 
                    //and other member data IF the param is valid
          }
    };
    

    Since you've written lots of code related to validation of the param, it makes the function cumbersome, and difficult to read. So you decided to move this validation code to function say, IsValidParam(), and then you call this function from DoWork() passing the parameter param to it. Something like this:

    class Sample
    {
       public:
          void DoWork(SomeClass param)
          {       
                if ( IsValidParam(param))       
                {
                    //actual code that operates on the param 
                    //and other member data IF the param is valid
                }
          }
    };
    

    That looks cleaner, right?

    Okay, you've written IsValidParam() somewhere in the class, but the question you face now is, would you make this function public? If this function is used only by your other functions like DoWork(), then making IsValidParam() public doesn't make sense. So you decided to make this function private.

    class Sample
    {
       public:
          void DoWork(SomeClass param)
          {       
                if ( IsValidParam(param))       
                {
                    //actual code that operates on the param 
                    //and other member data IF the param is valid
                }
          }
      private:
          bool IsValidParam(SomeClass param)
          {
              //check the validity of param.
              //return true if valid, else false.
          }
    };
    

    Functions of this kind (IsValidParam) should be private. I call these functions helper functions.

    Hope this explanation helps you!

提交回复
热议问题