Skip to main content

C++ namespace or static class

Created
Active
Viewed 63 times
6 replies
1

I am developing a library of functions in C++. These functions will be used extensively and repeatedly by me as well as others in the future. Let us say my functions are:

double SphBesselJn(const vector<double>& r, double k);
double SphBesselYn(const vector<double>& r, double k);

Should I use a namespace:

namespace SphFuncs {
    double SphBesselJn(const vector<double>& r, double k);
    double SphBesselYn(const vector<double>& r, double k);
}

or a static class

class SphFuncs {
    public:
    static double SphBesselJn(const vector<double>& r, double k);
    static double SphBesselYn(const vector<double>& r, double k);
}

I know both will work. But my question to experienced C++ library developers is: Which one is better ?. I have a feeling it is the former.

I just need feedback from other C++ developers.

6 replies

Sorted by:
79587524
0

Do these functions have side effects or are they pure functions?

79589449
0

Just pure functions. I edited the function names.

79589453
0

It would be good to state that these are pure functions. That is a crucial point.

79588818
0
  • 216.8k
  • 46
  • 279
  • 435

You haven't given enough context.

For example do these functions need to interact with containers or other classes? Is thread-safety relevant and if so do the functions modify any shared resources? Does something need to run/initialize before the functions can be used? And so on.

M1 and M2 are also really poor identifier names and you shouldn't name functions like that.

79589937
0

I changed the identifiers. These functions will be used by other classes. As of now, I am not using anything to do with threads.

Does something need to run/initialize before the functions can be used ? Ans: No

79592670
1
  • 5.3k
  • 4
  • 37
  • 50

I can imagine that at the end of the day, the compiler will optimize it away to pretty much the same machine code.

So what do you find cleaner? A library of functions, or an old fashioned util class? Java code bases are littered with util classes because the language forces you to slap everything in a class. You have the choice to say no.