What is the maximum number of instance variables a Java class should have?

Is it good for an OO project to have 20-25 instance variables in a JAVA class, with their getter / seters?
All variables are completely independent. Since I use a class in HBase that represents a column family, so there can be a different number of columns for each row of columns. So I have to add so many variables to this class. I am very curious to know how many instance variables and methods should a JAVA class have?

+4
source share
5 answers

Well, if your class represents data storage objects, then it's fine to go with that. This scheme is common in java beans.

For example, if you have a class that represents an employee in the company, then this is quite common, if the employee has 20-25 attributes.

But if you confuse so many instance variables with business methods, then along the line you will encounter difficulties, since you will not be able to concentrate and focus on business components.

To make it more intelligent in architecture, you can consider Inheritance (subclass) or composition (inner class)

0
source

Trying to have a good OO, it's good to look for a class to have a separate responsibility. Therefore, if you have so many unrelated variables, it sounds like a class does too much.

This will be the "smell of code," and you should consider re-factorizing into several classes.

Its excellent you are interested in good OO. I recommend reading Refactoring and Code Smells.

http://c2.com/cgi/wiki?OneResponsibilityRule will be relative here.

+7
source

It doesn’t matter if you provide low coupling . Assigning so many variables to a class can increase the likelihood of high coupling.

In addition, this may be a sign of low cohesion in your class, as opposed to an ideal situation with a high degree of cohesion.

+4
source

In 20-25 instance variables you should be within the limit, however, I think that 20-25 may be too large. You can try and group them into different classes and reduce the number of instance variables.

Typically, the presence of a large number of instance variables makes the class limited in volume, which is not ideal in a scenario in which you would like to support a solution. Violating it (if done correctly) should increase the reuse of some of your classes.

+2
source

In Java, there are no restrictions on the java instance variable that a class can have. At your request, you can have any number of instance variables.

The key point to remember should be accessible only with the getter and setter methods. The user should not have access to them directly with the name of the instance variable.

Denotes an Instance variable with private modifiers and should provide public methods for accessing and managing them.

0
source

All Articles