Search code examples
c++interfaceinformation-hiding

Creating internal and external interfaces for a class / information hiding


For some classes of a static C++ library I want to offer different interfaces for the user of the library and for the library itself.

An example:

class Algorithm {

  public:

    // method for the user of the library
    void compute(const Data& data, Result& result) const;


    // method that I use only from other classes of the library
    // that I would like to hide from the external interface
    void setSecretParam(double aParam);

  private:

    double m_Param;
}

My first attempt was to create the external interface as an ABC:

class Algorithm {

  public:

    // factory method that creates instances of AlgorithmPrivate
    static Algorithm* create();

    virtual void compute(const Data& data, Result& result) const = 0;
}

class AlgorithmPrivate : public Algorithm {

  public:

    void compute(const Data& data, Result& result) const;

    void setSecretParam(double aParam);

  private:

    double m_Param;
}

Pros:

  • The user of Algorithm cannot see the internal interface

Cons:

  • The user has to use a factory method to create instances
  • I have to downcast Algorithm to AlgorithmPrivate when I want to access the secret parameters from inside the library.

I hope you understand what I try to achieve and I'm looking forward to any suggestions.


Solution

  • The simplest way might be to make setSecretParam() private and make the following a friend of Algorithm:

    void setSecretParam(Algorithm& algorithm, double aParam)
    {
      void setSecretParam(double aParam);
    }