Home > Blockchain >  What is the advantage of a single-function-class over a function?
What is the advantage of a single-function-class over a function?

Time:02-10

I have often encountered classes with the following structure:

class FooAlgorithm {
  public:
    FooAlgorithm(A a, B b);
    void run();
  private:
    A _a;
    B _b;
};

So classes with only one public member function that are also only run once. Is there any advantage in any case over a single free function foo(A a, B b)? The latter option is easier to call, potentially has less header dependencies and also has much less boilerplate in the header.

CodePudding user response:

An object has state that can be set up at object construction time. Then the single member function can be called at a later time, without knowing anything about how the object was set up, and the function can refer to the state that was set up earlier. A standalone function cannot do that. Any state must be passed to it as arguments, or be global/static (global/static data is best avoided for a variety of reasons).

An hands-on example is worth a thousand abstract explanations, so here is an exercise. Consider a simple object:

struct Obj {
   std::array<std::string, 42> attributes;
};

How would you sort a vector of such objects, comparing only the attribute number K (K being a run-time parameter in the range 0..41)? Use std::sort and do not use any global or static data. Note how std::sort compares two objects: it calls a user-provided comparator, and passes it two objects to be compared, but it knows nothing about the parameter K and cannot pass it along to the comparator.

CodePudding user response:

For bigger projects it may be easier to structure your programm using OOP. For a simple program like yours it is easier to use a single function.

CodePudding user response:

Classes introduce a new dynamic to your program -> Better readability, security, moudularity, re-usability.... functions are used to organize code into blocks.

  • Related