According to the principle of separation of concerns, a class should have a single, well-defined responsibility. Usually though it's not straightforward to define what is a single responsibility, there are no golden rules for that. Naming of classes can give useful hints: a class name should indicate its responsibility. If it's difficult to name a class, it often indicates bad design. Maybe the class is overloaded, doing more than it should.
class MyClass {
public static int myMethod(int x, int y) {
return x + y;
}
}
Notice how code readability improves by better names:
class Calculator {
public static int add(int x, int y) {
return x + y;
}
}
The class looks fine, responsible for a single thing. Let's take a look at the next one:
class WhoKnowsWhatTheNameShouldBe {
public static int add(int x, int y) {
return x + y;
}
public static String helloWorld() {
return "Hello world!";
}
}
The class is clearly overloaded, having 2 responsibilities having nothing in common. It would also be quite challanging to find out a proper name for it. Often classes fulfilling too many different purposes are named very genericly, like "Utility". Such classes smell and are almost always bad, since they don't have a well-defined responsibility and their names don't indicate anything. As a result eventually all kinds of "utility" code finds their way into them, leading to even more chaos.
Read the next guide: encapsulation