Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encapsulating an algorithm into a class

I'm wondering how (un)common it is to encapsulate an algorithm into a class? More concretely, instead of having a number of separate functions that forward common parameters between each other:

void f(int common1, int param1, int *out1);
void g(int common1, int common2, int param1, int *out2)
{
  f(common1, param1, ..);
}

to encapsulate common parameters into a class and do all of the work in the constructor:

struct Algo
{
  int common1;
  int common2;

  Algo(int common1, int common2, int param)
  { // do most of the work }

  void f(int param1, int *out1);
  void g(int param1, int *out2);
};

It seems very practical not having to forward common parameters and intermediate results through function arguments.. But I haven't seen this "pattern" being widely used.. What are the possible downsides?

like image 844
zvrba Avatar asked Sep 30 '08 16:09

zvrba


2 Answers

It's not a bad strategy at all. In fact, if you have the ability in your language (which you do in C++) to define some type of abstract superclass which defines an opaque interface to the underlying functionality, you can swap different algorithms in and out at runtime (think sorting algorithms, for example). If your chosen language has reflection, you can even have code that is infinitely extensible, allowing algorithms to be loaded and used that may not have even existed when the consumer of said algorithms was written. This also allows you to loosely couple your other functional classes and algorithmic classes, which is helpful in refactoring and in keeping your sanity intact when working on large projects.

Of course, anytime you start to build a complex class structure, there will be extra architecture - and therefore code - that will need to be built and maintained. However, in my opinion the benefits in the long run outweigh this minor inconvenience.

One final suggestion: do not do your work in the constructor. Constructors should only be used to initialize a classes internal structure to reasonable defaults. Yes, this may include calling other methods to finish initialization, but initialization is not operation. The two should be separate, even if it requires one more call in your code to run the particular algorithm you were looking for.

like image 137
rpj Avatar answered Oct 06 '22 19:10

rpj


There's a design pattern that addresses the issue; it's called "Strategy Design Pattern" - you can find some good info on it here.

The nice thing about "Strategy" is that it lets you define a family of algorithms and then use them interchangeably without having to modify the clients that use the algorithms.

like image 30
Esteban Araya Avatar answered Oct 06 '22 18:10

Esteban Araya