Reputation: 1147
Let's assume that one has two C++
classes that support read-only and write-only operations on a file descriptor respectively.
class ReadFd {
public:
ssize_t read( /* */ ) {
// read from file_descriptor_
}
protected:
int file_descriptor_;
};
class WriteFd {
public:
ssize_t write(/* */) {
// write to file_descriptor_
}
protected:
int file_descriptor_;
};
Now suppose one would like to define a class ReadWriteFd
that supports both read and write operations.
My question is how to design such read-write class to avoid code duplication?
I cannot inherit from both ReadFd
and WriteFd
because obviously I need just one file_descriptor_
. The real situation that I encountered a bit more complicated but the concept here reflects it rather close.
Upvotes: 4
Views: 192
Reputation: 6546
As OO Principals state:
Encapsulate what varies. – can be rephrased as “Identify the aspects of your application that vary and separate them from what stays the same.” For those aspects that don’t change, we leave them as they are. Of course, we can’t just throw away those parts that vary; the former still needs to interact with them in order for the system to work.
In your particular case you can create a base class with common data and interfaces.
Upvotes: 1
Reputation: 33864
Create a new base class called class Fd
which contains the file descriptor. class ReadFd
& WriteFd
can both inherit from it with an is-a
relationship. Your ReadWriteFd
can inherit from these 2 classes. Just remember that you will have to solve the diamond multiple inheritance problem.
Here is an example UML:
Upvotes: 2
Reputation: 409166
Add a third class, base to both ReadFd
and WriteFd
, whose only purpose is to contain the descriptor variable (and possibly other things common to both reading and writing).
Upvotes: 7