开发者

Maximum number of variables in classes

What is the max number? Will my program crash if it exceeds certain number? Is there开发者_如何学Python a standard just like it is 5 for method parameters?


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;
};


Your code will become unreadable long before you reach any hard limits set by a programming language, both for variables and method parameters.


This is unlikely to be an issue. Although I would guess that it depends on the language you are talking about,


And why don't you try to code all your program in only one file, and with only one function ? :)

Because it's unreadable, and unmaintainable, so it's full of bugs, and so it will not work very well.

This is a kind of real limit to the number of member variables yes.


Although there is no hard limit, it is never recommended to use large number of variables in a class or method parameters. One can use composition design pattern or inheritance in some cases for reuse. The latter should used sparingly. I would rarely use more than 25 variables in a class or 5 in method parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜