29

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!

6
  • 8
    If you have persistent state, then by all means make a class.
    – Kerrek SB
    Dec 4, 2013 at 10:02
  • a rule I find helpful is to always pass parameters as function arguments (because 99.9% of bugs come from manipulating data in shared state) - however classes do have their uses still
    – Jimmy
    Dec 4, 2013 at 10:05
  • 1
    Don't know if it's idiomatic, I do like this all the time, for exactly the same reasons. And it's a convenient conversion from an initial rough variant of the algorithm with global variables :O
    – chill
    Dec 4, 2013 at 10:05
  • 1
    the random number generating engines of <random> are a good example of algorithms that encapsulate state in a class. Dec 4, 2013 at 12:07
  • "algorithm" is a noun, hence, an object. Dec 4, 2013 at 13:34

7 Answers 7

34

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.

2
  • I like that. Hm, I only see that helper arrays calculated at the beginning of the algorithm cannot be stored "globally" (global to all sub functions of the algorithm) but have to be passed by parameter and as return value (in the functions that calculate these helper arrays). I am not sure if that is a real problem but it still sums up to additional code that I would not have in a class case.
    – IceFire
    Dec 4, 2013 at 10:27
  • 2
    @IceFire generally that is not a problem. In fact, functions which only operate on their inputs, and not on any additional state like fields (i.e. Pure Functions), are generally considered easier to understand and "cleaner". They're also easier for the compiler to understand and optimise.
    – MikeFHay
    Dec 5, 2013 at 19:52
16

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.

7
  • 3
    Good answer. In fact, I might go and stress that the data and the algorithms should become the implementation of a class that exposes the higher-level logic. E.g. rather than having an "algorithm that binary-searches a tree", make a high-level "map", etc.
    – Kerrek SB
    Dec 4, 2013 at 10:08
  • @KerrekSB Yup, if it's an algorithm that can be made to express a high-level concept, I 100% agree. OTOH, I imagined this more like "computing the ODE integration" inside a complex simulation framework. There, I'd say the computation is the higher-level logic. Dec 4, 2013 at 10:11
  • I would definitely say that in my case the computation itself is the highest-level logic. The level above is a business context that has no representation in my code. Of course, if there was a higher level, I would consider making a class out of it.
    – IceFire
    Dec 4, 2013 at 10:32
  • +1 I've found that this approach combined with virtual inheritance is one of only a few manageable approaches when dealing with multiple algorithms that implement the same computation spec.
    – Mysticial
    Dec 4, 2013 at 15:53
  • 2
    I believe you are wrong. It’s common (by people mimicking Java) – but not idiomatic. A class has an interface. Having a class with only one method is idiotic – you’ve reinvented a function. Statefulness is properly represented by a closure, not a class. Now in C++ there’s a special case for this because until recently it didn’t support closures as a language construct and people thus worked around it via a functor – a structure whose interface mimics a function. That (and only that) is okay and idiomatic. Dec 4, 2013 at 21:29
6

If the abstraction for the client code is an algorithm, you probably want to keep a pure functional interface, and not introduce additional types there. It's quite common, on the other hand, for such a function to be implemented in a source file which defines a common data structure or class for its internal use, so you might have:

double calculation( /* input parameters */ )
{
    SupportClass calc( /* input parameters */ );
    calc.part1();
    calc.part2();
    //  etc...
    return calc.results();
}

Depending on how your code is organized, SupportClass will be in an unnamed namespace in the source file (probably the most common case), or in a "private" header, included only by the sources involved in the algorith.

1
  • In the case of classes, I would definitely use this kind of abstraction, too, agreed!
    – IceFire
    Dec 4, 2013 at 10:36
4

It really depends of what kind of algorithm you want to encapsulate. Generally I agree with John Carmack : "Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function."

3

It really boils down to: do the algorithm need access to the private area of the class that is not supposed to be public? If the answer is yes (unless you are willing to refactor your class interface, depending on the specific cases) you should go with a member function, if not, then a free function is good enough.

Take for example the standard library. Most of the algorithms are provided as free functions because they only access the public interface of the class (with iterators for standard containers, for example).

3

Do you need to call the exact same functions in the exact same order each time? Then you shouldn't be requiring calling code to do this. Splitting your algorithm into multiple functions is fine, but I'd still have one call the next and then the next and so on, with a struct of results/parameters being passed along the way. A class doesn't feel right for a one-off invocation of some procedure.

The only way I'd do this with a class is if the class encapsulates all the input data itself, and you then call myClass.nameOfMyAlgorithm() on it, among other potential operations. Then you have data+manipulators. But just manipulators? Yeah, I'm not so sure.

3

In modern C++ the distinction has been eroded quite a bit. Even from the operator overloading of the pre-ANSI language, you could create a class whose instances are syntactically like functions:

struct Multiplier
{
    int factor_;

    Multiplier(int f) : factor_(f) { }

    int operator()(int v) const
    {
        return v * _factor;
    }
};

Multipler doubler(2);
std::cout << doubler(3) << std::endl; // prints 6

Such a class/struct is called a functor, and can capture "contextual" values in its constructor. This allows you to effectively pass the parameters to a function in two stages: some in the constructor call, some later each time you call it for real. This is called partial function application.

To relate this to your example, your calculate member function could be turned into operator(), and then the Calculation instance would be a function! (or near enough.)

To unify these ideas, you can try thinking of a plain function as a functor of which there is only one instance (and hence no need for a constructor - although this is no guarantee that the function only depends on its formal parameters: it might depend on global variables...)

Rather than asking "Should I put this algorithm in a function or a class?" instead ask yourself "Would it be useful to be able to pass the parameters to this algorithm in two or more stages?" In your example, all the parameters go into the constructor, and none in the later call to calculate, so it makes little sense to ask users of your class make two calls.

In C++11 the distinction breaks down further (and things get a lot more convenient), in recognition of the fluidity of these ideas:

auto doubler = [] (int val) { return val * 2; };

std::cout << doubler(3) << std::endl; // prints 6

Here, doubler is a lambda, which is essentially a nifty way to declare an instance of a compiler-generated class that implements the () operator.

Reproducing the original example more exactly, we would want a function-like thing called multiplier that accepts a factor, and returns another function-like thing that accepts a value v and returns v * factor.

auto multiplier = [] (int factor)
{
    return [=] (int v) { return v * factor; };
};

auto doubler = multiplier(2);

std::cout << doubler(3) << std::endl; // prints 6

Note the pattern: ultimately we're multiplying two numbers, but we specify the numbers in two steps. The functor we get back from calling multiplier acts like a "package" containing the first number.

Although lambdas are relatively new, they are likely to become a very common part of C++ style (as they have in every other language they've been added to).

But sadly at this point we've reached the "cutting edge" as the above example works in GCC but not in MSVC 12 (I haven't tried it in MSVC 13). It does pass the intellisense checking of MSVC 12 though (they use two completely different compilers)! And you can fix it by wrapping the inner lambda with std::function<int(int)>( ... ).

Even so, you can use these ideas in old-school C++ when writing functors by hand.

Looking further ahead, resumable functions may make it into some future version of the language (Microsoft is pushing hard for them as they are practically identical to async/await in C#) and that is yet another blurring of the distinction between functions and classes (a resumable function acts like a constructor for a state machine class).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.