Just encapsulate the switch
:
- In the object's class, define
GetMemberVariableAt(int)
and move the switch in there.
- Then, have your client code ask for
object.GetMemberVariableAt(someVariable)
.
If you do this, it won't be all that important that you're using a nasty switch to get to the right member variable, because the switch will be internal to your object's implementation, not smeared across your code. And, you have the piece of mind that you can improve it later with minimal effort, switching to an array or whatever your mind (or your performance requirements, perhaps) desires.
If you don't control the source code of the class of your object, you can still proxy it or put an adapter in front of it, and code to the proxy or adapter.
The solution I am giving here is intended to make it easier to choose between the alternatives that you already offer in your question, by reducing the importance of the ugliness factor.
I should add that between the switch
and an array of member references solution, I prefer the switch
, because data duplication can be a wealthy source of latent bugs and complicated code. If you can replace the member variables with an array internally, I would go for that over the switch
, but if you have to maintain both an array and the fields outside GetMemberVariableAt
, this is data duplication that I would warmly recommend against.