Using a contrived formula that's difficult to understand or quickly check for correctness to solve a problem whose answer doesn't come from anything mathematical (i.e., the number of days in each month were arrived at arbitrarily, not via any formula) and just happens to work is NOT good style. At best it's cute and irrelevant (and doesn't even work for all of the twelve cases...). Wow.
Edit: also, if you're mapping the month string to an integer anyway, I don't see how you're going to do that without doing basically the same thing as the switches you posted anyway.
> Correctness should be verified by tests not 'looking at the code'.
Tests can prove the presence of bugs, but they are (in general) hopelessly inadequate to prove their absence; and once a test finds a bug, you still have to be able to understand what the code is doing in order to fix the bug.
In practice, code inspections and tests find quite distinct sets of bugs with some overlap, so it's valuable to do both of them. That's why all decent programming processes require both.
(This is probably one of the few cases where you could in fact verify that the code is correct by exhaustive testing — but only by comparing it against a known-correct implementation.)
To be honest your one liner takes me a while to parse and you forgot to close a parenthesis. OTOH It is really hard to read or write that switch incorrectly.
Are you serious? An "abomination"? The switch statement is fine, and using an array [31, 30, 31 ...] would be fine as well. Your 1 line isn't really 1 line because you have to convert the month to an integer anyway, and then the array lookup is even shorter than your solution.
Well done! Could you elaborate on how you came up with 5546 ? Perhaps there's a simpler technique than the one I describe below. btw, this was the technique that I learnt in school -
1. You have 12 months. Ignore February. Then you have 11.
2. The remaining 11 map to either 30 days or 31 days . ie. 30+0, or 30+1.
3. So the object is to write a many-to-one function that maps some members of the set to 0, rest to 1. Add 30 and you get the right answer ie. number of days in that month.
4. So you want to map {1,3,5,7,8,10,12} to 1, and {4,6,9,11} to 0.
5. Write down a 13 bit number. If you rightshift x times and AND it with unity, you get 1.
6. So then, x belongs to {1,3,5,7,8,10,12}.
7. That means the bit in each of those locations must be on. The rest of the bits must be off. That gives you the number 1010110101010, which is simply 5546 in decimal.
IntelliJ IDEA strongly suggests to turn those Strings into constants. And then to turn those constants into an Enum. Oh wait, we could also switch() on Enum values!
http://download.oracle.com/javase/7/docs/technotes/guides/la...