Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it alright to put data members in an interface?

Recently, I've learnt about composite pattern. I want to use it in my assignment which I have to implement File and Folder classes. I realize that sub-classes like CFile and Cfolder got to have the same attributes (name and size). So is it alright for me to put the attributes into the interface? As far as I know, it is not good practice to do so. However, I don't understand why I shouldn't. Or is there any other solutions? Class Diagram

like image 796
Stoatman Avatar asked Jul 27 '16 16:07

Stoatman


2 Answers

I would say its not a problem. Th difference is that instead of a pure interface class you have an abstract base class. However, if you want to retain the flexibility to use the interface for implementations that are not tied down to those specific member variables then you can always create an interface class as well as an abstract base class for full flexibility. Though that may be getting overly complex overly soon, you can always split the interface from the abstract base later if you need to.

using CItemUPtr = std::unique_ptr<class CItem>;

/**
 * Interface class
 */
class CItem
{
public:
    virtual ~CItem() {}

    virtual CItemUPtr findByName(std::string const& name) = 0;
    virtual void setHidden(bool a, bool b) = 0;
};

/**
 * Abstract base class
 */
class AbstractCItem
: public CItem
{
protected:
    std::string name;
    std::size_t size;
};

class CFile
: public AbstractCItem
{
public:

    CItemUPtr findByName(std::string const& name) override
    {
        // stuff
        return {};
    }

    void setHidden(bool a, bool b) override {}
};
like image 81
Galik Avatar answered Sep 21 '22 05:09

Galik


It's not really a question of "is it a good practice". By creating an interface, you're defining a standard. The question is, do you NEED the implementation of the interface to contain those data members? You are in the best position to understand your implementation, so you're really the only one who can answer this.

As a general rule, the class implementing the interface should be a black box, and the outside world shouldn't have access to any internals (including member data). Interfaces define common functionality that is required to be present to be able to support the interface, and I'd expect those implementation details to be buried in the underlying implementation of the class only, as a general rule. YMMV.

like image 33
Lynn Crumbling Avatar answered Sep 19 '22 05:09

Lynn Crumbling