In the existing responses, I missed cohesion in the code.
From the page of disambiguation of the entry Cohesion, in Wikipedia in English, we can see that cohesion is a "measure of relationship between parties". There is even an entry on code cohesion:
Cohesion (computer science), a Measure of how well the Lines of source code Within a module work Together
In free translation (emphasis added):
Cohesion (computer science), a measure how well the lines of the source code internal to a module work together
In the examples, it did not take precedence for the cohesion of the code, but for its coherence. There was no strong relationship between the size of the vector and the amount of iteration elements. If there were any change in the size of the vector, to maintain coherence, it would also be necessary to edit the limit of the iteration. This is due to the lack of cohesion between vector size and iteration.
To give the code greater cohesion, we have some possibilities. One of them is to put in a constant the size of the vector, calling it whenever it is necessary. But my favorite is to ask the vector itself what is its size, through numerosAleatorios.length
, an attribute that provides the size of the vector in question. More details in this question.
I adapted the code from reply by @Maniero to illustrate the cohesion;
package gerarOrganizar;
import java.util.Random;
public class GerarOrganizar {
public static void main(String[] args) {
int[] numerosAleatorios = new int[100];
Random geradorRandomico = new Random();
for(int i = 0; i < numerosAleatorios.length; i++) {
numerosAleatorios[i] = geradorRandomico.nextInt(250);
System.out.println(numerosAleatorios[i]); //deixei para você ver funcionando
}
}
}
Increasing the cohesion of the Code is considered a good practice, because when used correctly it will help in maintaining the code at a later time. You are not required to use it and also it can be negative if you want to increase the cohesion of a code just to make it more cohesive, without actually facilitating its maintenance.
You may well have an extremely non-cohesive, yet functional and coherent code, but this usually implies being extremely disciplined (the larger the code, the more discipline needed to keep it consistent).
You are trying to access element 101 of the array that has only 100. When you set
new int[100]
can access maximum ranF[99] or will be out of bounds. PSfor(i=0;i<100;i++)
and I also suggest trading forSystem.out.println
– DeMarco