Level 6 Rule
Origonal Rule Title: AvoidInstantiatingObjectsInLoops
Exceptions: Where the loop is used to create one or
many individual instances that are used outside of the
loop.
Really this Rule is a bit vague, it should be split
into two,
1) AvoidInstantiatingObjectsInLoopsWhereScopeIsWithinTheLo
opONLY
Example of a Failing rule:
Public viod setAllAdminStates() {
:::::
int n=5000;
Node nodes [] = new Nodes[n];
String host = null;
while(n>=0) {
host = getHost(n);
nodes[n] = new Node(host);
nodes[n].connect();
nodes[n].setAdminState(getState(n));
n--;
}
}
//AND the objects created in nodes[] are NEVER used outside of this loop
Correct implementation of this code. Passing the Rule:
Public viod setAllAdminStates() {
:::::
int n=5000;
Node n = null;
String host = new Node();
while(n>=0) {
host = getHost(n);
node.setup(host);
node.connect();
node.setAdminState(getState(n));
n--;
}
}
//Here we are reusing the same Node object with each iteration of the while loop.
HOWEVER;
Sometimes it is required that you may want/need to instansiate objects for use later in a program, the original rule above prevents this.
For example:-
Public viod init() {
:::::
int n=5000;
Node nodes [] = new Nodes[n];
String host = null;
while(n>=0) {
host = getHost(n);
nodes[n] = new Node(host);
i--;
}
}
::::
Then somewhere else, in this class or even another class,
We wish to use those objects previously set up.
:::::
Public void setHostAdminState(int hostIndex,String state) {
:::
nodes[hostIndex].connect();
nodes[hostIndex].setAdminState(state);
:::
}
2) AvoidDeclaringVariablesInLoops
Example of a Failing rule:
Public viod setAllAdminStates() {
:::::
int n=5000;
Node nodes [] = new Nodes[n];
while(n>=0) {
String host = getHost(n);
int adminstate = getState(n);
nodes[n] = new Node(host);
nodes[n].connect();
nodes[n].setAdminState(adminstate);
n--;
}
}
Here you see that the variables “host” and “adminstate” are re-declared every time instead of just being reset. Basically this rule is stating that you should always declare variables outside of loops.
A Correct implementation:
Public viod setAllAdminStates() {
:::::
int n=5000;
Node nodes [] = new Nodes[n];
String host = null; //declared
int adminstate = 0; //declared
while(n>=0) {
host = getHost(n);
adminstate = getState(n);
nodes[n] = new Node(host);
nodes[n].connect();
nodes[n].setAdminState(adminstate);
n--;
}
}
Logged In: YES
user_id=365381
Originator: NO
I have noticed two problems with the AvoidInstantiatingObjectsInLoops rule that I'd like to mention here:
1. If the instantiated object is added to an array or collection, that should not count as a violation unless the array or collection is never used anywhere outside the loop (not quite the same as eeigjon's 1st half)
2. If the instantiated object is non-reusable (e.g. File, Reader, Writer, Stream), that should not count as a violation.