Rule Definition
Utility classes are not meant to be instantiated because all the functionalities they provide are accessible without instantiating the class. Instantiating those classes means that the developer misused the class. It also consumes memory unnecessarily. Providing a private default constructor ensures that the class cannot be instantiated.
Remediation
Two possibilities:
- Add a private default constructor to ensure that the class can't be instantiated. This constructor only needs to be declared, not defined, since it will never be used.
- Use a dedicated namespace instead of a utility class in order to classify related functions inside a named entity.
The namespace solution is usually to be preferred, because:
- A namespace can be extended to another file
- A using directive or using declaration can ease the use of functions in the namespace if there is no name conflict
There are cases when the namespace is not suitable, especially when the class is to be used as a template parameter (for instance, a trait class).
Violation Code Sample
class MyUtilityClass
{
public:
static bool MyUtilityFunction1()
{
//Do Something Usefull
return true;
}
}; // VIOLATION
Fixed Code Sample
It is possible to correct this violation by making the utility class non instantiable:
class MyUtilityClass
{
public:
static bool MyUtilityFunction1()
{
//Do Something Usefull
return true;
}
private :
MyUtilityClass(); // FIXED: Avoid instantiation of the class. No definition
};
Or by using a namespace instead:
namespace MyUtility {
bool MyUtilityFunction1()
{
//Do Something Usefull
return true;
}
} // namespace MyUtility
Related Technologies
Technical Criterion
Efficiency - Memory, Network and Disk Space Management
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.