Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Bozart posted:

I am totally unfamiliar with PHP, but why wouldn't you just use an else if? That break in each of the if blocks makes me want to check that it exists in all of them or if there is some kind of bizzaro override.

I tried using if... else if... else if... else but didn't like the way it turned out, chiefly because it's too easy to end up with something like this:

code:
if ( /* Error condition 1 */ ) {
    // handle error
} else if ( /* Error condition 2 */ ) {
    // handle error
} else {
    // do something
    if ( /* Error condition 3 */ ) {
        // handle error
    } else if ( /* Absence of error condition 4 */ ) {
        if ( /* Error condition 5 */ ) {
            // handle error
        } else if ( /* Error condition 6 */ ) {
            // handle error
        } else {
            // do something else
            if ( /* Absence of error condition 7 */ ) {
                // Do what I wanted to do
                // (see how much of a chore this is to find)
            } else {
                // handle error
            }
        }
    } else {
        // handle error
    }
}
Using do... while false allows all of the error conditions to be separated, and I can do work between the if blocks if I want to. The if blocks all have the same form (set a certain number of variables, follow last of all with break) and it's quite easy to check over.

Adbot
ADBOT LOVES YOU

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

Hammerite posted:

I would use goto, but it isn't available in PHP until version 5.3.
This is actually quite amazing. For all the weird quirks and invitations to abuse the language PHP has, it only recently acquired the goto statement?

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Sagacity posted:

This is actually quite amazing. For all the weird quirks and invitations to abuse the language PHP has, it only recently acquired the goto statement?

Yup, I was surprised when I realised this as well.

nullfox
Aug 19, 2008

Hammerite posted:

code:
$error_type = false;
$error_message = '';

do {

    if ( /* Error condition 1 /* ) {
        $error_type = 1;
        $error_message = 'Type 1 error';
        break;
    }

    if ( /* Error condition 2 /* ) {
        $error_type = 2;
        $error_message = 'Type 2 error';
        break;
    }

    ...

    if ( /* Error condition n /* ) {
        $error_type = n;
        $error_message = 'Type n error';
        break;
    }

} while (false);

if ( $error_type !== false ) {
    // Report error to user as appropriate
} else {
    // Go ahead and do something; no error conditions satisfied
}

Ever considered using Exceptions?

code:
try {
  do {
    if ( /* Error condition 1 /* ) {
        throw new Exception('Something bad happened', 1);
    }

    if ( /* Error condition 2 /* ) {
        throw new Exception('Something else bad happened', 2);
    }
  } while (false);
} catch(Exception $e) {
  // Report error to user
  printf('Something hosed up: %s (%d)', $e->getMessage(), $e->getCode());
}

// No error conditions - Continue execution

MononcQc
May 29, 2007

PHP has lots of crap in it (see the nth debate about it in here), but the loose typing system is hardly an horror in itself compared to a weird design decision.

Most people would never even complain about it had the operators '==' and '===' or '!=' and '!==' been reversed on which is loose and which is strict. You could use PHP in an entirely strict manner (note: strict, not statically typed) by using the right operators and annotating function arguments with types:

http://ideone.com/ulkD2

So this is

php:
<?php
 
function untyped_plus($x$y$z)
{
    return $x $y $z;
}
 
function typed_plus(double $xint $ystring $z)
{
    return $x $y $z;
}
 
function partially_typed_plus(double $xint $y$z)
{
    return $x $y $z;
 }
 
// main yes
$x 4.0;
$y 6;
$z "2";
 
echo untyped_plus($x$y$z)."\n"// should be 12
 
echo partially_typed_plus($x$y$z)."\n"// works. 12
 
echo typed_plus($x$y$z); // crashes
?>

Which outputs...

quote:

12

Catchable fatal error: Argument 1 passed to partially_typed_plus() must be an instance of double, double given, called in /home/JxdxAo/prog.php on line 25 and defined in /home/JxdxAo/prog.php on line 13

:suicide:

Fehler
Dec 14, 2004

.

Hammerite posted:

Using do... while false allows all of the error conditions to be separated, and I can do work between the if blocks if I want to. The if blocks all have the same form (set a certain number of variables, follow last of all with break) and it's quite easy to check over.
I always do something like this:

code:
$e = array();
if($error1) {
    $e[] = 'error1!';
}

if($error2) {
    $e[] = 'error2!';
}

if(!empty($e)) {
    //print out all messages
} else {
    //do stuff
}
This has the advantage of checking for all possible errors and not just breaking after the first one, which is nice for form validation.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

Hammerite posted:

I'm sorry, but I don't understand your reasoning. How is that in any way an implementation of the if control structure?
Oops, I misread the code. I missed that i is declared in the loop head. My point about its badness still stands though, only now more extreme: It is a completely worthless construct.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

WildFoxMedia posted:

Ever considered using Exceptions?

I've heard of them but I haven't made the effort to learn about them yet. I'm a little suspicious of them because I don't understand where the flow of control goes when one happens, but this is entirely down to me not knowing anything about how they work.

Fehler posted:

I always do something like this: (code)

Yes, in places where I want to list all the errors (rather than stop after the first one) I do something similar.

Lysandus
Jun 21, 2010
Exceptions are great until they are thrown 14 calls back with no indications of which method threw it.

:suicide:

NotShadowStar
Sep 20, 2000
What crazytown language doesn't vomit a stack dump when you get an uncaught exception?

Lysandus
Jun 21, 2010

NotShadowStar posted:

What crazytown language doesn't vomit a stack dump when you get an uncaught exception?

RIMs bastard java they put on Blackberrys.

HFX
Nov 29, 2004

Lysandus posted:

RIMs bastard java they put on Blackberrys.

Sounds like OCAP.


If you are doing C, you should be able to write a macro that embeds line numbers and more into the exceptions message.

Big Nubbins
Jun 1, 2004
I thought I'd share this little gem by a programmer we recently sacked because he told my boss in all seriousness that he deserved a 100% pay raise. The gist is that it loops through an array of member objects which may have duplicates in it and produces an array with no duplicates.

code:
$unid_array = Array();
$y=0;
$recalc_array = false;
for ($z=0; $z<count($o_members); $z++) {
	$found = false;
	for ($x=0; $x<count($unid_array); $x++) {
		if ($o_members[$z]->get_unid() == $unid_array[$x])
			$found = true;
	}
	
	if ($found) {
		$recalc_array = true;
		$unid_array[$y] = 0;
	} else {
		$unid_array[$y] = $o_members[$z]->get_unid();
	}
	$y++;
}
if ($recalc_array) {
	$o_members2 = Array();
	$y=0;
	for ($z=0; $z<count($o_members); $z++) {
		if ($unid_array[$z] != 0) {
			$o_members2[$y] = $o_members[$z];
			$y++;
		}
	}
	$o_members = $o_members2;
}
:psyduck:

zootm
Aug 8, 2006

We used to be better friends.

NotShadowStar posted:

What crazytown language doesn't vomit a stack dump when you get an uncaught exception?
Interestingly if you're using java.util.concurrent you do not get a stack trace if your task dies, you have to check the return value of your Future instance when it completes. This catches people out when they're using them as "a nicer way to spawn threads".

nullfox
Aug 19, 2008

Hammerite posted:

I've heard of them but I haven't made the effort to learn about them yet. I'm a little suspicious of them because I don't understand where the flow of control goes when one happens, but this is entirely down to me not knowing anything about how they work.


Yes, in places where I want to list all the errors (rather than stop after the first one) I do something similar.

loving Exceptions, how do they work? http://us.php.net/manual/en/language.exceptions.php

crazyfish
Sep 19, 2002

zootm posted:

Interestingly if you're using java.util.concurrent you do not get a stack trace if your task dies, you have to check the return value of your Future instance when it completes. This catches people out when they're using them as "a nicer way to spawn threads".

You can get them if you register a default uncaught exception handler (http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#getDefaultUncaughtExceptionHandler%28%29) but the type of people you describe in your last sentence probably wouldn't have figured this out either.

Bozart
Oct 28, 2006

Give me the finger.

Hammerite posted:

I tried using if... else if... else if... else but didn't like the way it turned out, chiefly because it's too easy to end up with something like this:

code:
if ( /* Error condition 1 */ ) {
    // handle error
} else if ( /* Error condition 2 */ ) {
    // handle error
} else {
    // do something
    if ( /* Error condition 3 */ ) {
        // handle error
    } else if ( /* Absence of error condition 4 */ ) {
        if ( /* Error condition 5 */ ) {
            // handle error
        } else if ( /* Error condition 6 */ ) {
            // handle error
        } else {
            // do something else
            if ( /* Absence of error condition 7 */ ) {
                // Do what I wanted to do
                // (see how much of a chore this is to find)
            } else {
                // handle error
            }
        }
    } else {
        // handle error
    }
}
Using do... while false allows all of the error conditions to be separated, and I can do work between the if blocks if I want to. The if blocks all have the same form (set a certain number of variables, follow last of all with break) and it's quite easy to check over.

else ifs + exceptions removes the need for those nested structures, doesn't take up as much room, and is easier to read.

(pseudo-)
code:
if ( /* Error condition 1 */ ) {
    throw exception 1
} else if ( /* Error condition 2 */ ) {
    throw exception 2
}

// do something
if ( /* Error condition 3 */ ) {
   throw exception 3
} else if ( /* error condition 4 you were just obfuscating*/ ) {
   throw exception 4
} else if ( /* Error condition 5 */ ) {
   throw exception 5
} else if ( /* Error condition 6 */ ) {
   throw exception 6
} 

// do something else
if ( /* error condition 7 that was also backwards*/ ) {
   throw exception 7
}

// Do what I wanted to do
// (see how there was no nesting and everything looks the same?)
}

// this part you might end up registering somewhere, or just putting into
// a try structure, or who knows what depending on your language
catch  exception n {
   say "Hey I got Exception n!"
}
What I often end up doing is throwing those exception throwing blocks into their own void functions, like NeedHourlyData(DataThatImChecking). All that code above just becomes

NeedCondition1(StateData1,StateData2)
NeedCondition2(DEFCON1,DEFCON0)

Do stuff..
NeedCondition1(DifferentStateData1,DifferentStateData2)

etc.

Then again maybe I'm an oddball. Sorry for the long post.

w00tz0r
Aug 10, 2006

I'm just so god damn happy.
I've mentioned before that I work in a C++ dev shop.

We have a ton of objects being dumped in a hash map that my coworker wants to iterate over efficiently. Rather than writing or finding an implementation of a LinkedHashMap or similar, he has rolled his own memory pool and overloaded operator new() to ensure that they're all next to each other in memory, so that he can use pointer arithmetic or something.

ToxicFrog
Apr 26, 2008


Lysandus posted:

RIMs bastard java they put on Blackberrys.

:argh:

That whole thing is a coding horror.

My favorite part was probably finding out that in a multithreaded app, blocking the UI thread would block the entire application, including the background thread that pings the robot every 50ms to keep it from going into full reverse and destroying something.

Although, to be fair, the robot was around 4-5 horrors on its own. That entire project was a clusterfuck.

Zombywuf
Mar 29, 2008

w00tz0r posted:

I've mentioned before that I work in a C++ dev shop.

We have a ton of objects being dumped in a hash map that my coworker wants to iterate over efficiently. Rather than writing or finding an implementation of a LinkedHashMap or similar, he has rolled his own memory pool and overloaded operator new() to ensure that they're all next to each other in memory, so that he can use pointer arithmetic or something.

A linked list is not a particularly efficient way to iterate.

baquerd
Jul 2, 2007

by FactsAreUseless

Zombywuf posted:

A linked list is not a particularly efficient way to iterate.

Please describe how to iterate over an entire list in less than O(1)... If you're referring to a specific implementation of linked lists, don't do that.

Zombywuf
Mar 29, 2008

baquerd posted:

Please describe how to iterate over an entire list in less than O(1)... If you're referring to a specific implementation of linked lists, don't do that.

Yes, obviously I am talking about asymptotic complexity. Go away and learn about caching.

baquerd
Jul 2, 2007

by FactsAreUseless

Zombywuf posted:

Yes, obviously I am talking about asymptotic complexity. Go away and learn about caching.

Please, just because you implement linked lists in a naive fashion does not mean that you can't arrange them in a memory efficient manner.

Zombywuf
Mar 29, 2008

baquerd posted:

Please, just because you implement linked lists in a naive fashion does not mean that you can't arrange them in a memory efficient manner.

You mean write a custom allocator that places them in a contiguous memory block so they can be traversed by simple pointer arithmetic. Hey, if you were to do that you could eliminate the need for the next pointer and just treat it as an array. What an awesome idea!

baquerd
Jul 2, 2007

by FactsAreUseless

Zombywuf posted:

You mean write a custom allocator that places them in a contiguous memory block so they can be traversed by simple pointer arithmetic. Hey, if you were to do that you could eliminate the need for the next pointer and just treat it as an array. What an awesome idea!

This is true for smaller objects where your pro-caching technique works well. For large objects that may not even fit in the cache in the first place, the original LinkedHashMap is in fact a great choice, and there are many further optimizations depending on how pedantic you want to be and how far you want to mess up your data structure.

Zombywuf
Mar 29, 2008

baquerd posted:

This is true for smaller objects where your pro-caching technique works well. For large objects that may not even fit in the cache in the first place, the original LinkedHashMap is in fact a great choice, and there are many further optimizations depending on how pedantic you want to be and how far you want to mess up your data structure.

If your objects are too large to even fit in your level 2 cache then you need to start worrying about separating the key part of your data from the value, otherwise a hash table is probably the wrong structure. Judging by his description of the problem I'm going to stick with assuming w00tz0r is just wrong.

Even if he's not the C++ way to do it would not be copying parts of the Java standard library, also linked lists are still the death of efficiency in all but a very few cases.

A very bad man
Mar 31, 2010
I can't post the code, because it's no individual line that makes it a crime against humaity. It's 8912 line Perl module that implements some bastard homegrown version of OO that I have to rewrite at work.

Larry Wall posted:

Perl is cute, funny, fun, smart, and trendy. Other languages are stodgy, boring, depressing, and have no sense of humor.

gently caress you Larry.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."

ToxicFrog posted:

:argh:

That whole thing is a coding horror.

My favorite part was probably finding out that in a multithreaded app, blocking the UI thread would block the entire application, including the background thread that pings the robot every 50ms to keep it from going into full reverse and destroying something.

Although, to be fair, the robot was around 4-5 horrors on its own. That entire project was a clusterfuck.

Fun fact: in "RIM Java", static initialization on final variables can be fired every time the classloader of a subclass is executed.

Oh, and "Error 523", the magical "gently caress you" error message that tells you nothing other than that RIM wrote a Java implementation that can produce kernel panics for ill-defined reasons.

Zombywuf
Mar 29, 2008

A very bad man posted:

I can't post the code, because it's no individual line that makes it a crime against humaity. It's 8912 line Perl module that implements some bastard homegrown version of OO that I have to rewrite at work.

That has nothing to do with Perl, I used to have to maintain a 60,000 line XSLT file.

tef
May 30, 2004

-> some l-system crap ->
Luxury!

Lysandus
Jun 21, 2010

Internet Janitor posted:

Fun fact: in "RIM Java", static initialization on final variables can be fired every time the classloader of a subclass is executed.

Try this with strings and watch your memory footprint EXPLODE INTO WONDERLAND!

NotShadowStar
Sep 20, 2000
Man just when I thought I heard everything about Java being terrible. I wonder how RIM isn't sued to hell from Oracle like they're doing with Google.

On one had I wish Oracle would self destruct Java so as a whole we could move on to something interesting, on the other that would be bad as legions of absolutely awful Indians and eastern Europeans working for $10/hr are unleashed unsuspecting on the rest of everything, Enterprising everything they touch. It happened with C#!

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Yeah I hate when the browns mess up my code.

Remmiz
May 3, 2009

GRUUUUUUMMBLES!
code:
end = start + (items.Count() - start);
short but sweet.

Viggen
Sep 10, 2010

by XyloJW
I deal with PHP daily. I get a new bit of death inside every day.

Someone doesn't know how to do events, so here's how they did them:

code:
$expireDaemon = time() + ($cron_time_set * 60);
while (time() < $expireDaemon) {
  while ($looper = mysql_query("SELECT `something expensive here`")) {;
    ...
    $nested2deep = mysql_query("SELECT `fire_time` FROM `whythehell`");
    if ($nested2deep['firetime'] == date("H-m-s")) {
       $this->die_a_little_inside();
    }
 }
}
I did something like this in 2005, and I'm still not proud, but this takes the cake - thank god this function isn't exposed- not that the rest of the system has any sanitizing:

code:
function cacheRead($file) {
                if (file_exists('../tmp/cache/'.$file)) {
                        $data = file('../tmp/cache/'.$file);
                        if(time() < $data[0]) {
                                return unserialize($data[1]);
                        } else {
                                unlink('../tmp/cache/'.$file);
                        return null;
                        }
                } else {
                        return null;
                }
}
 
Here's part of the glory that is cacheWrite() - I love the comment. I can only assume they were worried about NFS/filesystem caching, or more likely, never heard of filemtime():

code:
                $lineBreak = "\n"; // this function will NOT work on a windows server without further modification
                $data = serialize($data);
                $expires = time() + $duration;
                $contents = $expires . $lineBreak . $data . $lineBreak;
                $write = '../tmp/cache/'.$file;
                $result = fopen($write, 'w');
                if (is_writable($write)) {
                        if (!$handle = fopen($write, 'a')) {
                                return false;
                        }
                        if (fwrite($result, $contents) === false) {
                                return false;
                        }
                        fclose($result);
                        return true;
                } else {
                     return false;
                }
Ah hell, here's another one, because explode() and array_shift() don't exist for a reason. Let's just overwrite the superglobal:

code:
$_SERVER['SERVER_NAME'] = str_replace('www.', '', $_SERVER['SERVER_NAME']);

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
My friend was taking an online quiz and I noticed how lovely the website looked, so I did a View->Source to have a laugh. All of the answers to the questions were in there as <input type="hidden"/>. Not only that, but the last 10 questions had incorrect answers marked in the key. After you finish the quiz it doesn't tell you your score or which ones you got wrong, it's just a pass/fail, so who knows how long this has gone by without notice.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

fletcher posted:

My friend was taking an online quiz and I noticed how lovely the website looked, so I did a View->Source to have a laugh. All of the answers to the questions were in there as <input type="hidden"/>. Not only that, but the last 10 questions had incorrect answers marked in the key. After you finish the quiz it doesn't tell you your score or which ones you got wrong, it's just a pass/fail, so who knows how long this has gone by without notice.

What kind of online quiz? One of those "WHICH FAMILY GUY CHARACTER ARE U???" type ones, or something important?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Hammerite posted:

What kind of online quiz? One of those "WHICH FAMILY GUY CHARACTER ARE U???" type ones, or something important?

Slightly more important than that type of quiz, but not terribly important. It was a quiz that the company gives its employees to see if they are knowledgeable enough to sell a certain product. I notified them about the stupidity anyways.

w00tz0r
Aug 10, 2006

I'm just so god damn happy.

Zombywuf posted:

If your objects are too large to even fit in your level 2 cache then you need to start worrying about separating the key part of your data from the value, otherwise a hash table is probably the wrong structure. Judging by his description of the problem I'm going to stick with assuming w00tz0r is just wrong.

Even if he's not the C++ way to do it would not be copying parts of the Java standard library, also linked lists are still the death of efficiency in all but a very few cases.

You're right, I'm totally off the mark with this one. My original plan was to use a vector, since it has contiguous memory allocation, rather than a linked list; LinkedHashMap was a terrible example, I was thinking of complexity, not efficiency.

I forgot we were storing pointers to the objects, not the object themselves; so even if we used a contiguous block of memory to store them, we'd still get cache misses when we went to dereference the pointers.

Adbot
ADBOT LOVES YOU

Kelson
Jan 23, 2005

Bozart posted:

else ifs + exceptions removes the need for those nested structures, doesn't take up as much room, and is easier to read.

(pseudo-)
code:
try
{
   if ( /* Error condition 1 */ ) {   throw exception 1 }
   else if ( /* Error condition 2 */ ) { throw exception 2 }

   // do something
   if ( /* Error condition 3 */ ) {   throw exception 3 }
   else if ( /* error condition 4 you were just obfuscating*/ ) { throw exception 4 }
   else if ( /* Error condition 5 */ ) { throw exception 5 }
   else if ( /* Error condition 6 */ ) { throw exception 6 } 

   // do something else
   if ( /* error condition 7 that was also backwards*/ ) {  throw exception 7 }

   // Do what I wanted to do
   // (see how there was [almost] no nesting and everything looks the same?)
}

// this part you might end up registering somewhere, or just putting into
// a try structure, or who knows what depending on your language
catch  exception n {
   say "Hey I got Exception n!"
}
What I often end up doing is throwing those exception throwing blocks into their own void functions, like NeedHourlyData(DataThatImChecking). All that code above just becomes

NeedCondition1(StateData1,StateData2)
NeedCondition2(DEFCON1,DEFCON0)

Do stuff..
NeedCondition1(DifferentStateData1,DifferentStateData2)

etc.

Then again maybe I'm an oddball. Sorry for the long post.

You don't need to bother with else clauses if you throw an exception. It breaks the normal program flow. That becomes less annoying if implemented as exception throwing functions though. On the other hand, you've already got the else blocks to avoid the non-linear exception handling altogether.

code:
if ( /* Error condition 1 */ ) {   handle exception 1 }
else if ( /* Error condition 2 */ ) { handle exception 2 }
else
{
   // do something
   if ( /* Error condition 3 */ ) {   handle exception 3 }
   else if ( /* obfuscated error condition 4*/ ) { handle exception 4 }
   else if ( /* Error condition 5 */ ) { handle exception 5 }
   else if ( /* Error condition 6 */ ) { handle exception 6 } 
   else
   {

      // do something else
      if ( /* error condition 7 that was also backwards*/ ) {  handle exception 7 }
      else
      {
         // Do what I wanted to do
         // (see how there was no nesting and everything looks the same?)
      }
   }
}
The previous use is essentially just opaque gotos; here's a familiar version!
code:
do
{
   if ( /* Error condition 1 */ ) { handle exception 1; break; }
   if ( /* Error condition 2 */ ) { handle exception 2; break; }

   // do something
   if ( /* Error condition 3 */ ) { handle exception 3; break; }
   if ( /* Error condition 4 */ ) { handle exception 4; break; }
   if ( /* Error condition 5 */ ) { handle exception 5; break; }
   if ( /* Error condition 6 */ ) { handle exception 6; break; }

   // do something else
   if ( /* error condition 7 */ ) { handle exception 7; break; }

   // Do what I wanted to do
   // (see how there was no nesting and everything looks the same?)
} while(0);

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply