Background:
I am having a discussion with a friend regarding the correct way to refer to elements within a 2D array for something I’m designing. I was unhappy with using XNA’s Point and Vector2 structs as array references because the properties of them are labelled X and Y.
I created my structs for these, ArrayPoint and ArrayVector2 and called my own properties I and J. My friend thinks this is a massive waste of time, however, I do not like swapping the X and Y references because my maths background has always taught me to use i and j for matrices, e.g using myArray[i, j] instead of myArray[y, x].
What is the best way to deal with this situation?
Is it simply a case of swapping x and y? Or creating your own structs to deal with it how you like? Is it all down to personal preference since this is pretty much all arbitrary anyway?
Listen to your friend!
There are so many reasons this is a bad idea, here are a few:
Your maths background may say
iandj. But for arrays that map into 2D space (eg: a tile map, as opposed to a matrix) thenxandyare actually preferable as they convey semantic meaning that makes your code easier to understand. (ie: you have X and Y axes, not I and J).(Usually the cases where
iandjmake more semantic sense, you won’t be storing the indexers in a struct anyway – they’ll just be temporary locals.)Without a genuine reason, less code is always preferable to more code. Writing and testing code takes up valuable time. Using someone else’s code (like the built-in XNA types) saves you time.
One day you might write some utility function that takes a
Point. If you have two versions ofPointthen you could well end up with two versions of that function. More code and, worse still: duplicate code!“Not Invented Here” is a really, really, really bad habit to get into as a programmer. Learn to live with other people’s code (as long as it works – which, in this case, it does).
No one else does this. Your code is going to confuse and annoy everyone who tries to work with it.
Small performance hit needlessly copying things around. (Plus a few other esoteric things that will have a minor affect on performance.)
(Also: indexing into an array with a
Vector2(floating point) is kinda weird.)