这种设计是否过度工程化?

Lig*_*ica 7 c++ polymorphism

您是否会考虑使用接口和多态来扩展此设计以进行过度设计?

优点

  • 扩展
  • 封装
  • 自动神奇

缺点

  • 更多代码
  • 使用有点笨重(你必须使用不同的类型名称来获得不同的行为)
  • 可能是使用效率较低,由于虚函数调用.

我的直觉是,对于这种特殊情况,单个if语句和布尔标志是最好的选择,但不是每个人都同意我.

行什么,你觉得呢?


原版的

// 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;
};
Run Code Online (Sandbox Code Playgroud)

使用布尔标志扩展

// 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;
};
Run Code Online (Sandbox Code Playgroud)

扩展多态性

// 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;
};
Run Code Online (Sandbox Code Playgroud)

Mic*_*l J 9

这取决于你将使用它.如果你有一个大项目,并且会多次使用该类的变体,那么确保它具有灵活性是有意义的.

经验法则:

  1. 使用一次 - 保持简单.
  2. 使用它两次 - 保持简单,并根据需要进行复制和更改
  3. 三个或更多 - 概括它并使其适用于所有情况.

当然有很多例外,但这是一个起点.

  • 又名"一,二,很多".程序员不需要能够计算;-) (8认同)

Sep*_*ram 7

你为什么不复制文件描述符?这样,当对象被销毁时,你可以关闭()它并让操作系统处理剩下的事情:

CommandWriter::CommandWriter (int _fd) : fd (dup (_fd)) {};
Run Code Online (Sandbox Code Playgroud)

为此添加一个布尔标志就是发明了一个轮子.使用多态性正在构建一架frigging直升机.