- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
If you can't switch a string in your language, I quite like it! Although something more like,
Admin
It seems like a reasonable thing to do when you're worried about the length of command-line arguments, or weird command-line injection attacks. This way all the programmer had to worry about was the security of the hashing function (which, in Java, should be fine). And it probably saves some time, I'd guess that hashing and comparing integers is faster (and safer) than string comparison.
Admin
I think it might be because java has become less dense than it used to be.
Admin
Here's the C/C++ version..
I passed this on to a friend of mine who now serves as a CM and--oftentimes--code reviewer. He shared the following lead-in of "platform independent C++ code" that operates the same way (get a number and then use a switch)...
long value = ((long)((void*)&word)); //word is a char[5]
Admin
Admin
The guy should have used a Visitor pattern, easily.
Admin
switch(strcmp(arg,"foo")) { case 0: { stuff } break; default: switch(strcmp(arg, "bar")) { case 0: { more stuff } break; default: ...
though, actually, your teacher does have a point. Did you suggest using a binary-search structure of if statements? That can counteract the main reason if-else-if-else is bad (and, yes, it is, even in those cases) for cases when switch won't work.
Admin
Quick! Which weighs more, a gallon of bricks or a gallon of feathers?
What you're suggesting is that you shouldn't ever be allowed to say one bulk substance is "heavier" than the other.
Admin
If you want to be clever with a question like this, you should probably use an actual weight unit. A gallon is a unit of liquid volume. I imagine if you filled a 1-gallon milk jug with bricks, it would weigh substantially more than the same jug filled with feathers.
Admin
I actually got apologized to by one of my teachers in second grade when she looked up the "Oxford comma" (putting a comma before the "and" at the end of a list of three or more items) and found out that it was perfectly valid, if optional. She'd insisted it was wrong. (Not that I knew to call it "Oxford comma" back then....)
Admin
You write that as if sofas, pretzels, and beer aren't great things.
Kids--when will they ever learn?
Admin
Maybe he is hiding from the decompiler. When it compiles, it will look like any other compare. You guys know the languages posted on the thedailywtf isn't always the language the code arrived in.
Admin
" "What's wrong with if else if else if else if else if or some kind of mapping ?"
"If else if else if else hoses the pipeline a lot with branch instructions." "
The switch statement would also have the branch instructions when compiled into machine code. The only difference is how the high-level-langugage constructs look before they're compiled.
Admin
" "What's wrong with if else if else if else if else if or some kind of mapping ?"
"If else if else if else hoses the pipeline a lot with branch instructions." "
The switch statement would also have the branch instructions when compiled into machine code. The only difference is how the high-level-langugage constructs look before they're compiled.
Admin
Admin
Admin
I can't believe everyone thinks this is whacked code. Hashing strings before entry into a case statement is a common construct when there are a huge quantity of strings that must be compared. The overhead of the hash function is small compared to the increased speed delivered by only having to compare numbers rather than strings. It can also be done before entering an actual search routine as opposed to the simple case statement of the example.
You could argue it will almost always be over-optimising but there are times when it makes sense. It might be a wtf but without knowing what follows the "etc" we have no way of knowing.
As for the concern that the hash function will allow collisions... that's valid but again, we havn't seen the whole routine. Collisions can be checked for when the danger warrants it. This can be done at design time or after passing through the function.
Admin
He's writing in Java. Java does not "switch" on objects (like Strings), because of the various complexities of what is object.equals() for different objects etc.
If I had to write similar code today, I'd use Java Enums, as of version 1.5, which CAN be put into a switch statement and look a heck of a lot nicer.
I'd justify that choice by saying that these are command line arguments--they are tokens of a small fixed known supported set that won't change during runtime. Furthermore, it might be handy to associate other information with them, such as a list of other arguments that are mutually exclusive or are also required, etc.
Go easy on me, I haven't programmed in Java in months... it's been PHP/Python season. Anywho, building off of Adrian's example:
Captcha: "Muhahaha I'm in ur JVM, nulling ur pointerz"
Admin
Admin
We think its whacked out code because its horrible to maintain.
If this is reading in command line arguments, the amount of time saved in using the hashtable algorithm is lost in the cost of starting the program up.
As for collisions, well there is always the danger of them, and they aren't checked. We see the first item is "help". But how do we know that "helpme" doesn't map to the same thing as "format ."?
Admin
Yes, it's not optimum for maintenance and that's one reason why it should only be done when there is a speed issue due to the volume of strings being compared.
There will be zero noticable extra time needed to start the program. The hash function should return in a few milliseconds. If it doesn't, it's not a very good hash function. There will only be a single string to be hashed and typically hundreds of possible hashes to be searched. That's why directly comparing hundreds of strings would be a true wtf.
Collisions aren't checked in the tiny part of the function we were given. You don't know what the real function ends up doing. Anyway, the expected strings can be checked at design time to ensure no collisons. Non-expected strings (bad input) stand only a very remote chance of reporting a false match and checking for collisions is probably not even warranted. For most applications, the fact that a wrong input was entered AND then managed to slip through as something else would not be a huge issue if it only were possible 1 out of a few million times. You'd have to actually be a guy who buys lottery tickets to worry about it. <g> Depends on the application, of course.
I'll admit it's a bit unusual to need it for command line parsing. There aren't usually enough command line options that an app would be interested in.
I've never had to use it and I think I'd first try alternate methods such as a simple binary search but it IS a legit method rather than an automatic wtf.
Admin
Wtf? You are eating your chips with peanut butter? You must be British to pull that.
CAPTCHA: gotcha (how appropriate)
Admin
It looks like the snippet is generated by something like http://www.gnu.org/software/gperf/gperf.html Not a wtf at all imho. Its automatically generated code, nothing that needs to be readable.
Admin
C# compiler will convert a string switch to a hashtable - which means there is no actual wtf here - move along.
Admin
If one were prime, then positive integers would not have unique prime factorizations. 100 for example could break into 2^2 * 5^2, as well as 2^2 * 5^2 * 1 and 2^2 * 5^2 * 1 * 1... and so on. "Itself and one" is a pretty poor definition for prime numbers really.
Admin
More interesting question - Which is heavier a pound of feathers or a pound of gold?
Admin
If you are really worried about using integer based operation to save time, by using some hashing code, i'd recommend this, which is cleaner and has the comparaison optimization:
Note: Before throwing heavy things at me saying you can't compare Strings with == operator in java and that i'm an ass, check the api specification of intern() :) For those not used to java, the == operator compare object instance , not it's content. So, it's generally a bad idea to use == operator to compare String object, but intern() is magic :pAdmin
Admin
Admin
Well, if 1 is a prime number it's easy: 2 = 2×1×1×1×1×1.... Oh, wait. I guess 2 is composite after all. Now, what about 3....?
Admin
A pound of feathers. The pound of gold (troy) is 12 ounces, while the pound of feathers (avoirdupois) is 16.
Admin
I come here like every day at midday to either learn something or have a good laugh but today I almost split my drink all over my keys when I saw this piece of code.
It remembers me of my self always wanting to invent new ways of "improving" certain things...
I thank you allot for the good laugh
Admin
1 cannot be prime or the uniqueness decomposition theorem goes out of the window.....
Admin
Ah. Now, what weighs more, an ounce of gold or an ounce of feathers?
Admin
I was being clever. A weight unit is expected in the standard form of that question, which I inverted. I was pointing out the flaw in refusing to say that cold air can't be heavier than hot air.
What is the difference? You can't really attribute "smart" or "fear" to a non-sapient animal, and from an evolutionary point of view they're the same in this instance. Actually, I'd go so far as to say that a justified fear is always the same as "smart" from an evolutionary point of view.
captcha kungfu
Admin
(obTRWTFITFS: post was eaten. new captcha: yummy)
I was being clever. A weight unit is expected in the standard form of that question, which I inverted. I was pointing out the flaw in refusing to say that cold air can't be heavier than hot air.
What is the difference? You can't really attribute "smart" or "fear" to a non-sapient animal, and from an evolutionary point of view they're the same in this instance. Actually, I'd go so far as to say that a justified fear is always the same as "smart" from an evolutionary point of view.
Admin
It's not magic, it's lots of hard work concealed behind the scenes. How do you think it works, if not by comparing the string to every string already in the string pool, not even only the ones you're testing for.
captcha: stinky
Admin
Random's right... Using String.intern() for strings in place of String.equals() in this case is a WTF unless you literally need to be certain it's the same String object in memory. Unlikely.
Admin
Admin
Every system has a tendency to lower its potential energy -- until it has reached the minimal P.E. state. If a system is not at a minimal P.E. state, it will rearrange itself to lower its P.E. until a minimal is reached.
Now, how do we apply the "physical law" stated in the paragraph above to the example with hot/cold air? Just examine the gravitational potential energy of a system of hot and cold air in a gravitational field. Which state has a higher potential energy: hot air above cold air, or cold air above hot air? Now, you should see why, according to the "law" stated in the paragraph above, cold air sinks and hot air rises: The system is simply rearranging itself to lower its (gravitational) P.E. That explanation simultaneously explains why hot air floats (buoyancy) and cold air sinks (gravitational pull). Indeed, quantitatively, you can compute the force acting on the objects in the system: rate of change of P.E. is equal to the force.
Now, which explanation is better? It's just like asking which side of a coin is better. It's a meaningless question.
Admin
See my other posting. I can explain why oil tends to stay above water (or water tends to stay below oil) by a simple principle: a system rearranges itself to lowers its (gravitational) potential energy until the total P.E. of the system is minimized. It's not hard to realize that the state in which all oil molecules stay above all water molecules minimizes the P.E. of a water-oil system.
Using my "P.E. minimization" approach, I would say "cold air sinks" or "falls" because it has higher (gravitational) potential energy. Is there anything wrong with that? Why are you only giving concentration to the hot air molecules?While "density difference" is the usual approach to this physical phenomenon taught it textbooks, there are alternative approaches to explain the same thing, such as the "minimization of P.E.". Both explanations are valid and useful.
Those who assume that there can be only one approach are too naive.
Admin
The WTF here is that the programmer didn't reuse what's already written, tested and debugged in java.util.HashMap (or String.hashCode()).
Why do you assume it's unlikely to happen?The code snippet shows that it is not using the standard String.hashCode() function in Java. Instead, it is using a customized getHashValue() function. And we know absolutely nothing about this function. This function could be written so badly that it clashes often. e.g. rather than exploiting the full 32-bit range of the Java int type, this function may be returning a value that only varies in its lowest 3 bits. In that case, collision is 1 part in 8, or 12.5%, which I won't consider "unlikely".
But of course, if that hash function is generated by the "gperf" utility, it is likely that the probability of collision is ZERO. In that case, the program is a genius.
Admin
Really? In any configuration?
Try to apply a DC of 100kV across this combination and see if you get smoke!
Even with a simple resistor, you cannot say its voltage drop is fixed. What is fixed for a resistor is the resistance (measured in Ohms), not the voltage drop (measured in Volts). The voltage drop across a resistor is current*resistance. It does depend on current. And how large a current can you create? It depends on the voltage of the power supply.
Admin
2 is not a prime number because it is even. By the same rule, 3 is not a prime number either, as it is a multiple of 3. Neither is 5, etc. In short, prime numbers simply do not exist. This is a brilliant discovery!!!
OK, back to reality. 1 is not a prime number because it only has one positive divisor, not two. This makes sense if you consider the main purpose of prime numbers. They can be used to give a unique decomposition of any number, for example 156 = 2^2 * 3^1 * 13^1. If 1 was a prime, there would be an infinite amount of decompositions possible because you can add any power of 1 without changing the result. Prime numbers are the building blocks for making numbers by multiplication. Multiplying by 1 does not get you anywhere, so it is not considered a prime. Look up "prime" on wikipedia if you don't believe me, you'll find all sorts of other uses for primes where 1 would be completely out of place.
As for 1 not being a composite number, think again. It's just the zero'th power of any prime. (In fact, the prime decomposition is an infinite series of powers of all primes, with only a finite amount of the powers not equal to zero, and in the case of 1 they are simply all zero).
Zero is the only nonnegative integer that does not have a prime decomposition.
As for hot air and cold air: a gas is just a bunch of molecules flying around at high speed, hitting each other and all sorts of nearby surfaces. The "gas laws", using density, pressure, etc., are really just very good statistical approximations. For example, pressure is the average force caused by the zillions of collisions per second of gas molecules with a unit surface. Temperature is related to the average kinetic energy of the molecules. If you increase the temperature, the molecules will hit nearby surfaces more frequently and at higher speed, so we say pressure goes up. Increase the volume (by moving a wall away from the gas) and the molecules hitting the retreating wall will bounce back with less energy, decreasing the average temperature. Believe it or not, it works out perfectly if you do the math, resulting in laws like "p = rho r t" that we all know and love. It's called ideal gas theory (which is itself just a pretty good approximation because gases are not really ideal in reality, collisions are not perfectly elastic, viscosity is not accounted for, etc.).
So the beautiful analogy with lazy molecules going for the couch and energetic molecules going up to achieve great things is the most realistic view imho.
Anyway, what was this thread about again? O, using hashes in a switch statement? Well, the main problem is that a user might type something like "yqsfolihqsd" and the hash just happens to be the same as that for "help", resulting in unexpected behaviour. The problem is unlikely to cause problems (compile errors) during development, though, because all valid commands are likely to have different hashes.
The main missing bit is that, in each case clause, the full string should be verified to make sure it is not a different string that happens to have the same hash.
Other than that, I don't think this is such an extremely bad idea. If you have lots of strings, this may even be one of the most efficient ways of handling them. After all, the C++ standard library does offer hash tables too, doesn't it? Then again, if it's only a few commands, the overhead of the hashing function is likely to offset any gains in switching performance.
Then again, does performance really matter for something that's used only once per application run anyway?
Admin
Admin
i had the same ignorant asshole teacher in 4th grade: she insisted that the answer to "could timmy feel the heat of the burning barn?" was no because that's what the answer key said, and hot air rises:-(
Admin
I found something very similar in some code parsing a xml file recently in our codebase. It did this to match element names with the values of an enum.
It was written based on brilliant advices from one of our worse premature optimizers (who is also unfortunately the lead coder of an important module of the project): "it's the fastest way to do it!!1!")
Those were pretty small xml files containing only a few elements by the way.
Admin
Simple: get a 5 megaohm resistor. V=IR. R=V/I. A LED has a ~2V drop and requires ~20mA. R=100000/0.02=5000000. Hows this any different? :) Of course this is ignoring the (im)practicalities of pumping that much voltage through such small devices, and that the resistor would have to disipate 2kW (P=VI) to get the voltage to drop that much. A very long cable should do it!
(Sorry if my maths is off, it is past 2am here and I should have been in bed hours ago but I sometimes get stuck reading interesting websites)
o---VVV---|>|---o is the same as o---|>|---VVV---o for a given problem. (Mmm ASCII art)
Admin
Yes, but even though that teacher was douche, he inadvertently taught you a lesson. Many authority figures are morons and your best bet is to find a way to circumvent them to get to the real solution.
Admin
I've inherited some code that did something similar in C for long lists of nested switches. It's far more maintainable, but it is still kinda perverse:
Compiler catches collisions of the hand-coded case hashes, but "foo", "oof" and "nog" are indistinguishable. Fine if your inputs are constrained to a known valid set.