martes, 8 de enero de 2008

3 instance variables at most

One message that is very hard to get through is that all classes should have 3 instance variables at most.
Why limit the number of instance variables and why 3?
What if you need more?
Let me look at this another way.
Why do you need more then 3?
Why can't you group variables into objects that make sense?
This is very important. While it is rather easy to constraint method length to 10 lines, and to constraint the number of methods to 10, to constraint classes to only 3 instance varialbes seems almost impossible.
Yet, this is the most important thing to achieve, just because it is so hard to achieve it will give a competitive advantage if you do.
Which advantage?
More clases!!!
Having more classes shouldn't be an advantage per se. But if you test every class using JUnit, your code will be better tested.

Which code looks clearer?

class Form
{
String name;
String company;
String address;
int age;
String companyAddress;
String phone;
String companyPhone;
}

Instead of that, consider this:

class Form
{
Client client;
Company company;
}

class Client
{
String name;
String address;
int age;
String phone;
}

class Company
{
String name;
String address;
String phone;
}

Only the Client class has more than 3 instance variables. But address and phone can be stored together:

class AddressPhone
{
String address;
String phone;
}

class Form
{
Client client;
Company company;
}

class Client
{
String name;
AdressPhone addressPhone;
int age;
}

class Company
{
String name;
AdressPhone addressPhone;
}

Isn't this code clearer?

No hay comentarios: