Question

If its needed some generic read and/or write access, is better to do it this way?:

class IRead {
public:
    virtual int read() const = 0;
};

class IWrite {
public:
    virtual void write(int) = 0;    
};

class concrete_readonly : public IRead {
public: 
    virtual int read() const {  ... }
};

class concrete_writeonly : public Iwrite {
public: 
    virtual void write(int i) { ... }
};

class concrete_readwrite : public IRead, public IWrite {
public: 
    virtual int read() const { ... }
    virtual void write(int i) { ... }
};

Or is better to have single interface and dissallow undesirable acces in derived concrete class, for examle this way? :

class IAccess {
public:
    virtual int read() const = 0;
    virtual void write(int) = 0;    
};

class concrete_readonly : public IAccess {
public: 
    virtual int read() const {  ... }
    virtual void write(int i) { assert(0); }
};

class concrete_writeonly : public IAccess {
public: 
    virtual int read() const { assert(0); return 0; }
    virtual void write(int i) {  ... }
};

class concrete_readwrite : public IAccess {
public: 
    virtual int read() const { ... }
    virtual void write(int i) { ... }
};

Or can be done something else?

Was it helpful?

Solution

The first way is better, because of the Liskov Substitution Principle. A base class which offers read and write but actually can't promise that either will work is basically useless. Two base classes which offer guaranteed functionality are much more useful.

On the other hand, proceed with caution, because while it is tempting to think that reading and writing can be abstracted cleanly, it is often not the case. For example, reading and writing using network sockets requires extra state to handle asynchronous operation; reading datagrams from UDP has different semantics than packets from TCP, etc.

OTHER TIPS

Probably former I would say, and the reason for that is; If it is a concrete readonly class why should the compiler enforce a Write(...) method on it?

The question might be more general than about read/write access but since that's not clear I'll sum up some reasons why I would advise against it entirely:

  • C++ already has const
  • Write-only has very little use (Hardware access?)
  • You need at least templates for this (only read/write ints?) and it might become complicated
  • There is no functional gain
  • You force your classes to have virtual functions (and a virtual destructor) without any use for polymorphism.
  • Getters/setters should only be used when needed, classes should preferably just do something

Sorry for the negativity, it is just advice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top