Comment On Having a Hard Time Switching

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 ... [expand full text]
« PrevPage 1 | Page 2 | Page 3Next »

Re: Having a Hard Time Switching

2005-10-17 13:58 • by Brian Hampson
ROTFLMAO!!!  I love it.  His code WAS technically correct...he had the SWITCH [:P]

Re: Having a Hard Time Switching

2005-10-17 13:58 • by Free

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


if elseif elseif else [:@]

Re: Having a Hard Time Switching

2005-10-17 14:00 • by The Wizard of Oz
Seems it could just be reduced to this

$editid = (int) $_GET[$_GET['action']];




Re: Having a Hard Time Switching

2005-10-17 14:00 • by Not You
That... is fantastic.

Re: Having a Hard Time Switching

2005-10-17 14:09 • by jimbo
47016 in reply to 47014
Anonymous:
Seems it could just be reduced to this

$editid = (int) $_GET[$_GET['action']];







No because if the result of $_GET['action'] is not one of the specified
values it should default to $_GET['id'] which your example won't do.

The old saying...

2005-10-17 14:11 • by TGV
It once more goes to show that you have to be careful with what you ask for: you might get it...

Re: Having a Hard Time Switching

2005-10-17 14:12 • by TGV
47018 in reply to 47016
Anonymous:
No because if the result of $_GET['action'] is not one of the specified
values it should default to $_GET['id'] which your example won't do.


I'm sure that's easier to fix, and with a lot less possible typing errors and a lot more flexibility.

Re: Having a Hard Time Switching

2005-10-17 14:20 • by John Bigboote
Might wanna wrap the switch block in an

if(true)

block just to be sure.

Re: Having a Hard Time Switching

2005-10-17 14:25 • by DrJames

how about


switch ($_GET["action"])

   case "delete" : 
   case "edit" :
   case "save" :
      $editid = (int) $_GET[$_GET["action"]];
      break;
   default :
      $editid = (int) $_GET["id"];
}

Re: Having a Hard Time Switching

2005-10-17 14:27 • by Anonymous Coward
47021 in reply to 47019

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

Re: Having a Hard Time Switching

2005-10-17 14:28 • by 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



Re: Having a Hard Time Switching

2005-10-17 14:31 • by Richard Nixon
47024 in reply to 47022
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

Re: Having a Hard Time Switching

2005-10-17 14:39 • by Djinn
47025 in reply to 47016
Anonymous:
Anonymous:
Seems it could just be reduced to this

$editid = (int) $_GET[$_GET['action']];







No because if the result of $_GET['action'] is not one of the specified
values it should default to $_GET['id'] which your example won't do.




$editid = (int) (isset($_GET[$_GET['action']]) ? $_GET[$_GET['action']] : $_GET['id']);

Re: Having a Hard Time Switching

2005-10-17 14:41 • by DrJames
47026 in reply to 47025
Anonymous:
Anonymous:
Anonymous:
Seems it could just be reduced to this

$editid = (int) $_GET[$_GET['action']];






No because if the result of $_GET['action'] is not one of the specified values it should default to $_GET['id'] which your example won't do.


$editid = (int) (isset($_GET[$_GET['action']]) ? $_GET[$_GET['action']] : $_GET['id']);


 


I don't know what isset but if it is just checking the hash for a key existance that that's wrong,  suppose if $_GET['action'] = 'blah' for example you would still want to run $_GET['id']

Re: Having a Hard Time Switching

2005-10-17 14:42 • by Djinn
47027 in reply to 47025
Anonymous:
Anonymous:
Anonymous:
Seems it could just be reduced to this

$editid = (int) $_GET[$_GET['action']];







No because if the result of $_GET['action'] is not one of the specified
values it should default to $_GET['id'] which your example won't do.




$editid = (int) (isset($_GET[$_GET['action']]) ? $_GET[$_GET['action']] : $_GET['id']);




or, if it really has to be one of those values you could $values = array('delete', 'edit', 'save')



then check if is_in_array() (or whatever that function is, I'm too lazy to look it up (a great virtue))

Re: Having a Hard Time Switching

2005-10-17 14:46 • by OneFactor
47028 in reply to 47024

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

Re: Having a Hard Time Switching

2005-10-17 14:47 • by Djinn
47029 in reply to 47026
DrJames:
Anonymous:
Anonymous:
Anonymous:
Seems it could just be reduced to this

$editid = (int) $_GET[$_GET['action']];






No because if the result of $_GET['action'] is not
one of the specified values it should default to $_GET['id'] which your
example won't do.


$editid = (int) (isset($_GET[$_GET['action']]) ? $_GET[$_GET['action']] : $_GET['id']);


 


I don't know what isset but if it is just checking the hash for a
key existance that that's wrong,  suppose if $_GET['action']
= 'blah' for example you would still want to run $_GET['id']





You picky bastard...



$editid = (int) ((isset($_GET[$_GET['action']]) &&
(in_array($_GET['action'], array('save', 'edit', 'delete'))) ?
$_GET[$_GET['action']] : $_GET['id']);

Re: Having a Hard Time Switching

2005-10-17 14:48 • by Djinn
47030 in reply to 47028
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; 
}





syntax error ... wtf

Re: Having a Hard Time Switching

2005-10-17 14:51 • by Anonymous
47031 in reply to 47021
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))





Or, better:



if( ! checkFalse( new Boolean( true ) ) )



http://www.thedailywtf.com/forums/39325/ShowPost.aspx

Re: Having a Hard Time Switching

2005-10-17 14:59 • by elfz

Apart from the lesser problem (the utterly nonsense switch usage - it is weird that the developer didn't know how to use it, but at least that is a thing that can be easily fixed by pointing the dev at the right page of php manual), 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.


It is actually quite frightening how many php projects fall to pieces with error reporting turned on to the max (or rely on one or another specific php configuration settings; register_globals anyone? or fall when magic_quotes_gpc are turned off).

Re: Having a Hard Time Switching

2005-10-17 15:01 • by Mutty
47035 in reply to 47029


 DrJames wrote:
 Anonymous wrote:
 Anonymous wrote:
 Anonymous wrote:
Seems it could just be reduced to this

$editid = (int) $_GET[$_GET['action']];






No because if the result of $_GET['action'] is not
one of the specified values it should default to $_GET['id'] which your
example won't do.


$editid = (int) (isset($_GET[$_GET['action']]) ? $_GET[$_GET['action']] : $_GET['id']);

 


I don't know what isset but if it is just checking the hash for a
key existance that that's wrong,  suppose if $_GET['action']
= 'blah' for example you would still want to run $_GET['id']








You picky bastard...





$editid = (int) ((isset($_GET[$_GET['action']]) &&
(in_array($_GET['action'], array('save', 'edit', 'delete'))) ?
$_GET[$_GET['action']] : $_GET['id']);







Re: Having a Hard Time Switching

2005-10-17 15:03 • by Mutty
47036 in reply to 47035
that was SUPPOSED to be a quote and a "And somehow this is better?!?!?"   bah.

Re: Having a Hard Time Switching

2005-10-17 15:07 • by Djinn
47037 in reply to 47036
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.

Re: Having a Hard Time Switching

2005-10-17 15:16 • by einstruzende
47038 in reply to 47035
I hope that you don't actually make ternary statements that look like
that.  It's error prone and a maintenance nightmare, not to
mention it gains you nothing over using a couple of IF statements.





Re: Having a Hard Time Switching

2005-10-17 15:22 • by Djinn
47039 in reply to 47038
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.

Re: Having a Hard Time Switching

2005-10-17 15:25 • by fmobus
47040 in reply to 47038
There's another WTF here, but this one is subtle:

Instead of

.../stupid.php?action=save&save=69

.../stupid.php?action=edit&edit=69

.../stupid.php?action=delete&delete=69

[...]



Shouldn't be:

.../clever.php?action=save&id=69

.../clever.php?action=edit&id=69

.../clever.php?action=delete&id=69



I know this is nitpicky, but makes hell lot easier to parse.



I'm having similar problems where I'm working: very similar structures,
with the same operations and field types, but the names of the fields
are completely different! I waste most of the time COPY-PASTING
operations and replacing with the proper fields, which is, naturally, a
error-prone approach... but its a giant system and I can't change it. =/

Re: Having a Hard Time Switching

2005-10-17 15:27 • by Volmarias
47041 in reply to 47028

Hah!


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


BRILLANT! [H]

Re: Having a Hard Time Switching

2005-10-17 15:29 • by Volmarias
47042 in reply to 47028

OneFactor's code, I meant, although the WTF had the same effect.


OneFactor:


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

Re: Having a Hard Time Switching

2005-10-17 15:31 • by Alexis de Torquemada
47043 in reply to 47024
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?



Re: Having a Hard Time Switching

2005-10-17 15:33 • by rogthefrog
47044 in reply to 47034
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.


It is actually quite frightening how many php projects fall to pieces with error reporting turned on to the max (or rely on one or another specific php configuration settings; register_globals anyone? or fall when magic_quotes_gpc are turned off).



Who needs validation when you can provide your customers with superb added value like the following:


http://www.bootbarn.com/multiview/men/bootsshoes/view/view/0/48/popular/All?size=12.0&width=Narrow


I.e. ENTERTAINMENT!

Re: Having a Hard Time Switching

2005-10-17 15:35 • by rogthefrog
47045 in reply to 47044

In case bootbarn fixes their site, here's what happens when you go to


http://www.bootbarn.com/multiview/men/bootsshoes/view/view/0/48/popular/All?size=12.0&width=Narrow


 










Home ›› Men ›› Boots & Shoes

DBD::mysql::st execute failed: You have an error in your SQL syntax near 'AND i.item_id = ix.item_id AND (ix.stock_avail = 'X' OR ix.stock_avail > 0) ' at line 13 at /www/bootbarn.com/htdocs/libraries/multiview-tags.psp line 227.

Re: Having a Hard Time Switching

2005-10-17 15:39 • by rogthefrog
47048 in reply to 47045

Sorry to be hijacking this thread with validation-related posts. I'm taking it to its own section here:

http://thedailywtf.com/forums/47047/ShowPost.aspx#47047

 

Re: Having a Hard Time Switching

2005-10-17 15:40 • by JohnO

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

Re: Having a Hard Time Switching

2005-10-17 15:41 • by Enric Naval
47050 in reply to 47039
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.


If you are using this code in several places you could, of course, make a function, so you can reuse the code in other pages. But maybe I'm a bad programmer :)



This code will probably won't compile, but it is just so you get the idea. I assume _GET is global, but you could pass it by parameter. Q are the postrequisites.




//PARAMETER MANAGING FUNCTION

//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();

Re: Having a Hard Time Switching

2005-10-17 15:44 • by Jenny Simonds
47051 in reply to 47040

Shouldn't be:
.../clever.php?action=save&id=69
.../clever.php?action=edit&id=69
.../clever.php?action=delete&id=69

I know this is nitpicky, but makes hell lot easier to parse.


Darn it, you stole my thunder while I was busy composing my brilliant reply. [:O]


Anyway, the WTF code would end up looking like this:



$editid = (int) $_GET['id'];


 

Re: Having a Hard Time Switching

2005-10-17 15:51 • by Djinn
47052 in reply to 47050
Enric Naval:
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.


If you are using this code in several places you could, of course,
make a function, so you can reuse the code in other pages. But maybe
I'm a bad programmer :)



This code will probably won't compile, but it is just so you get the
idea. I assume _GET is global, but you could pass it by parameter. Q
are the postrequisites.



//PARAMETER MANAGING FUNCTION

//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();





dude .... I don't even know where to begin here .... just forget it ....

Re: Having a Hard Time Switching

2005-10-17 15:52 • by Simon
47053 in reply to 47049
JohnO:

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



My thought exactly, and I thought it was pretty clever.

Re: Having a Hard Time Switching

2005-10-17 15:57 • by diaphanein
47054 in reply to 47050

for the obligatory python one-liner, assuming a global '_get':


def actionIdParamater(): return _get[_get.get('action','id')]

Re: Having a Hard Time Switching

2005-10-17 16:05 • by OMG
LMAOF -- god that is good. and if he/she is being a smart ass, then all the better!

Re: Having a Hard Time Switching

2005-10-17 16:11 • by DrJames
47057 in reply to 47050
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)

Re: Having a Hard Time Switching

2005-10-17 16:15 • by Enric Naval
47058 in reply to 47052
Anonymous:
Enric Naval:
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.

If you are using this code in several places you could, of course, make a function, so you can reuse the code in other pages. But maybe I'm a bad programmer :)


This code will probably won't compile, but it is just so you get the idea. I assume _GET is global, but you could pass it by parameter. Q are the postrequisites.

//PARAMETER MANAGING FUNCTION

//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();



dude .... I don't even know where to begin here .... just forget it ....


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.



</rant>

Re: Having a Hard Time Switching

2005-10-17 16:24 • by kiriran
47060 in reply to 47058
hehe .. that made my day. now i can go with a smile to bed ^^;;

Re: Having a Hard Time Switching

2005-10-17 16:27 • by ItsAllGeekToMe

Rather than a clueless programmers, that had to be an intentional "F U" to his boss.  You don't just happen to figure out how to use the switch statement along with the default case, without somehow reading about the user-defined cases.


That guy rules.

Re: Having a Hard Time Switching

2005-10-17 16:30 • by Anonymous coward
47063 in reply to 47015
Anonymous:
That... is fantastic.




No, it's better; it's BRILLANT.

Re: Having a Hard Time Switching

2005-10-17 16:38 • by Djinn
47064 in reply to 47058
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.

Re: Having a Hard Time Switching

2005-10-17 16:46 • by Scott
47066 in reply to 47063
Am I the only one who finds the switch statement as nasty as a ternary statement? I've never understood why something like:



if x = 5:
    do_this
elif x = 6:
    do_that
else:
    do_something_else



is supposed to be "bad", but



case of:
    x = 5:
        do_this
    x = 6:
        do_that
otherwise:
        do_something_else



is supposed to be "good."

Re: Having a Hard Time Switching

2005-10-17 16:50 • by Anigo Montoya
47068 in reply to 47061
Never attribute to malice that which is adequately explained by stupidity.

Re: Having a Hard Time Switching

2005-10-17 16:50 • by Enric Naval
47069 in reply to 47057
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 :)



Re: Having a Hard Time Switching

2005-10-17 16:55 • by jvancil
47071 in reply to 47064

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


 

Re: Having a Hard Time Switching

2005-10-17 17:04 • by Djinn
47072 in reply to 47071
That is the single most foolish remark I have ever heard. You must be
very, very, young. You do know there are many houses that are art forms
in thier own right? Don't believe me? Look up woodstock (not the hippie
fest).

« PrevPage 1 | Page 2 | Page 3Next »

Add Comment