4

Problem Description

I am wondering what is a best practice for classes that start having too many static functions, but no member variables.

class A {
    static void fooA();
    static void fooB();
    static void fooC();
    static void fooD();
    ...
}

/* 
 *   #include "A.h"
 *
 *   A::fooA(); A::fooB(); A::fooC(); A::fooD();
 *
 */

Or

class A {
    void fooA() const;
    void fooB() const;
    void fooC() const;
    void fooD() const;
    ...
};

/* 
 *   #include "A.h"
 *
 *   A a;
 *   a.fooA(); a.fooB(); a.fooC(); a.fooD();
 *
 */

Question

Is it best to just make an instance of the class and access the functions over the instance, or have the static keyword to all the member functions and access them in a static way?

I am asking this because my class has 8 static functions and it just seems visually weird.

hexaquark
  • 883
  • 4
  • 16
  • 20
    Perhaps a namespace would be more appropriate. My general rule of thumb is No state, no class. – user4581301 Jan 13 '22 at 18:07
  • 2
    This sounds like a case for using regular function wrapped in a namespace. – NathanOliver Jan 13 '22 at 18:15
  • 1
    At one time, using a class to hold a lot of associated static functions was *best practices* in C++. Then `namespace` was invented, and that was a much better way to express the intent. – Eljay Jan 13 '22 at 18:17
  • 1
    Related https://stackoverflow.com/questions/70356582/c-are-classes-with-only-static-members-bad-practice-anti-pattern, https://stackoverflow.com/questions/50452161/helper-classes-with-only-public-static-methods, https://stackoverflow.com/questions/1434937/namespace-functions-versus-static-methods-on-a-class – ChrisMM Jan 13 '22 at 18:18
  • 2
    @user4581301 A potentially useful exception would be a stateless class template since you cannot templetise namespaces. Doesn't apply to the question though. – eerorika Jan 13 '22 at 18:25
  • Does this answer your question? [Namespace + functions versus static methods on a class](https://stackoverflow.com/questions/1434937/namespace-functions-versus-static-methods-on-a-class) – SuperStormer Jan 14 '22 at 23:19

0 Answers0