• (cs) in reply to RiX0R
    RiX0R:

    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"].

    Hehe. Isn't PHP fun? :)

    There is a configuration setting to make $_GET and $_POST not global, so you are forced to declare it global or pass it :) It's supossed to force you to do "the correct thing".

    In the default configuration, "index.jsp?action=delete" automagically creates in index.jsp a variable called 'action' with content 'delete'. PHP is funny and damn easy.No need to retrieve the variables from the request, because PHP does it for you! :P Of course, this is dangerous because visitors can set any variable to anything in your program.

  • Bill Clinton? (unregistered) in reply to Richard Nixon
    Richard Nixon:
    Gene Wirchenko:
    Alex Papadimoulis:

    For those who "grew up" programming in a language without it, a Switch/Case statement might seem to be a bit foreign. When "transitioning" programmer brought code to a review, O.C. rejected it and requested that he use a switch statement instead of the numerous elseif blocks. The same programmer returned to the next day's code review but didn't quite seem to understand the finer points of the switch statement ...


    I suggest that that transitioning programmer is more than a little clueless.  The first language that I programmed in did not have switch/case either.  When I first read about it, it was simple to see how it worked and simple to use.

    Sincerely,

    Gene Wirchenko



    But Gene, you're so much smarter than everyone else. As evidenced by the fact that you sign all your posts even though your username is displayed prominently next to your posts. I mean, that's operating on a whole different plane of existence and thought. It's not fair to use you as a point of reference as you are so obviously superior to everyone else.

    Sincerely,

    Richard Nixon

    and you're well known to be a tosser, it's been seen on many other posts on this site. Your point?

  • anon (unregistered)

    Seriously, the code is not the WTF. I imagine I wrote the original code. 'switch' cannot do everything 'if' can, so there's probably a reason I used 'if' in the first place. For whatever reason, the code ended up the way it was, as a long chain of 'if' and 'ifelse'. However, it works and is tested.

    And now O.C. tells me, I have to use a switch, because... uhm... because... well, because he says so? I would either turn in exactly the code submitted ("You wanted a switch?! You get a switch!") or implement a refactoring tool, prove it correct (this might take a week or so, at the very least) and then apply "turn-if-into-case" exactly once. ("I had to be absolutely sure not to introduce an error in the transformation O.C. requested.")

    See the WTF? Yeah, stupid code review practice it is.

  • (cs) in reply to Newton
    Anonymous:
    brazzy:
    other switch-less languages are Lisp, Fortran, Smalltalk, and Scheme - all fairly old, established languages.


    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?

    Scheme is a Lisp dialect (nobody uses the original Lisp nowadays, people use dialects built from lisp with structures such as loops already included [Lisp doesn't have anything like while or for loops originally, it only has something like 7 statements anyway], and an OOP implementation). The most common dialects of Lisp are probably Scheme and CLisp (Common Lisp), but there are many more.

    Smalltalk, on the other hand, is a completely different beast (and - as a side note - the language that birthed unit tests thanks to Kent Beck's sUnit, which was later reimplemented in Java by the same Kent, thus spawning jUnit and the whole xUnit legacy).

  • (cs) in reply to Bilbo Baggins
    Anonymous:
    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?

    The general idea is to put up stuff that is absolutely indefensible - where doing it right would be easier and quicker as well as more efficient and clean.

    Anonymous:

    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".

    Your mind must be a sad place then, because what's actually here are people that will quite often admit to having made similar mistakes, and nearly always try hard to find justification for the code besides simple stupidity and incompetence.

    Anonymous:

    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.


    Recognize a bit too much of your own coding practices here? What's more retarded and pointless, making fun of other people's really bad mistakes and discussing how it should be done ideally, or getting all worked up and morally outraged about some totally harmless site on the internet?

  • (cs) in reply to anon
    Anonymous:
    Seriously, the code is not the WTF. I imagine I wrote the original code. 'switch' cannot do everything 'if' can, so there's probably a reason I used 'if' in the first place. For whatever reason, the code ended up the way it was, as a long chain of 'if' and 'ifelse'. However, it works and is tested.

    Last time i checked, the only thing switch/case couldn't do that if/else could was non-equality (not as in "!=", as in "not ==") comparisons. A common operation, but one which doesn't occur in this code.

    On the other hand, switch/case feature fallthrough, which would allow here for a much cleaner syntax overall, and an enhanced readability (compared to the current version, or a version using in_array in order to get rid of the duplicate code)

    And using a switch/case structure prevents you from hitting the "=" comparison issue.

    And now O.C. tells me, I have to use a switch, because... uhm... because... well, because he says so?

    There is a quite cool process that i've known has been in existence for the last few hundreds of millenia (sp?), it's called 'a question'.

    It's widely used when you don't understand the reason for an instruction, it allows you to get more informations about the aforementioned reasons and stop being a dumbfuck

    See the WTF?

    Your idiocity?

  • (cs) in reply to Bilbo Baggins

    Whoa!  Lighten up Francis!

  • (cs) in reply to Enric Naval
    Enric Naval:
    RiX0R:

    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"].

    Hehe. Isn't PHP fun? :)

    There is a configuration setting to make $_GET and $_POST not global, so you are forced to declare it global or pass it :) It's supossed to force you to do "the correct thing".

    In the default configuration, "index.jsp?action=delete" automagically creates in index.jsp a variable called 'action' with content 'delete'. PHP is funny and damn easy.No need to retrieve the variables from the request, because PHP does it for you! :P Of course, this is dangerous because visitors can set any variable to anything in your program.

    I think you're referring to the register_globals configuration option. Yes, disabling this stops the variable $action from automatically appearing your scripts global variables, but this configuration option by no means affects the globality or superglobality of the $_GET or $_POST arrays. (In fact, if they were not global, how would you be supposed to get at them?)

    But you're right, that's what it does and why you should have it disabled.

  • (cs) in reply to jvancil
    jvancil:

    Dude... programming is not an 'Art Form' it is just using tools to accomplish results... no different than using a hammer and a nail to make sure a piece of wood stays in place...

    Class, please repeat after me... "Programming is not an art... "

     


    Funny enough, driving a nail into a piece of wood is not considered an art, but designing and constructing opulent buildings is and always has been. I leave the moral of this up to the reader.

  • (cs) in reply to Savior
    Savior:
    Savior:

    Richard Nixon:
    Alexis de Torquemada:
    Richard Nixon:

    But Gene, you're so much smarter than everyone else. As evidenced by the fact that you sign all your posts even though your username is displayed prominently next to your posts. I mean, that's operating on a whole different plane of existence and thought. It's not fair to use you as a point of reference as you are so obviously superior to everyone else.

    Sincerely,

    Richard Nixon


    Aren't you the Richard Nixon from Futurama?



    Aren't you the guy that threatens people with physical violence and talks about <font size="6">how big is guns are?</font>

    Sincerely,

    Richard Nixon

     

    Way to go, mister grammar god.

    LOL

    Or should it be:
    And aren't you the guy who brags about his grammar, and "expect if from the best" bullshit?



    That was obviously a typo - not a grammatical error.

    Sincerely,

    Richard Nixon
  • (cs) in reply to Newton

    Just as a BTW, I'd like to present a situation where I feel that ?: is better than if-then-else -- Where you're doing the same thing with the result of the conditional, regardless of which branch is taken. For instance, given:

    my ($id, $name, $change, $page) = split /\s*,\s*/, $line;

    (ie $id, $name, $change and $page are the first four CSVs from $line)

    ...you can do the obvious:

    if    (!$id                            ) { die "No id" }
    elsif (exists $types{$id}              ) { die "Id clash" }
    elsif (!$name                          ) { die "No name" }
    elsif ($change ne "+" && $change ne "-") { die "Change not +/-" }
    elsif (!exists $pages{$page}           ) { die "Page nonexistant" }


    ...in which case you can be glad the thing you're doing with all the values is called something nice and short (ie die()). Yes, you could muck about with assigning the results of each of those blocks to $err or something, but then you've got single-use variables floating around, and I prefer to avoid that.

    Instead, I would do:

    CHECK: {
    die
        !$id                             ? "No id" :
        exists $types{$id}               ? "Id clash" :
        !$name                           ? "No name" :
        $change ne "+" && $change ne "-" ? "Change not +/-" :
        !exists $pages{$page}            ? "Page nonexistant" :
        last CHECK                       # escape the die()
    }


    This saves you from an unncessary variable, having to type "die" or "$err =" over and over again, and the - in my mind, unncessary and crossed-eyes-inducing - noise of repeated elsifs and their associated punctuation. Yes, it does involve using loop control to escape from the parameter list of a function to stop it being called, which looks disturbingly hackish, but it's so much easier on the eyes.

    Let's see what y'all think's Evil And Wrong (TM) about this, then. I'm sure there'll be something.

  • (cs) in reply to Scott
    Anonymous:
    Am I the only one who finds the switch statement as nasty as a ternary statement? I've never understood why something like:

    <font class="fixed_width" face="Courier, Monospaced">if x = 5:
        do_this
    elif x = 6:
        do_that
    else:
        do_something_else
    </font>

    is supposed to be "bad", but

    <font class="fixed_width" face="Courier, Monospaced">case of:
        x = 5:
            do_this
        x = 6:
            do_that
    otherwise:
            do_something_else
    </font>

    is supposed to be "good."




    It's not for that case that elseif is considered bad...It's for the case where you have 20 more elseifs, and a few nested if statements. Besides that, switches are generally more readable; your pretty formatting makes the elseif look just as readable as the switch, but with an elseif block, you're generally counting {}'s, whereas with a switch, you're just going between big obvious breakpoints.

  • Karl (unregistered) in reply to masklinn
    masklinn:

    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.



    It does:

    Case Expressions
  • (cs) in reply to Satanicpuppy
    Satanicpuppy:
    Anonymous:
    Am I the only one who finds the switch statement as nasty as a ternary statement? I've never understood why something like:

    <font class="fixed_width" face="Courier, Monospaced">if x = 5:
        do_this
    elif x = 6:
        do_that
    else:
        do_something_else
    </font>

    is supposed to be "bad", but

    <font class="fixed_width" face="Courier, Monospaced">case of:
        x = 5:
            do_this
        x = 6:
            do_that
    otherwise:
            do_something_else
    </font>

    is supposed to be "good."




    It's not for that case that elseif is considered bad...It's for the case where you have 20 more elseifs, and a few nested if statements. Besides that, switches are generally more readable; your pretty formatting makes the elseif look just as readable as the switch, but with an elseif block, you're generally counting {}'s, whereas with a switch, you're just going between big obvious breakpoints.

    What he wrote was more or less Python, no braces there, please move along.

    (Oh, and i don't really see where you get "big obvious breakpoints" in switch/case statements)

    Anonymous:
    masklinn:

    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.



    It does:

    Case Expressions

    Thanks sir.

  • Brian (unregistered)

    Why is he typecasting in PHP? This guy is retarted.

  • (cs) in reply to anon
    Anonymous:
    Seriously, the code is not the WTF. I imagine I wrote the original code. 'switch' cannot do everything 'if' can, so there's probably a reason I used 'if' in the first place. For whatever reason, the code ended up the way it was, as a long chain of 'if' and 'ifelse'.


    We have been clearly led to believe that the coder was new to this lanauge, while O.C. is an expert.   While there are many situations where switch/case cannot repalce if/elseif/else, given the above I would assume that O.C. is correct when he says this code can be changed to switch/case


     However, it works and is tested. And now O.C. tells me, I have to use a switch, because... uhm... because... well, because he says so? I would either turn in exactly the code submitted ("You wanted a switch?! You get a switch!") or implement a refactoring tool, prove it correct (this might take a week or so, at the very least) and then apply "turn-if-into-case" exactly once. ("I had to be absolutely sure not to introduce an error in the transformation O.C. requested.") See the WTF? Yeah, stupid code review practice it is.


    In compiled languages a switch/case is turned into a hash table for large amounts of cases (about 10).   Therefore a switch/case is much faster than if/elseif/else when there are many cases.  

    I don't know how php does things, but someone examined the output from the C# compiler last time we had this discussion and verified that it really does create a hash table.

    siwtch/case is also more readable because it is clear from the start that you are only looking at one variable.   (Note, for some languages this doesn't apply)   With an if/else you need to watch for the variable being exampled changing, which makes reading code hard:

    if x==5
      doSomething()
    else if y == 5
      SoemthingElse()
    else if x == 6
      doSomethingElse()
    ...

    Of course if you really need to mix variables to get the logic correct you need the if/elseif sequence.   (and some comments so I understand why...)
  • (cs) in reply to Satanicpuppy
    Anonymous:
    Am I the only one who finds the switch statement as nasty as a ternary statement? I've never understood why something like:

    <FONT class=fixed_width face="Courier, Monospaced">if x = 5:
        do_this
    elif x = 6:
        do_that
    else:
        do_something_else
    </FONT>

    is supposed to be "bad", but

    <FONT class=fixed_width face="Courier, Monospaced">case of:
        x = 5:
            do_this
        x = 6:
            do_that
    otherwise:
            do_something_else
    </FONT>

    is supposed to be "good."

    I agree that both are equally bad/good. Long switches are hideous monstrosities as well. Their performance advantage over the else if chains hardly justifies their existence. If an else-if chain smells bad enough to justify going to a switch, then you may as well go into a strategy or command design pattern.

  • (cs) in reply to hank miller

    hank miller:

    I don't know how php does things, but someone examined the output from the C# compiler last time we had this discussion and verified that it really does create a hash table.

    Even for strings? I thought compilers could only do that for ordinal types.

  • (cs) in reply to Brian

    <Pun forewarning>

     

    Anonymous:
    Why is he typecasting in PHP? This guy is retarted.

    Because he's switching to the dark side, just in case...

     

     

  • (cs) in reply to hank miller
    hank miller:
    In compiled languages a switch/case is turned into a hash table for large amounts of cases (about 10).   Therefore a switch/case is much faster than if/elseif/else when there are many cases.


    Or a jump table.

    siwtch/case is also more readable because it is clear from the start that you are only looking at one variable.   (Note, for some languages this doesn't apply)   With an if/else you need to watch for the variable being exampled changing, which makes reading code hard:

    if x==5
      doSomething()
    else if y == 5
      SoemthingElse()
    else if x == 6
      doSomethingElse()
    ...

    Of course if you really need to mix variables to get the logic correct you need the if/elseif sequence.   (and some comments so I understand why...)


    Even in xBASE (which uses expressions), it is useful.  I sometimes have to iterate through the four possibilities of truth values of two conditions.  I find it much clearer to write

       do case
       case p and q
          ...
       case p and !q
          ...
       case !p and q
          ...
       otherwise     && !p and !q
          ...
          endcase

    than cascading if-else statements.
      Less often, I have have to handle more combinations.  Cascading if-elses are thoroughly nasty then.

    Sincerely,

    Gene Wirchenko

  • (cs) in reply to Gene Wirchenko

    I was under the impression that it was to keep a consistent coding style in the codebase. I mean, christ, who hasn't come across that project maintained by 5 people before you, all of whom had distinct coding styles and preferred to precision-insert changes instead of rewriting a block? Welcome to readability hell. Style standards are a good thing.

    On the other hand, sometimes the coding equivelent of a middle finger is also a good thing. =D

  • It's me again (unregistered) in reply to Anonymous Coward
    Anonymous:

    John Bigboote:
    Might wanna wrap the switch block in an
    if(true)
    block just to be sure.

    No, no, no.  That is bad code.  For God's sake, man: if you want to do something, do it right:

    if(IsTrue(true))

     

    No.  That is also bad code. 

    if(IsTrue(true) == true)

  • lordm (unregistered) in reply to jvancil

    It most certainly CAN be an art form. Developing elegant and efficient code takes skill and drive. I'd suggest that many programmers put into their code what people put into painting, music, or other "arts."

  • (cs) in reply to brazzy

    brazzy:
    Xepol:
    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)


    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.

    Actually, no, you can't.  Not even jump tables work here.  If you had values for 1 and 20008, your jump table would be larger than any CPU would support and would have a lot of junk pointers to the default routine.  It always compiles to an if/else chain.  Strings don't fit in registers, so could you imagine the size of a jump table if you representing the strings as integer values?  No CPU has registers that large, and I'll go out on the bill gates branch here and say that no cpu ever will have registers that large, and certainly will never support an accompanying jump table (could you imagine a  jump table for all possible strings?  Not freaking likely).

  • RealMonster (unregistered) in reply to Xepol
    Xepol:
    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.

    I think it works for him, too. I bet he thought exactly the same thing as you. I don't believe that he didn't know how to use a switch statement, I think the programmer figured that for an if/else with only THREE outcomes, it wasn't actually worth a rewrite into a real case statement.

    This looks like a case of rebellious programming, not bad programming.

  • (cs)
    Alex Papadimoulis:
        <FONT color=#000099>if</FONT> ($_GET[<FONT color=#990000>'action'</FONT>] == <FONT color=#990000>'delete'</FONT>)
        {
          $editid = (<FONT color=#000099>int</FONT>) $_GET[<FONT color=#990000>'delete'</FONT>];
        }
    I must be either too new to programming or too old (started in 1978), 
    but I don't get the dollar signs at the begining of the variables and
    array? names. WTF is that?
     
  • (cs)

    Actually in C I believe the switch statement has fall-through for each of the cases, so e.g.

    switch(c) {

     1: { ... }

     2: { ... }

     3: { ... }

    }

    Each one just "falls though" to the next case? In this way switch looks more like a series of gotos. All cases should be mutually exclusive anyway, so else isn't required either.

  • (cs) in reply to Otis Mukinfus
    Otis Mukinfus:
    Alex Papadimoulis:
        <FONT color=#000099>if</FONT> ($_GET[<FONT color=#990000>'action'</FONT>] == <FONT color=#990000>'delete'</FONT>)
        {
          $editid = (<FONT color=#000099>int</FONT>) $_GET[<FONT color=#990000>'delete'</FONT>];
        }
    I must be either too new to programming or too old (started in 1978), 
    but I don't get the dollar signs at the begining of the variables and
    array? names. WTF is that?
     

    In PHP, you have to prepend always all variables with "$", or PHP won't recognize it as a variable. Same with arrays.

    In unix-like shells like bash, sh, tcsh, zsh, etc. you have to do the same, except when doing an assignment.

  • (cs) in reply to Xepol
    Xepol:

    brazzy:

    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.

    Actually, no, you can't.  Not even jump tables work here.  If you had values for 1 and 20008, your jump table would be larger than any CPU would support and would have a lot of junk pointers to the default routine.  It always compiles to an if/else chain.  Strings don't fit in registers, so could you imagine the size of a jump table if you representing the strings as integer values?  No CPU has registers that large, and I'll go out on the bill gates branch here and say that no cpu ever will have registers that large, and certainly will never support an accompanying jump table (could you imagine a  jump table for all possible strings?  Not freaking likely).



    You know what binary search is? You know what a hashtable is? Apparently not, otherwise you wouldn't write such nonsense.
  • Jesper (unregistered)

    Aha. This is the kind of person that if you ask him "Say hello to Alice, Peter!" responds with: "Hello to Alice, Peter!".....

  • erlando (unregistered) in reply to elfz
    Anonymous:

    this shows the general bad coding approach of the php developers - not enough input validation, and hoping that everyone will have error_reporting(E_NONE) turned off, and when you try to do the right thing, and check the site with error_reporting(E_ALL), and don't include, let's say, that ID parameter, just look at the page crawling with warnings and notices.

    As a professional PHP developer I resent your generalization. Not all PHP developers employ bad coding practices. We are actually some coders that put pride and thought into our code.

    Remember, it's not the tool that makes a bad coder.

  • Rumata (unregistered) in reply to Scott

    Yep, I don't understand this either.

    The world is full of strange things, you know ...

  • (cs) in reply to RiX0R
    RiX0R:

    hank miller:

    I don't know how php does things, but someone examined the output from the C# compiler last time we had this discussion and verified that it really does create a hash table.

    Even for strings? I thought compilers could only do that for ordinal types.



    I work with C and C++ which only allow switch on ordinal types so I'm, not sure.

    However I see no reason you can't do a hash table on a string.  The has function is a little more complex, but it doesn't have to be perfect.   There are plenty of papers on hashing of strings, just pick something that works when you implement the compiler. 
  • (cs) in reply to Xepol
    Xepol:

    Actually, no, you can't.  Not even jump tables work here.  If you had values for 1 and 20008, your jump table would be larger than any CPU would support and would have a lot of junk pointers to the default routine.  It always compiles to an if/else chain.  Strings don't fit in registers, so could you imagine the size of a jump table if you representing the strings as integer values?  No CPU has registers that large, and I'll go out on the bill gates branch here and say that no cpu ever will have registers that large, and certainly will never support an accompanying jump table (could you imagine a  jump table for all possible strings?  Not freaking likely).



    Why won't a branch table work?   You just need to be a little intelligent about it.  For your example you don't jump on the full word, just the least significant bit.

    foo[] = [(function for 20008), (function for 1)
    foo[x & 0x0001]

    Of course your functions then need to test for to be sure x is the correct value, so for this simple case it is a pointless optimization.   

    The C# compiler was tested some months back.  When the number of cases is less than 10 it turns a switch into an if/elseif.   When the number of cases is more than that it builds a hash/jump table.  

    Notice that we did not specify any particular table implimentation.   A jump table with all possible values does not fit into memory.  However compiler writers are smarter than that.   Both hash tables, and binary searches will fit into memory (If it won't you have bigger problems, and need to think about hand optimized assembly). 


  • (cs) in reply to erlando
    Anonymous:
    Anonymous:

    this shows the general bad coding approach of the php developers - not enough input validation, and hoping that everyone will have error_reporting(E_NONE) turned off, and when you try to do the right thing, and check the site with error_reporting(E_ALL), and don't include, let's say, that ID parameter, just look at the page crawling with warnings and notices.

    As a professional PHP developer I resent your generalization. Not all PHP developers employ bad coding practices. We are actually some coders that put pride and thought into our code.

    Remember, it's not the tool that makes a bad coder.



    Certainly there are programmers who use PHP and don't write poor code but by saying that PHP is just a tool and the people are responsible, you fail to take into account the often-present culture that surrounds a language and the users of a language. In that respect, I think the assessment of PHP which you objected to is correct.

    Sincerely,

    Richard Nixon
  • (cs) in reply to Brian

    <FONT face="Courier New" size=2>was i the only one who caught the =/== mistake?  or was that just a typo?</FONT>

  • (cs) in reply to Otis Mukinfus
    Otis Mukinfus:
    Alex Papadimoulis:
        <font color="#000099">if</font> ($_GET[<font color="#990000">'action'</font>] == <font color="#990000">'delete'</font>)
    {
    $editid = (<font color="#000099">int</font>) $_GET[<font color="#990000">'delete'</font>];
    }
    I must be either too new to programming or too old (started in 1978), 
    but I don't get the dollar signs at the begining of the variables and
    array? names. WTF is that?
     


    It isn't that you are too old, but that your experience has likely been in the dos/windows world or the mainframe world.  The family of unix shell languages that evolved from the Bourne shell use the dollar sign to indicate a variable, much like dos uses the percent signs.  Perl was developed as a better unix scripting language and so absorbed many syntactic elements of the Bourne shell languages.  PHP in turn was developed as a better Perl for the web, and so absorbed many syntactic elements from Perl.

    It is interesting to observe how many widely used languages were specifically designed to broadly resemble some preceding successful language.  Anyone who is comfortable with shell scripting, sed, awk, etc. can naturally absorb Perl in small easy to digest chunks.  Meanwhile the Perl developer can use PHP and Python more easily than a non-Perl developer..  Likewise C begat C++, which begat Java and Java's near clone C#.  Meanwhile languages like Ruby are slower to gain acceptance.  There is a certain feeling of comfort when much of the syntax is recognizable.
  • Trancer (unregistered) in reply to Volmarias
    Volmarias:

    Hah!

    This code made me laugh out loud. It's hideous but technically correct!

    BRILLANT! [H]



    Not quite ;p

    $editid == (<font>int</font>) $_GET[<font>'save'</font>];

    hehe

  • Kim (unregistered) in reply to Djinn

    Yeah, that's much better than the readable switch-version ;-) Job security via code obscurity

  • AKrotkov (unregistered) in reply to felix
    felix:
    Anonymous:
    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.

    Well, you're the one advocating unreadable code as being "better", Mr. Easily Offended. I didn't even post a code example.

    Anonymous:
    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 ?:.

    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>



    Just saying, but whitespace is not everything. I am one of those people that prefers the coding style

    if (x)
    {
        ...
    }

    Just because that lines up the brackets, and actually puts the block on the same level as the rest.

    And a quick question:

    (x)
    ?
    {
        ...
    }
    :
    {
        ...
    }

    Would that compile? If so, that's my counter argument ;-)
  • lo (unregistered)

    heh... looks like something I would have done... 'you want a switch statement!? I got your stupid switch statement right here buddy...'

    -lo

  • NrgSpoon (unregistered)

    Hey, uh.. all your corrections that have been made, they don't stay true to the original code.

    Alex Papadimoulis:

        <FONT color=#000099>elseif</FONT> ($_GET[<FONT color=#990000>'action'</FONT>] == <FONT color=#990000>'save'</FONT>)
        {
          $editid <FONT style="BACKGROUND-COLOR: #ffffff" color=#ff0000>==</FONT> (<FONT color=#000099>int</FONT>) $_GET[<FONT color=#990000>'save'</FONT>];
        }

  • Anonymous Coward (unregistered) in reply to Enric Naval
    Enric Naval:
    DrJames:
    Enric Naval:

    //P= no prerequisites
    //Q= return action parameter  if action has been passed by parameter,
    //                            and if action is a valid action
    //   return id parameter      otherwise
    //Exceptions= never
    function int actionIdParameter ()
    {
      $validActions = array('save', 'edit', 'delete')

      thePar = $_GET['action'];
      if (  (int) ((isset($_GET[$thePar]) &&
           in_array(thePar,$validActions) ) {
        $temp = $_GET[$thePar];
      }
      else {
        $temp = $_GET['id']);
      }
    return (int) $temp;
    }

    //CALLING CODE

    $editid = actionIdParameter();

    1. accessing global $_GET within a private method (if $_GET is just the Request object then that's okay)
    2. not declaring variables inside method
    3. if ( (int) ... ) ? 
    4. Remove Prequisites and Exceptions, or put them in xml tags to be parsed by a document generator (I'd say just remove them as they will inevitably become out of date as program Y goes in and adds an exception but doesn't read/update the little header)... method summarys are not likely to change
    5. Along that, you say there are no exceptions yet what if $_GET['action'] does not exist... whamo exception (maybe not in this language?)
    6. Actually along this theme you say there are no prerequisites... yet $_GET is expected to be exist (not so bad if as in point #1 this is the Request object)

    $_GET always exists. Like you say, it's like the request object in JSP, only it's just a String[][] array. It's generated and filled by the interpreter and available as a global variable. I don't remember how to pass $_GET by parameter in PHP. In PHP it's very normal to just access the global GET and POST arrays for reading parameters from them.

    In PHP you can declare variables with no type, so you maybe didn't notice them. I actually mistyped some of the declarations, I re-write them here:

    $validActions = array('save', 'edit', 'delete'); //declares a String[] called validActions
    $thePar = $_GET['action'];  //declares a String called thePar and initializes it
                                //   if there is no index called "action" I think
                                //   it creates an empty invalid variable
    $temp = $_GET[$thePar];     //declares a String called temp similarly to thePar
    

    PHP is fun because if you mistype a variable name anywhere then PHP just creates a new empty variable for you with the mistyped name. Hours of fun guaranteed tracking down why your variable is not getting inicializated.

    I try to keep the requisites up to date. But I don't try too hard. In Java you are forced to declare all exceptions, so that line can be taken out. Sometimes I forget what the little buggers do, and thore requisites give some clue, even if they are a bit out of date :) As the function gets called by more and more code, it's more and more important to be able to know fastly what it is SUPOSSED to do. You can then look at the code to see it still does what it is SUPOSSED TO DO, and change it back, or change the requisites.

    Getting the "action" parameter doesn't give an exception because I first check the existance of it with isset(). However, I'm not checking the existance of the "id" parameter either, but PHP will probably just return a non set variable. The only posible exception would come from the (int) conversion, if I'm getting passed a string with alphabetic characters on it. I'm not sure what happens then.

    "if ( (int) ... )" Ooooh, I just copy&pasted from the other code. Anyways, it probably works the same since the "if" will probably just convert the int back to boolean to check it. PHP is very forgetful of this kind of mistakes :)

    You have to try PHP at least once in your life :)

    I discourage people from trying PHP because it turns out dickheads like you who think they know it all and attempt to correct real programmers.

    $_GET is not a String[][]. String[][] -- even though it doesn't exist in PHP since it's simply called 'array' -- would be indexed via $_GET['foo']['bar'], so you can see why you're wrong without me even explaining type to you. You also confuse declare and define, more evidence you only know PHP. (I refer to your comments here.)

    Also, PHP does not create an empty variable whenever you mistype a variable name. I present sample code, $foo = $bar all by itself:

    PHP Notice:  Undefined variable: bar in test.php5 on line 2

    Learn C and take an English class, then try to hock a programmer discussion. Seriously.

  • Anonymous Coward (unregistered) in reply to AKrotkov

    Anonymous:
    felix:
    Anonymous:
    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.

    Well, you're the one advocating unreadable code as being "better", Mr. Easily Offended. I didn't even post a code example.

    Anonymous:
    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 ?:.

    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>



    Just saying, but whitespace is not everything. I am one of those people that prefers the coding style

    if (x)
    {
        ...
    }

    Just because that lines up the brackets, and actually puts the block on the same level as the rest.

    And a quick question:

    (x)
    ?
    {
        ...
    }
    :
    {
        ...
    }

    Would that compile? If so, that's my counter argument ;-)

    Nope. Need an x. If you throw in an

    int
    x
    =
    0
    ;

    before it...then it should, yes. Talk about token fun!

  • (cs) in reply to Anonymous

    Being a junior or transitioned is one thing. . . lacking common sence is another

    Well here is one more for the desert (from another "transitioning" programmer):

    <FONT color=#0000ff>String</FONT> fName = <FONT color=#800080>null</FONT>;
    <FONT color=#800080>if</FONT> (fname == <FONT color=#800080>null</FONT>). . . . .

    The "==" I can understand. . . after all, he is "transitioning", but . . . . WTF

  • Anonymous Coward (unregistered) in reply to Anonymous Coward

    Hrmm...

    def IsTrue(true):

    return IsTrue(true)

    if(IsTrue(true))...

  • a/c (unregistered)

    Was this anonymized to hide a Delphi snippet perhaps?  Not sure what other languages might be affected, but Borland's "native" string type in 32-bit environments was implemented as an instance of AnsiString class.  Objects were not allowed in case statements, so the code just wouldn't fail.  In such a case, the WTF would be that O.C. didn't know this.

  • lunchtime (unregistered) in reply to Gene Wirchenko
    Gene Wirchenko:
    Anonymous:
    All you newbs out there, listen up: if you can get it done in one line without sacrificing readability, then do it! Programming is an art form, not politics.

    That is a very big IF.

    Ah, the politics of art!

    Sincerely,

    Gene Wirchenko

    Yeah, you may want to replace it too...

    All you newbs out there, listen up: switch case you can get it done in one line without sacrificing readability, do it! break
  • (cs) in reply to Gene Wirchenko
    Gene Wirchenko:
    Alex Papadimoulis:
    For those who "grew up" programming in a language without it, a Switch/Case statement might seem to be a bit foreign. When "transitioning" programmer brought code to a review, O.C. rejected it and requested that he use a switch statement instead of the numerous elseif blocks. The same programmer returned to the next day's code review but didn't quite seem to understand the finer points of the switch statement ...
    I suggest that that transitioning programmer is more than a little clueless.  The first language that I programmed in did not have switch/case either.  When I first read about it, it was simple to see how it worked and simple to use.

    Sincerely,

    Gene Wirchenko

    No - he was just being cute or a smart a**. "OK then I'll use switch, but I'll do it my way". Any of those reviewing his code the second time would have realised this.

Leave a comment on “Having a Hard Time Switching”

Log In or post as a guest

Replying to comment #:

« Return to Article