Should data be descriptive of itself? In what cases should it preferably be or not be?
I am not sure how to put this easily into a simple question.
I am just going to use an example.
Say I am sending some parameter to a web browser from a server. The Javascript will know what to do with it. Say it was a setting for some page element that could have 4 different values. I could make it be 0-3, or I could make it be "bright", "dark", "transparent", "none". Do you see what I mean? In one case the data is descriptive.
Now step outside of the realm of web development. In fact, step away from any facet of programming that would NOT require one method or the other, and think of some that would prefer one over the other. Meanin开发者_Python百科g it would be beneficial to the over all goals if it was done in a descriptive manner, or beneficial if it was done in a cryptic manner.
Can you think of some examples where you would want one over the other?
PS: I may need help with the tags on this one guys.
Benefit of the number variant is smaller data size. That can be useful if you are communicating a lot of data or communicating over a restricted bandwidth channel. Also comparing numbers is much faster than comparing strings.
The alternative with meaningful names is beneficial when you need easy extensibility and maintainability. You can see what the value means without using any other translation table. Also you can enable others to add new values by defining some naming rules.
The benefits of using the one strategy over the other is quite simmilar to the benefits of strong vs. weak typing. Values like "bright", "dark" etc. is strongly typed while 0, 1, 2 is weakly typed.
The most important benefits of using strongly typed data is 1) that it is easy for other people to know what the value means and how to use it and 2) that you will get a meaningful, syntactic error early if you use an illegal value.
The benefits of weakly typing is that you may introduce new values without having to change intermediate modules. I.e. you could introduce "4" without changing intermediate modules that don't really have to understand what the value means.
I would definitely go for "bright", "dark" etc.
NB! Some would probably argue that "bright" is a string and so is weakly typed in the same way as "1", but this depends on the perspective.
精彩评论