• (cs) in reply to Mutty

    > $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 ?


  • (cs) in reply to Djinn
    Anonymous:
    Enric Naval:

    Uuuh, you don't like it? :)

    If you are only checking the action parameter on one place, you don't need to build a generic, parametrized function, of course :P

    But I'm used to building big websites, with lot of repetitive code, so I'm calling quite but not exactly similar code from a pair of hundred different web pages in several different places and contexts.

    From my experience, sooner or later my boss will ask me to add a "rename" action in every single page, and using one-liners like yours, I'll have to edit every single one-liner in the website. Last time I had to edit by hand like some 80 pages, because, of course, I had slightly modified some of the one-liners, because different pages would accept different arrays of actions, and I had to unify all the behaviour.

    Next time I had to a add a different action, I only needed to change a few lines of code, because all the code was in a single place.

    After several months expanding the same website, code placed in functions get naturally expanded, then gets placed inside classes and ends up making lots of complicated work, so "actionIdParameter" could be taking into account the user ID and several fields in the database, to check if the user can do that action. At the end, they allow me to change the behaviour of all of the website by only modifying a few lines.

    One-liners, on the other hand, just get bloated and finally replaced.



    I won't tear you to pieces here as I can see you're still learning, but you're saying I shouldn't use one-liners because they will be replaced. That's terrible ... just ... terrible thinking. I don't think there's anything wrong with using a function, and I won't even comment on the faults of the code, and your thinking in writing it. I do take personal offense though when you try to tell me that I'd use a one-liner EVERYWHERE in the site. How did you get that impression? I'd use it as nesscary, like anything else.

    It's not freakin' rocket science, hell it ain't even computer science! Write the code to be simple, clean, and concise. Branch out as needed, following these rules. I can't believe any of you would knock a perfectly good one-liner.

    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.

    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?

  • (cs) in reply to maht

    er, way to post your inability to read

    ignore me (for now ;)

  • Alan (unregistered) in reply to rogthefrog

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

  • Mutty (unregistered) in reply to Djinn
    Anonymous:
    Way to use the forum! ;)

    Yeah, it's better. It's all on one simple line. In real life I'd probably break it out onto seperate lines for readability (but still one statement). TMTOWTDI.


    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.
  • (cs) 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 :)

    - 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!

  • (cs) in reply to DrJames

    Ok, ok, I'll be the first to say it:
    It's an optimization!

    [6]

  • DudeInAZ (unregistered) in reply to JohnO
    JohnO:

    Why is everyone so sure this guy wasn't just being smartass? 

    That was my thought. 

  • (cs)

    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.

  • (cs) in reply to llxx

    This looks a bit fake to me.

    (2 second edit limit? WTF?!?!)

  • Djinn (unregistered) in reply to llxx

    Enric:


    /* 
    * there are no return values in PHP. I know you're rusty,
    * and this code is adapted, so I forgive you
    */
    function int actionIdParameter ()
    {
    /*
    * you don't really need a seperate variable for this.
    * inline is fine.
    */
    $validActions = array('save', 'edit', 'delete')

    /*
    * thePar is such a crappy name for a variable, especially
    * when the variable is supposed to represent a key. plus,
    * it's not even a variable, it's a constant. where's the '$'?
    */
    thePar = $_GET['action'];
    /*
    * - silly formatting, but that's okay.
    * - (int) we've been over.
    * - you remembered '$' here. WHAT WERE YOU THINKING???
    * - you're missing TWO parenthesis!!!!!!
    */
    if ( (int) ((isset($_GET[$thePar]) &&
    in_array(thePar,$validActions) ) {
    /*
    * where did you learn lexical scoping?
    * temp wasn't used before this block
    */
    $temp = $_GET[$thePar];
    }
    else {
    /* see above */
    $temp = $_GET['id']);
    }

    /*
    * SCOPING RULES, MAN!
    */
    return (int) $temp;
    }

    and this is supposed to be better than:

    function getActionID() {
    $key = (isset($_GET['action']) ? $_GET['action'] : '');

    return (int) (
    (isset($_GET[$key]) && (in_array($key, array('save', 'edit', 'delete'))) /* if we have a key that is 'edit', 'save', 'delete' */
    ? $_GET[$key] /* then use that key */
    : $_GET['id'] /* otherwise, the id */
    )
    );
    }

    I won't bust your balls over the psycho doc you had going on there either.
  • Djinn (unregistered) in reply to Djinn

    s/return values/variable types/;

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


    Way to win the avatar contest!
  • Lothar (unregistered) in reply to OneFactor
    OneFactor:

    Wow. Almost unbelievable. And to think I once belonged to the camp that said that if there was sufficient test coverage, the code would naturally be fairly good. No way for a unit test to sniff this sucker out - and yet... the mind reels at how anyone could invent this. A classic WTF.

    public String getMessage() {
       String result = "";
       if (isTrue(new Paula().getPaula().equals("Brillant")) {
          switch ("Brillant'.hashCode()) {
             default:
                for (int i = 0; i < 3; i++) {
                   switch(i) :
                      case 0: result = result + "W"; break;
                      case 1: result = result + "T"; break;
                      case 2: result = result + "F"; break;            
                }
          }
       }
       return result; 
    }



    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;
       }
    }
  • (cs) in reply to JohnO
    JohnO:
    Why is everyone so sure this guy wasn't just being smartass?


    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

  • (cs) in reply to Djinn
    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

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



    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.

  • Tony Morris (unregistered) in reply to Free
    Free:

    There are poeple who persist in the belief that elseif structures are "just better".

    if elseif elseif else [:@]



    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
  • Tony Morris (unregistered) in reply to llxx
    llxx:
    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.


    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.
  • (cs) in reply to llxx
    llxx:
    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.


    Perl doesn't... Switch.pm notwithstanding
    http://search.cpan.org/~dconway/Switch-2.09/Switch.pm
  • anzac (unregistered)

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

  • (cs) in reply to anzac
    Anonymous:
    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...


    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

  • (cs) in reply to Gene Wirchenko
    Gene Wirchenko:
    Anonymous:
    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...


    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



    That lazy programmer should at least check the manual when someone told him the hints.
  • (cs) in reply to Djinn
    Anonymous:
    That is the single most foolish remark I have ever heard. You must be very, very, young.


    And you must be relatively new to this board ;)
  • Anonymous (unregistered) in reply to Lothar

    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.

  • (cs)

    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.

  • (cs) in reply to Alexis de Torquemada
    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 how big is guns are?

    Sincerely,

    Richard Nixon
  • (cs) in reply to Djinn
    Anonymous:
    You're just not used to being around good programmers. Consice statements are nothing to fear. It saves space, and any programmer of any worth can easily tell what's going on there. I'm not doing anything unusual here. Even if I were afraid of dorkface down the hall who doesn't know how to code, I could, like I said, break it out into several lines and even /* comment */ the sections. It DOES add value to the code, as it's simply a matter of two conditions instead of multiple ifs, which you'd probably want me to deeply nest.

    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.
  • (cs) in reply to llxx
    llxx:
    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.

    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.

  • (cs) in reply to Richard Nixon

    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

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

  • Djinn (unregistered) in reply to foxyshadis
    foxyshadis:
    Anonymous:
    You're just not used to being around good programmers. Consice statements are nothing to fear. It saves space, and any programmer of any worth can easily tell what's going on there. I'm not doing anything unusual here. Even if I were afraid of dorkface down the hall who doesn't know how to code, I could, like I said, break it out into several lines and even /* comment */ the sections. It DOES add value to the code, as it's simply a matter of two conditions instead of multiple ifs, which you'd probably want me to deeply nest.

    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.


    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)
  • (cs)

    Not to worry; this one is easy to fix.  I think Mr. Trump and I are of one mind in this: "You're fired!"


  • vhawk (unregistered)

    poor kid ...  must be terrible ....

  • Daniel Von Fange (unregistered) in reply to Enric Naval

    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

  • (cs) in reply to Djinn
    Anonymous:

    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)


    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.

  • Djinn (unregistered) in reply to felix
    felix:
    Anonymous:

    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)


    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.



    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?
  • (cs) in reply to Djinn
    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>

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

     

    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

  • (cs) in reply to felix
    felix:

    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.


    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.

  • (cs) in reply to llxx
    llxx:
    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.


    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.
  • (cs) 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)


    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.
  • (cs) in reply to DrJames
    DrJames:
    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 :)

    - 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!

    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.

    //the function, one last time
    
    
    //P: nothing
    //Q: if action parameter existes 
    //   and is a valid action
    //      the value of the parameter defined by action
    //   else if id parameter exists
    //      $_GET['id']
    //   else
    //      -1
    //Exceptions: conversion to int may fail if action or id are not numbers
    function actionIdParameter ()
    {
      global $_GET;
      $validActions = array('save', 'edit', 'delete');
      $temp = ''; //incialize to nonsense
    
      $actionKey = $_GET['action'];
      if ( isset($actionKey) 
           && isset($_GET[$actionKey])
           && in_array(actionKey,$validActions) ) {
        $temp = $_GET[$actionKey];
      }
      else {
        $temp = $_GET['id']);
        if ( ! isset($temp) ) { 
          $temp = '-1';
        }
      }
    return (int) $temp;
    }
    

    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!

  • Bilbo Baggins (unregistered) in reply to jvancil

    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.

  • (cs) in reply to Djinn

    Let me play wise-ass and point out some factual mistakes:

    Anonymous:
    Enric:
      if (  (int) ((isset($_GET[$thePar]) &&
           in_array(thePar,$validActions) ) {
        /*
         * where did you learn lexical scoping?
         * temp wasn't used before this block
         */
        $temp = $_GET[$thePar];
      }
      else {
        /* see above */
        $temp = $_GET['id']);
      }

    /*
      * SCOPING RULES, MAN!
      */
    return (int) $temp;
    }

    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:

    <?
      if (true) {
          $x = "'Tis so!";
      }
      else {
          $x = "Nay";
      }
      echo $x;
    ?>

    Happily prints "Tis so".

    Enric Naval:
    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.

    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? :)

  • zootm (unregistered) in reply to masklinn
    masklinn:
    llxx:
    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.

    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.

    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.


  • (cs) in reply to Volmarias
    Volmarias:

    Hah!

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

    BRILLANT! [H]



    It's technically correct, which is the best form of correct
  • (cs) in reply to Enric Naval

    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.

    
    public class Answer 
    {
      //lots of functions
    
      //has value by defect
      //only one option selected
      public StringBuilder radioinput( final String enunciate, final String var_name, final String[][] valuesParameter, 
         final StringBuilder other, final LooksLike looksLike, final String editable ) 
         throws java.io.IOException, java.sql.SQLException
      {
        final StringBuilder t = new StringBuilder(150);
        final String var = this.extract(var_name,true,editable);
        final String[][] values = Answer.normalizeAnswer(var,valorsParametre,false,others);
        if ( editable.equals("no") ) {
          t.append( Answer.printMultiplePlainText(var,valors) );
        }
        else {
          String tempEnunciate = AnswerType.RADIOINPUT.getFinalEnunciate(enunciate);
          t.append( Answer.generateHTML(tempEnunciate,nom_var,valors,other,AnswerType.RADIOINPUT,looksLike,editable) );
        }
        return t;
      }
    
    
    
    // gets called like this:         
    //<%    
    //  static String[][] a18Formules = {
    //    { "A=(b*a)/2",         "[image]" },
    //    { "A=pi*a^2",          "[image]" },
    //    { "A=(D*d)/2",         "[image]" },
    //    { "A=a*b",             "[image]" },
    //    { "A=((B+b)/2)*a",     "[image]" },
    //    { "A=a^2",             "[image]" },
    //    { "A=(1/2)*P*a,P=n*l", "[image]" },
    //  };
    //%>
    // task-1-2.jsp
    //<%= resposta.radioinput("How do you calculate a circle area?","a04",a18Formules,null,LooksLike.BOXED_LIST,editable) %>
    //
    // task-3-3.jsp
    //<%= resposta.radioinput("How do you calculate a trapezoid area?","d06",a18Formules,null,LooksLike.TABLE_X_3,editable) %>
    //
    // task-4-2.jsp
    //<%= resposta.radioinput("How do you calculate the area of " + someGeometricFigure + "?","f14",a18Formules,null,LooksLike.HORIZONTAL_TABLE,editable) %>
    //
    // task-4-3.jsp  //only displays what you answered in the former page because we're passing editable == "no"
    //<%= resposta.radioinput("You selected this area:","f14",a18Formules,null,LooksLike.BLOCKQUOTE,"no") %>
    //
    //               // displays a 5x10 textarea
    //<%= resposta.textarea("Why did you select that formula? Explain it.",5,10"f15",editable) %>
    
    
    
      //Q= SQLException if we attempt to use twice the same answer id
      //                if editable != "no"
      //   SQLException if can't get variable value from BD
      //   SQLException if can't get suggerence     from BD
      //   if no exceptions,
      //      if variable contains something
      //         variable
      //      if variable contains nothing,
      //         if there is suggerence
      //             suggerence
      //         if there is no suggerence
      //             content    si there is content
      //             ""         si there is no content and editable != "no"
      //             " "   si there is no content and editable == "no"
      private String extract( StringBuilder content, final String var_name, boolean multiple, final String editable ) throws ja\
    va.io.IOException, java.sql.SQLException
      {
    
        // 45 lines of crap code and DB access using two different prepared statements which are
        //      defined in the class constructor and a custom class for DB access and connection pooling
    
      }
    
    
    } //CLASS END
    
    
    

    Ouch! Another too long message :(

  • (cs) in reply to Enric Naval

    Ahem, gets called like this:

    //a18-header.jsp
    //<%    
    //  static String[][] a18Formules = {
    //    { "A=(b*a)/2",         "<img src=\"images/formula1.gif\">" },
    //    { "A=pi*a^2",          "<img src=\"images/formula2.gif\">" },
    //    { "A=(D*d)/2",         "<img src=\"images/formula3.gif\">" },
    //    { "A=a*b",             "<img src=\"images/formula4.gif\">" },
    //    { "A=((B+b)/2)*a",     "<img src=\"images/formula5.gif\">" },
    //    { "A=a^2",             "<img src=\"images/formula6.gif\">" },
    //    { "A=(1/2)*P*a,P=n*l", "<img src=\"images/formula7.gif\">" },
    //  };
    //%>
    // task-1-2.jsp
    //<%= resposta.radioinput("How do you calculate a circle area?","a04",a18Formules,null,LooksLike.BOXED_LIST,editable) %>
    //
    // task-3-3.jsp
    //<%= resposta.radioinput("How do you calculate a trapezoid area?","d06",a18Formules,null,LooksLike.TABLE_X_3,editable) %>
    //
    // task-4-2.jsp
    //<%= resposta.radioinput("How do you calculate the area of " + someGeometricFigure + "?","f14",a18Formules,null,LooksLike.HORIZONTAL_TABLE,editable) %>
    //
    // task-4-3.jsp  //only displays what you answered in the former page because we're passing editable == "no"
    //<%= resposta.radioinput("You selected this area:","f14",a18Formules,null,LooksLike.BLOCKQUOTE,"no") %>
    //
    //               // displays a 5x10 textarea
    //<%= resposta.textarea("Why did you select that formula? Explain it.",5,10,"f15",editable) %>
    
    
    
    
    
  • Newton (unregistered) in reply to brazzy
    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?

Leave a comment on “Having a Hard Time Switching”

Log In or post as a guest

Replying to comment #:

« Return to Article