Dom Sinclair
Dom Sinclair

Reputation: 2528

Is it possible for modules to share code

I am looking at Module A which performs task

  1. I am also looking at another module (module B) which performs task
  2. Tasks A & B are to all intents and purposes similar but for one small difference.

If they were classes I would be inclined to re-factor them such that the common code ended up in a base class inherited by modules A and B (which would of course now be classes because you cant inherit in a module).

However keeping Modules A & B as modules happens to be preferable in this particular instance so is there a clean way to have a third module that performs the same role as a base class or does one simply have to accept that in this instance there will have to be an element of code duplication.

I'm thinking along the lines of a friend declaration for the third module with the common methods declared as friends within that, but am wondering if I've overlooked something obvious.

Upvotes: 1

Views: 82

Answers (1)

rory.ap
rory.ap

Reputation: 35270

No, you haven't overlooked something obvious, I don't think. You should always try to follow the DRY principal (Do Not Repeat Yourself); in this case, refactor it so the common code exists only once in a separate module, and only the code that is different between the two original modules is left in those two.

Upvotes: 1

Related Questions