Could you use the interface and polymorphism to expand this design to over-engineering?
Pros
- Extensible
- encapsulated
- Auto-magical
against
- More code
- A bit cumbersome to use (you have to use a different type name to get a different behavior)
- May be less efficient to use due to virtual function calls.
My instinct is that for this particular case, one if and a boolean flag are an excellent option, but not everyone agreed with me.
What do you think?
Original
// Connects to a local pipe, and naturally // owns that connection struct CommandWriter { CommandWriter() { fd = open("/path/to/fifo", O_WRONLY); if (fd == -1) throw std::runtime_error("Could not establish connection to FIFO"); }; ~CommandWriter() { close(fd); }; // (Has useful member functions here) private: CommandWriter(CommandWriter const&); // Not relevant to question int fd; };
Extended with boolean flag
// Adds a constructor where an FD can be specified // from the call site, and no ownership is taken struct CommandWriter { CommandWriter() : owns_fd(true) { fd = open("/path/to/fifo", O_WRONLY); if (fd == -1) throw std::runtime_error("Could not establish connection to FIFO"); }; CommandWriter(int fd) : fd(fd), owns_fd(false) {}; ~CommandWriter() { if (owns_fd) close(fd); }; // (Has useful member functions here) private: CommandWriter(CommandWriter const&); // Not relevant to question int fd; bool owns_fd; };
Advanced with polymorphism
// Sorry for the poor type names! struct ICommandWriter { virtual ICommandWriter() {} // (Has useful member functions here) private: ICommandWriter(ICommandWriter const&); // Not relevant to question }; struct CommandWriter_Connects : ICommandWriter { CommandWriter_Connects() { fd = open("/path/to/fifo", O_WRONLY); if (fd == -1) throw std::runtime_error("Could not establish connection to FIFO"); }; ~CommandWriter_Connects() { close(fd); }; // (Has useful member functions here) private: int fd; }; struct CommandWriter_Uses : ICommandWriter { CommandWriter_Uses(int fd) : fd(fd) {}; ~CommandWriter_Uses() {}; // (Has useful member functions here) private: int fd; };
Lightness races in orbit
source share