Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay when a base class has only one derived class?

I am creating a password module using OOD and design patterns. The module will keep log of recordable events and read/write to a file. I created the interface in the base class and implementation in derived class. Now I am wondering if this is sort of bad smell if a base class has only one derived class. Is this kind of class hierarchy unnecessary? Now to eliminate the class hierarchy I can of course just do everything in one class and not derive at all, here is my code.

class CLogFile
{
public:
    CLogFile(void);
    virtual ~CLogFile(void);

    virtual void Read(CString strLog) = 0;
    virtual void Write(CString strNewMsg) = 0;
};

The derived class is:

class CLogFileImpl :
    public CLogFile
{
public:
    CLogFileImpl(CString strLogFileName, CString & strLog);
    virtual ~CLogFileImpl(void);

    virtual void Read(CString strLog);
    virtual void Write(CString strNewMsg);

protected:
    CString & m_strLog; // the log file data
    CString m_strLogFileName; // file name
};

Now in the code

CLogFile * m_LogFile = new CLogFileImpl( m_strLogPath, m_strLog );

m_LogFile->Write("Log file created");

My question is that on one hand I am following OOD principal and creating interface first and implementation in a derived class. On the other hand is it an overkill and does it complicate things? My code is simple enough not to use any design patterns but it does get clues from it in terms of general data encapsulation through a derived class.

Ultimately is the above class hierarchy good or should it be done in one class instead?

like image 942
zar Avatar asked Dec 16 '22 15:12

zar


2 Answers

No, in fact I believe your design is good. You may later need to add a mock or test implementation for your class and your design makes this easier.

like image 139
Ivaylo Strandjev Avatar answered Dec 29 '22 00:12

Ivaylo Strandjev


The answer depends on how likely it is that you'll have more than one behavior for that interface.

Read and write operations for a file system might make perfect sense now. What if you decide to write to something remote, like a database? In that case, a new implementation still works perfectly without affecting clients.

I'd say this is a fine example of how to do an interface.

Shouldn't you make the destructor pure virtual? If I recall correctly, that's the recommended idiom for creating a C++ interface according to Scott Myers.

like image 39
duffymo Avatar answered Dec 28 '22 23:12

duffymo