Everything has a cost, and sometimes the benefits aren't worth what you have to pay for them. All abstractions have a cost, either in runtime speed, development speed, or brain-cell demands. Part of the craft of software development is having a key eye where the benefits are worth it.
Hardcoding things is the easiest upfront means of putting data into a program. It's simple to do, but its cost is the difficulty of changing the code. It's also basically the fastest way you can get at the data, and it is virtually guaranteed to work every time without exception. Only people programming space probes and pacemakers have to worry about it not working.
On the other hand, say you put the data into a file or database. Now you have a relative ton of the additional work of figuring out how to get at that data. If you are using a config file, you now have to handle the file being missing, and dealing with that. What if users want defaults if they don't have a configuration? Where do you store the defaults? Where do you store the data that says where to find the file? The rabbit hole can do deep indeed. All those questions have to be answered. Hardcoding has none of those.
The more abstractions you pile on the more places bugs can lurk, the trickier it is to test, and the harder you have to think to understand what is taking place in your program.
Sure, DB libraries, OEMS, config file libraries can make some of that work easier, but they will all without a doubt be more work, more code, and more places to go wrong than a hardcoded array.
So you have to evaluate what's appropriate. I can't give you an answer you can mechanically test because so far its a judgment call only us humans can do. You need to evaluate how likely the data is to change, how expensive dealing with that change is going to cost, against the cost of dealing with the abstractions. Like many programs, you'll find a mixture of data hardcoded, in flat files, and in a database, for any reasonably defined program.
Your example code using a bunch of yield statements is one of the most extreme examples of "when all you have is a hammer, everything looks like a nail" that i've seen in a long time. When the answers come in, I think you should read them and think hard about whether a given abstraction you are using is appropriate for the task at hand, as your usage and defending that design means you still need to develop that sense.
yield
statements – Ben Cottrell Nov 29 '17 at 22:40private static readonly
collection for lookup data is fairly normal. If I were reviewing code like this, my main issue with the usage of theyield
statement is that it's an unconventional way of writing a constant lookup table (See Principle of Least Astonishment ) - Also, you can have random access with an Array / List / Dictionary / etc. Theyield
keyword doesn't provide random access. – Ben Cottrell Nov 29 '17 at 22:50