mercredi 19 octobre 2016

How to properly design library external access without mess up its internal access?

I'm trying to design a library, opening only several interfaces to caller, without mess up its own internal access control. What is the proper way to do it?

For example, here is the library:

namespace ControlledLib {
    class ThinkTrack1   {
        friend class DeepThought;
        friend class ThinkTrack2;
    private:
        int ResultA()   { return 6; }
        int ResultB()   { return 5; }
    };

    class ThinkTrack2   {
        friend class DeepThought;
    private:
        int ResultC()   { ThinkTrack1 tt1; return tt1.ResultB() + 2; }
    };

    class DeepThought   {
        friend int DeepThoughtAnswers();
    private:
        int Answers()   { 
            ThinkTrack1 tt1;
            ThinkTrack2 tt2;
            return tt1.ResultA() * tt2.ResultC(); 
        }
        int CreateWorld()   {
            return 7;
        }
    };

    int DeepThoughtAnswers()    { DeepThought dt;  return dt.Answers(); }
}

, it can be called by

#include "ControlledLib.h"

int i = ControlledLib::DeepThoughtAnswers();

The actual answer is given by class DeepThought's function Answers(), however, to make only one Answers() accessible to external callers, I have to make class DeepThought's functions private, and invent a global function DeepThoughtAnswers() as an entry point, which calls class DeepThought to get the answer, then class DeepThought has to define DeepThoughtAnswers() as a friend function.

It just begins. As class DeepThought actually calls class ThinkTrack1 and class ThinkTrack2, and class ThinkTrack2 calls class ThinkTrack1 and so on... To make all these unaccessible to external caller, all these functions are set to private, and I have to define a lot of friendship. Most of all, all these messed up the internal access control!

What would be a better way to do it?

Aucun commentaire:

Enregistrer un commentaire