samedi 23 septembre 2017

Incovenience of avoiding duplicate code due to an if statement c++11

I want to avoid duplicated code in this usecase

class A {
protected: 
  virtual void A1(const void* const s, const std::streamsize n) const;
  inline void A2(const void* const s, const std::streamsize n) const;
};

class B : public A {
private:
  const  char *a;

  void B1(const char *b) {
     //duplicate code before this if
     if (a < b) {
         A1(a, b-a);
     }
  }

  void B2(const char *b) {
      //duplicate code before this if (the same as in B1)
      if (a < b) {
         A2(a, b-a);
     };
  }
};

So, as you can see above in both B1() and B2() there is duplicate code except for the call inside that if (note that the if condition is the same). I think this ifmakes somehow inconvenient to extract a new method, but also I think it can be done using lambdas and/or templates. There is no point of interest on how A1() and A2() are implemented for this usecase.

My question: What is the best and simplest way to avoid this duplication of code ?

Aucun commentaire:

Enregistrer un commentaire