Search code examples
programming-languages

Maximum number of variables in classes


What is the max number? Will my program crash if it exceeds certain number? Is there a standard just like it is 5 for method parameters?


Solution

  • An answer to such a question would depend on the language you are using, but generally speaking, there isn't any limit on the amount of variables or parameters of a method.

    There is a cap on the amount of data you can handle, and that's the amount of memory available to your system, but that's a cap on the size of the actual data held by the variables.

    Having a high number of variables or methods inside a class is not recommended because your code can become unmaintainable very quickly. That is due to the Single Responsibility Principle: your class should be responsible for one thing, and only one thing, and that one thing will rarely need that many variables to accurately represent it's state. In the event that it does, use Object Composition: identify the small structures which have emerged inside the class and break them up into smaller classes, then add references to objects of those classes to the original class, effectively creating a "has a" relationship between the original class and the smaller classes.

    For example, a car has an engine:

    class Car {
        Engine engine;
    };