Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class that contains only public functions

I would like to have a class which contains only public functions, For example:

class foo
{
    public:
        int f1(param1, param2) ;
        void f2(param1, param2);
};

The Class doesn't have state, it just manipulate input parameters, Behaves like auxiliary class,

Is it a good design ? or need special pattern for that ? What is the name of the pattern?

like image 737
user3498424 Avatar asked Dec 05 '22 06:12

user3498424


2 Answers

Short answer: use functions inside a namespace.

namespace foo
{
    int f1(param1, param2);
    void f2(param1, param2);
}

However, if your application has a OO design, you should ask yourself why you need a bunch of functions that just manipulate input parameters. Believe me: your code is trying to tell you something :-)

In your snippet of code, you used dummy names (foo, f1, f2, param1, param2), so I cannot guess what your functions do. But maybe your functions operate on the same parameter: in that case you can promote the parameter to become a class.

Before:

bool IsLeapYear( int date );
void IncrementDay( int date, int numOfDays );

After:

class Date
{
    public:
        bool IsLeapYear() const;
        void IncremetDay( int numOfDays );
    private:
        int daysFromOrigin;
};

If your functions take different parameters, instead, you can consider to allocate your functions to existing classes on your OO design (on the assumption you do want a OO design!).

Finally, if your functions are unrelated, you can consider to move each of them in existing classes even as static methods (it really depends on the meaning of your functions).

As for your final question "Is it a good design?", well it depends on what design you're working on:

  • object oriented design: likely it's not a good OO design, but without more context it's difficult to say
  • procedural design: it's ok
  • functional design: it's ok

While this may or may not be a good design according to your paradigm, certainly that's not a good C++ idiom: you should use free functions inside a namespace instead of a class with only static methods.

like image 162
Daniele Pallastrelli Avatar answered Dec 09 '22 14:12

Daniele Pallastrelli


Just make them free standing functions. Not everything in C++ has to be in a class. If you look at the STL, for example, you'll see that it has lots of free standing functions.

like image 37
Sean Avatar answered Dec 09 '22 15:12

Sean