- 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
> $editid = (int) ((isset($_GET[$_GET['action']]) && (in_array($_GET['action'], array('save', 'edit', 'delete'))) ? $_GET[$_GET['action']] : $_GET['id']);
what if $_GET[$_GET['action']] == 0 ?
Admin
Thanks for not tearing me. I didn't want to mean that you would use one-liners everywhere. I'm sorry that you felt offended.
I know there are faults on that code. Part of my code in Java has been rewriten half a dozen times, as I learnt and discovered better ways of writing it, so I don't expect a hastly-written function in a half-forgotten language to be correct.
Actually, I would have preferred some constructive thoughts on why my thinking is incorrect when building that function, because I could learn from them :) Please, could you elaborate on why the thinking behind is incorrect?
Admin
er, way to post your inability to read
ignore me (for now ;)
Admin
<font color="red">(ix.stock_avail = 'X' OR ix.stock_avail > 0)
is a WTF. How the hell do you store both 'X' and a numeric value into same column? (Also this god damn html software is a WTF, it's happily telling me I'm typing in black at the moment but looks pretty damn red to me.)
</font>
Admin
Um, I respectfully disagree. It is not better. One liners like are notoriously difficult for average programmers to read. It is not saving anything in its current form. Multiple lines would really help it out.
Admin
- okay I thought $_GET might be the request object, that make sense to not pass it in then.
- about declaring variables, even in languages that do not require initialization or declaration there is almost always a way to scope the variable. I'd be surprised if PHP did not have this?
- I still stand that stating that "there are no prerequisites" (which is technically untrue) and "there are no exceptions" which is possibly also untrue is useless. I don't want to get into the whole "the code is the comment" argument, but headers such as this are more likely to become out of date quicker as they are not closely tied with the code that is performing them. A comment for example is usually within 1 or 2 lines of the code in question, this header could easily be missed as its farther away. Hence maintenance nightmare.
- not a big deal but you still assume the action key exists as the line $thepar = $_GET['action'] is run before the condition of isset()
- This is why in general I hate languages like this. Being "forgiving of mistakes" is horrible and will cause many many bad techniques. Take IE versus Firefox for example. IE developers are notoriously non-standard compliant becuase they don't know any better, IE allows everyhing!
Admin
Ok, ok, I'll be the first to say it:
It's an optimization!
[6]
Admin
That was my thought.
Admin
Can anyone tell me what sort of language (besides Asm and batch files) doesn't have a switch statement? C, Pascal, Java, they all have one the last time I checked.
Admin
This looks a bit fake to me.
(2 second edit limit? WTF?!?!)
Admin
Enric:
Admin
s/return values/variable types/;
Admin
Way to win the avatar contest!
Admin
Many things missing
for(int i = Paula.SAYS_ZERO; isTrue(i < Paula.SAYS_THREE); i = Paula.increaseBrilliantly(i)){
switch(i){
case Paula.SAYS_ZERO: result = result + "W"; break;
case Paula:SAYS_ONE: result = result + "T"; break;
case Paula:SAYS_TWO: result = result + "F"; break;
default: Paula.shutUp(); break;
}
}
Admin
It never occurred to me, and things like that very often do. I suppose it is because on the surface, it is indistinguishable from total cluelessness.
Sincerely,
Gene Wirchenko
Admin
That is a very big IF.
Ah, the politics of art!
Sincerely,
Gene Wirchenko
Admin
Well, it isn't. It should be
case of x =
5:
do_this
6:
do_that
otherwise:
do_something_else
and you can more clearly see the benefit when it's closer to the original example:
case of relatively_long_expression_that_we_wish_not_to_repeat_many_times =
5:
6:
7:
do_this
8:
do_that
otherwise:
do_something_else
A web search indicates that Python lacks native switch/case syntax (and turns up several interesting alternatives), but that's a separate discussion.
Admin
There are people who persist in the belief that switch/case is a legitimate language construct.
http://www.google.com/search?q=strategy+design+pattern
Admin
Yes, the Pure Programming Language omits any such atrocity. Unfortunately, the language specification is still in draft, and not public. Suffice to say, it is a statically-typed language that enforces the use of appropriate abstractions. The associated API specification is an example.
Admin
Perl doesn't... Switch.pm notwithstanding
http://search.cpan.org/~dconway/Switch-2.09/Switch.pm
Admin
as far as i now switch needs a primitive type value to check against.
well, i don't know what language the code snipplet is from, but for those languages i know a string is hardly a primitive type which is why it is not possible to check it out in switch statement. hence the solution from the code snipplet might be that of a thorough programmer who actually knows how a switch statement works...
Admin
Since languages are sometimes changed before the WTF is posted, we can not rely on that. Some languages do have a powerful case statement that allows the use of strings in the condition. The xBASE family of languages is one group. Another such language is COBOL.
Sincerely,
Gene Wirchenko
Admin
That lazy programmer should at least check the manual when someone told him the hints.
Admin
And you must be relatively new to this board ;)
Admin
somewhat OT for this thread, but what is wrong with for...switch? I do that sometimes when I need to do something a fixed number of times, but when a small part of it is different each time.
Of course, I would never use this if the only thing in the loop is the switch.
Admin
Since a string based switch system basically turns into chained if/else assembler equivalents, it's pretty much a wash as far as I am concerned. Personally I prefer the if/else chain since it is more language transportable.
The true WTF is stupid requirements. An if/else chain is just as efficent (more so in some cases), more flexible, easily more maintainable and it in its simpliest implementation provides identicle functionality to a string based switch.
Yes, string based switches "look" pretty (if you can get around how ugly the switch statement syntax itself is implemented in every language that uses it), but they provide no real improvments, and can actually confuse the flow of data since the execute flow through a switch can and often does contain gotos.
Stupid requirement, stupid fix. Works for me.
Admin
Aren't you the guy that threatens people with physical violence and talks about how big is guns are?
Sincerely,
Richard Nixon
Admin
Djinn, you're wrong. Your statement is no more concise and more difficult to read and follow even for an advanced programmer than this:
switch($_GET['action']) {
case 'delete':
case 'edit':
case 'save':
$editid = (int) $_GET[$_GET['action']];
break;
default:
$editid = (int) $_GET['id'];
}
By reformatting it without linebreaks it has EXACTLY the same character count as yours, so don't bullshit us about how much simpler
and more concise your method is. The comments to explain what it does alone would be longer, whereas this is eminently understandable on a glance. You are the one who is intentionally buying future daily wtf submissions by crowbarring in something better served by other structures, so that you can have the satisfaction of having bent the language to your will. I pity anyone maintaining your code once you leave.
Admin
Python doesn't. Perl doesn't either
And I haven't done much Ruby but I can't recall having seen anything like a switch/case in it's structures either.
Admin
Way to go, mister grammar god.
LOL
Admin
Or should it be:
And aren't you the guy who brags about his grammar, and "expect if from the best" bullshit?
Admin
Simpler and more concise doesn't equal character count. It could be more characters and more digestable. I fear we're getting down to a matter of preference here, but I would much rather see this done in one simple statement. I don't think the comments need to be in the one-line op, and that is much easier read by a decent programmer than the switch statement. Don't get me wrong here, I'm not saying I hate switch, indeed it's a useful construct, but please explain to us all how I'm 'crowbarring in something better served by other structures', when you have a SWITCH, used for MULTIPLE CONDITIONS, when it can easily be put on one or two lines, with one or two conditions, which hardly warrent a switch.
(you failed to see if the key exists, btw)
Admin
Not to worry; this one is easy to fix. I think Mr. Trump and I are of one mind in this: "You're fired!"
Admin
poor kid ... must be terrible ....
Admin
More than one way to skin a cat, of course.
case @params['action'] when 'edit'; editid = @params['edit'].to_i when 'save' editid = @params['save'].to_i when 'delete' editid = @params['delete'].to_i default editid = @params['id'].to_i end
id_key = case @params['action'] when 'edit'; 'edit' when 'save'; 'save' when 'delete'; 'delete' default; 'id' end editid = @params[id_key].to_i
if ['delete','edit','save'].include? @params['action'] editid = @params[@params['action']].to_i else editid = @params['id'].to_i end
id_key = ['delete','edit','save'].include?(@params['action']) ? @params['action'] : 'id' editid = @params[id_key].to_i
editid = @params[@params['action']].to_i if ['delete','edit','save'].include?(@params['action']) editid ||= @params['id'].to_i
Drum roll, please!
@params[@params['action'].find('id'){|x| ['delete','edit','save'].include? x }].to_i
Admin
Since it's just a matter of preference, let me tell you this: if you think cramming a lot of code on one line with no comments makes it more readable, then you are a l33t hax0r, but *not* a programmer.
Admin
That sentance doesn't even make any sense. A matter of prefrence has nothing to do with you trying to insult me with l33t hax0r. You're crossing the line here without bringing anything to the discussion. You, sir or madam, have represented yourself as the script kiddie here, not I. Furthermore, since when did the ?: construct become a lot of code? The only difference between $a=($b ? $c : $d) and what I have is $a=(($b && $c) ? $d : $e). It's one extra condition. It's not a lot of code, and if you need comments to make it any more readable than 4+ lines of a switch, you need more experience with ?:.
Seriously, is it just me? Am I the only one here that thinks &&?: is not poor practice, and in fact quite readable and concise?
Admin
Well, you're the one advocating unreadable code as being "better", Mr. Easily Offended. I didn't even post a code example.
You didn't get the point. There's a difference between
$a=(($b && $c) ? $d : $e)
and
$editid = (int) (isset($_GET[$_GET['action']]) ? $_GET[$_GET['action']] : $_GET['id']);
The second doesn't even fit on one line. How wide is your editor window? And how about having that code burried inside 2-3 indentation levels? The ternary operator is very cool, but the situations where it's usage is shorter and clearer than "if... else..." are few and far apart.
<sarcasm>Of course, it's all a matter of preference...</sarcasm>
Admin
Apparently you have never heard of the famous set of books titled "The Art of Computer Programming".
http://www-cs-faculty.stanford.edu/~knuth/taocp.html
Admin
Yeah, I was about to say - the issue is not &&?: itself, but the length of the inputs, and their similarity to one another.
Now if you split it up into a couple extra lines, like so:
$editid = (int) (isset($_GET[$_GET['action']])
? $_GET[$_GET['action']]
: $_GET['id']);
then it's at least a little better.
Admin
There's lots and lots. C, Pascal and Java are all Algol-derived languages, so it's no surprise they all have it. Apart from the languages that have already been cited, other switch-less languages are Lisp, Fortran, Smalltalk, and Scheme - all fairly old, established languages.
Admin
Um... no. Quite the other way round: a switch statement can be compiled into a branch table or use binary search, and be MUCH more efficient than an if/else chain. Of course, this really only matters when you have a LOT of cases, which is really bad code, no matter whether it's done with switch or if/else.
Admin
Hello, Djinn, DrJames: I took so much time to answer because I went to sleep. It's 10AM right now here.
Normally, as the code matures, the headers and the code gets more in sync. When I'm calling the same function from several different places, it's difficult to keep track of what the function is supossed to do in every case, that's why I keep small notes of what it returns on what circunstances. I'm the only programmer here, and I can't remember all the freak cases. Even id the headers are out of code, I still find them useful, because I can see how the code has evolved, comparing the differences between code and headers.
DrJames, you're right about the scope. The $_GET variable is not accessible from inside the function. I need to call "global" first or use $_GLOBAL[$_GET] or some similar construct. You're also right about checking the correcteness of "thePar". In the university, I have been teached to use P and Q, and I have found then useful for complex programs. For small functions with clear code, they are overkill. This function would probably not need them.
Normally I don't add those headers until I'm forced to by the complexity of the program. Also, if a function is small and unimportant then it may change radically very easily. Complex functions that play vitals roles in a program need to be changed ery carefully, or you can break several freak behaviours of the program in some obscures places.
I would say that are no pre-requisites, because I define the behaviour for every possible entry and circumstance. Of course, technically, there are still pre-requisites, the "trick" is ignoring them if they don't affect the function's behaviour. $_GET always exists, so I don't need to pre-requisite, and the functions will still return -1 if $_GET is completely empty, which is correct behaviour, according to the post-requisites (I guess I have taken too many CS classes on programming theory).
djinn, thanks for the comments. You're right, I need to declare the "$temp" variable outside the if block. I have gotten too used to bash, where you can declare variables anywhere and they are all global. Mind you, when I program I make scope mistakes all the time :( You're right in that "thePar" is acrappy name. It's a variable, but I forgot the "$" in front of it. Would "$action_key" be a more correct name? At first, I was going to call it $temp2, but that was too crappy even for quick&dirty throw-away code :)
Also, I declare the array at the start of the function so it is easy to find and change. This is a vice I have gotten from Java. I have gotten used to declare those as static arrays so the program does not have to build them at every run of the program and it runs a bit faster. Anyways, my experience is that in my programs that kind af arrays get re-used everywhere on the long term. If it is a small piece of code that is never going to change, then by all means us an inline array. I have gotten used to declaring separate arrays because my programming style uses them all the time. So declaring array as global static in some header file or class from the very first moment makes it's easier to re-use them. Either that or
first making it inline,
then placing it in a variable because I need to use it in a different place,
later placing it in some global class because I need to access it from more than one function,
and finally passing it by parameter to every function so I can use different arrays of actions depending on circumstances.
$actionsAdmin = array('list','save','delete','create'); $actionsUser = array('list','save','delete_his_own','modify_his_own','create'); $actionsVisiter = array('list');
//decide allowed actions depending on user permission // you only need to do it once at the top of the page $validActions = actionsAllowed($userPermissionLevel);
$id = actionParameter($validActions); if ( $id == -1 ) { die('You aren't allowed to do this action.'); }
//here we pass an inline array $id = actionParameter(array('list','create'); if ( $id == -1 ) { die('Here you are only allowed to list or create.'); }
//no need to check again the user permission because we // already know all valid actions in this context if ( canDo('delete',$validActions) ) { // //deleting code // } else { print('You aren't allowed to delete here. Try using a different login.'); }
//etc...
Djinn, Sorry that we don't think the same way. I have nothing against one-liners and they are useful many times. I just avoid them always and try to create more generic constructs.
Now, of course, you'll have to check that the return value is different from -1 to see if the function worked correctly. In the WTF code, it assumed as prerequisite that either 'action' or 'id' variables existed. I think that he should have written it somewhere, as a guide to other programmers!
Admin
What kind of a site dedicates itself to a cynical look at other people's errors? Who under time and pressure constraints hasn't written code that would not pass the critical eye of the masses? It saddens me theres a site dedicated to picking out problems to people that can't defend themselves. In my minds eye I see a glut of semi-or-barely-capable developers reading the postings, and laughing, and silently thinking "Shit, I've written code like this before, but yet I'll sit back and mock a bit more and hope mine doesn't appear here". Everyone here a seasoned veteran of coding? I don't think so. Everyone here perfect? No. Sure, there's some horror code out there (like the code in this posting), but shamelessly picking at every bit that comes along is just pointless, non-interesting, and imho morally retarded. I hope people reading the site walk away feeling a bit dirty, because they should, they're partaking in a pointless excercise of mockery and denegration.
Admin
Let me play wise-ass and point out some factual mistakes:
Ah yes. Scopes. PHP doesn't do very much of it. Actually, you only have global scope and (function) local scope. This code works. So does this:
Happily prints "Tis so".
No you don't. $_GET is a thing called a "superglobal" in PHP, which means that it's global, but also directly accessible from any scope. Other superglobals are $_POST, $_SERVER and $GLOBALS (not $_GLOBAL). And you'd need to write $GLOBALS["_GET"].
In fact, the superglobal $GLOBALS contains itself, so to access a GET variable called "foo", you could easily write something like this:
echo $GLOBALS["GLOBALS"]["GLOBALS"]["GLOBALS"]...["GLOBALS"]["_GET"]["foo"]
Hehe. Isn't PHP fun? :)
Admin
Most (many? most I've seen) functional languages use a more powerful pattern matching system instead of a switch/case system, too. It's more of a feature of C-derived languages.
Admin
It's technically correct, which is the best form of correct
Admin
Oh, one comment. See that long farragous message I just wrote? This is what my code looks like and that's why I need P and Q. Learning what my code does at one glance may be a bit chellenging.
Looking at this piece of real code,
what does "extract" is supossed to do???? I can't call it "extract_var_from_db_taking_into_account_suggerences_and_content_and_dump_on_repetitions"
How I am supossed to keep track of all of this without at least some headers? I prefer an out-of-date header to no headers.
I don't need one-liners. My "normal, extendable, OOP-oriented" code is already hard enough to track :) Inside some of the functions there are already several one-liners, but they appear only once and changing them changes the behaviour all across the application.
This is not a critique to you, djinn, you're right that experienced programmers should be able to read one-liners, but I still think that expanded if-elses and defining variables first is more readable always. As my code becomes more complex, one-liners become a problem.
Yes, "editable" should be an Enum, not a String. LooksLike and AnswerType are already Enums. Yes, in Java Enums have constructors, fields and methods. Yes, this is a pain to change because the important code is spread over 3 different files and is called from many different files taking many different arguments.
Ouch! Another too long message :(
Admin
Ahem, gets called like this:
Admin
Lisp has 'cond' which is a generalized switch, FORTRAN has a computed GOTO which can act as a switch (with some contortions), I don't know about SmallTalk and Scheme - isn't that very much like Lisp?