3. Separating Implementation From Implementation Approach

In the previous approach we realized that the main issue with with C++ is that encapsulation does not encapsulate at binary level.This would mean that same class cannot be interface and implement it. The solution is to have two abstractions as two distinct entities using two C++ classes.


One C++ class has to be developed only to expose the functionality and the other to implement it. In this way we can ensure that we can change the implementation behind the scene and ship to the customers. 


the following is the implementation of FastStringIft class for encapsulating implementation class FastString.



//faststringitf.h
class __declspec(dllexport) FastStringltf {
class FastString; // introduce name of impl. class
FastString *m_pThis; // opaque pointer
                     // (size remains constant)
public:
FastStringltf(const char *psz);
-FastStringltf(void);
int Length(void) const; // returns # of characters
int Find(const char *psz) const; // returns offset
} ;

//faststringitf.cpp // (part of DLL, not client) 
#include "faststring.h"
#include "faststringitf.h"
FastStringltf::FastStringltf(const char *psz)
   m_pThis(new FastString(psz)) {
   assert(m_pThis != 0);
}
FastStringltf: :-FastStringltf(void) {
  delete m_pThis;
}
int FastStringltf::Lengthltf(void) const {
   return m_pThis->Length();
}
int FastStringltf::Find(const char *psz) const {
   return m_pThis->Find(psz);
}



Now consider the previous problem, if the size of the of FastString class size changes from 4 Bytes to 8 Bytes . When we compile the DLL the FastString will be instantiated in the DLL itself (  new FastString(psz)  in FastStringIft.cpp ) allocating the required size to instantiate the FastString object. Now, when client calls the FastStringItf , the solution will work correctly because there is no impact on definition of the interface class.

PROBLEMS SOLVED WITH THIS APPROACH:

  • The implementation of the class be modified without impacting the client .


IMMEDIATE CHALLENGE AHEAD:

  • Too much work and error prone.
     The calls have to be directed from the interface class FastStringItf class to the implementing class for each function (m_pThis->Find(psz),m_pThis->Length()). This is easy for one or two but when you have 100s of them you can imagine the situation. Also, this is not an effective solution to have duplicate calls.

  





No comments:

Post a Comment