Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is basic DRY violation. The number is duplicated twice and that can get out of sync (as in the example).

I think everyone has coded this way out of expedience and some of us have eventually messed it up too. But you could, for example, use a macro in C to only list the number once. It might not be a trade-off worth making though.

Personally, I've used reflection to do this kind of mapping of enums to functions in a language that supports reflection.



The code was inspired by a piece of Java code that rendered geometric primitives. It was basically case "box": return parseBox(); as you suggested in your other post.

Turning "box" into "parseBox" using string operations and then using reflection to call the right method is an approach I'd consider in Ruby, but not in Java. It breaks IDE features like "Find Usages" and static analysis, and the code to dynamically invoke a Java method is more annoying to review than the boring repetition in my posted snippet.


> This is basic DRY violation. The number is duplicated twice 2 and that can get out of sync (as in the example).

I think it's pretty clear that the number is a placeholder for something reasonable, e.g. making an association between two distinct sets of concepts. You'll still be vulnerable to copy-paste or typo issues.

> Personally, I've used reflection

Now you have two problems (and still have to maintain an association between two sets of concepts).


I don't think most enum-to-function mappings are distinct sets of concepts.

In my own code, I have used the enum name to map to a set of functions related to that enum value. The association is implicit in the name of the enum value and the name of the functions. No way to mess that up like this.

If it was:

    case: KIND_BOX: return parseObjectOfKindBox();
It's no difference. Still repeating "Box".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: