Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ever appropriate to leave the 0 index of an array empty to correspond to real values in the program's front-end?

Tags:

java

arrays

I am creating a game with multiple players between 2 and 8. I could use an array from size 8 to fit 8 players in, but I could also create an array of size 9 and leave all the calculations necessary to convert a number to and index.

For me it feels sillier to do many simple calculations like int index = playerNumber - 1 then to deal with the fact that arrayExample[0] is not being used. Is this rare to actually see this being used in code?

like image 970
Joop Avatar asked Dec 19 '22 05:12

Joop


1 Answers

Although there is nothing wrong with leaving some array elements unused, I think that using an array in that way shows a deeper problem with the design: it is reusing a player number, which belongs to the view portion of your program, as an index into an array, which belongs to the model portion of your program (in MVC sense). This is fragile, because if you change player numbers to, say, player names or player colors, you would have to change the indexing scheme as well.

That's why I would recommend treating array indexes and player numbers as belonging to different domains that do not intersect.

like image 76
Sergey Kalinichenko Avatar answered Apr 28 '23 09:04

Sergey Kalinichenko