Wednesday, May 18, 2011

Naming convention : Use named constants for array sizes

It's useful to define constants for the number of rows and columns. The reason named constants can better code is that these numbers may represent part of the problem domain and they will be used in other parts of the code. If a change is every necessary (eg, the number of teams in the Big Ten), changing one named constant will change all parts of the program. Each numeric "constant" should only appear once (the "DRY" principle).

static final int ROWS = 2;
static final int COLS = 3;
. . .
int[][] board = new int[ROWS][COLS];

Many row and column indexes (indices is the traditional English plural, but many prefer the more modern indexes) have a meaning, and aren't just simply arbitrary numbers. The following example might be used to represent the number of accidents on by day of the month and the hour of the day. See programming problems below for some examples using this array.
static final int DAYS  = 31;
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];

No comments:

Post a Comment