Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it idiomatically ok to put algorithm into class?

I have a complex algorithm. This uses many variables, calculates helper arrays at initialization and also calculates arrays along the way. Since the algorithm is complex, I break it down into several functions.

Now, I actually do not see how this might be a class from an idiomatic way; I mean, I am just used to have algorithms as functions. The usage would simply be:

Calculation calc(/* several parameters */); calc.calculate(); // get the heterogenous results via getters 

On the other hand, putting this into a class has the following advantages:

  • I do not have to pass all the variables to the other functions/methods
  • arrays initialized at the beginning of the algorithm are accessible throughout the class in each function
  • my code is shorter and (imo) clearer

A hybrid way would be to put the algorithm class into a source file and access it via a function that uses it. The user of the algorithm would not see the class.

Does anyone have valuable thoughts that might help me out?

Thank you very much in advance!

like image 851
IceFire Avatar asked Dec 04 '13 10:12

IceFire


2 Answers

I have a complex algorithm. This uses many variables, calculates helper arrays at initialization and also calculates arrays along the way.[...]

Now, I actually do not see how this might be a class from an idiomatic way

It is not, but many people do the same thing you do (so did I a few times).

Instead of creating a class for your algorithm, consider transforming your inputs and outputs into classes/structures.

That is, instead of:

Calculation calc(a, b, c, d, e, f, g); calc.calculate(); // use getters on calc from here on 

you could write:

CalcInputs inputs(a, b, c, d, e, f, g); CalcResult output = calculate(inputs); // calculate is now free function // use getters on output from here on 

This doesn't create any problems and performs the same (actually better) grouping of data.

like image 61
utnapistim Avatar answered Oct 05 '22 10:10

utnapistim


I'd say it is very idiomatic to represent an algorithm (or perhaps better, a computation) as a class. One of the definitions of object class from OOP is "data and functions to operate on that data." A compex algorithm with its inputs, outputs and intermediary data matches this definition perfectly.

I've done this myself several times, and it simplifies (human) code flow analysis significantly, making the whole thing easier to reason about, to debug and to test.

like image 45
Angew is no longer proud of SO Avatar answered Oct 05 '22 09:10

Angew is no longer proud of SO