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
floWenoL
Oct 23, 2002

Mustach posted:

If that's what you really meant, then I'm going to drop it, too. My biggest problem was with the idea that pointer-as-out was some kind of replacement for reading function documentation/asking a coworker; the rest just spun off of that and is apparently well-beaten horse.

Sure. I wasn't arguing for it to be a replacement for documentation, but simply as a way to avoid having to look up the documentation less often, given that certain conditions hold (large code base, enforceable code standards, limited interaction with third-party apps, etc.).

TTS gave a pretty good summary of the differences between his and my view point, and I agree that his position (that the "nullability" of a parameter is an important piece of information to keep) is a valid one. Honestly, the whole thing would be moot if C++ had some way to return multiple values. :v:

Okay let's stop derailing this thread.

Adbot
ADBOT LOVES YOU

Zakalwe
May 12, 2002

Wanted For:
  • Terrorism
  • Kidnapping
  • Poor Taste
  • Unlawful Carnal Gopher Knowledge
boost tuples http://www.boost.org/doc/libs/1_36_0/libs/tuple/doc/tuple_users_guide.html

TR1 has tuples, but that poo poo isn't really official of course. Roll on 0x

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

floWenoL posted:

Honestly, the whole thing would be moot if C++ had some way to return multiple values. :v:

Yeah, I'm not a good person to argue either side of this because I either use boost::tuple or just roll a POD struct if boost isn't allowed by the project spec.

gold brick
Jun 19, 2001

no he isn't

JoeNotCharles posted:

code:
 if (loggedIn) 
    sendFileUpdatedMessageToAnotherApp(loginName, 
                                       about 20 other parameters, 
                                       one per line); 
else 
    sendFileUpdatedMessageToAnotherApp("", 
                                       about 20 other parameters, 
                                       one per line); 
Our old system was like this except that since this was VB, every parameter was also marked Optional :gonk:

ashgromnies
Jun 19, 2004

KaeseEs posted:

Done making GBS threads on the thread, here's a classic from php land, quoted from elsewhere:

I'm curious, just because I'm not a good C coder - what's the proper way to check for overflow?

Standish
May 21, 2001

ashgromnies posted:

I'm curious, just because I'm not a good C coder - what's the proper way to check for overflow?

Let's say you want to check if the expression "a + b" (a, b >= 0) overflows:
code:
if (a > (INT_MAX - b))
a * b (a >= 0, b > 0):
code:
if (a > (INT_MAX / b))
edit: and if you're doing signed arithmetic, you also need to check if their sum would be less than INT_MIN

Standish fucked around with this message at 21:58 on Sep 2, 2008

Aredna
Mar 17, 2007
Nap Ghost

Standish posted:

a * b (a >= 0, b > 0):
code:
if (a > (INT_MAX / b))

Wouldn't this check fail in several cases due to integer math?

For example, when a = 40000 and b = 53688:

A * B = 2,147,520,000
INT_MAX = 2,147,483,648

INT_MAX / b = 39999.32, which will be rounded down to 39999.

Since A > 39999, it'll pass the overflow test.

I'm not sure of the best way to do it either so I'll have to let someone else chime in with how to check for overflows with multiplication.

Standish
May 21, 2001

Aredna posted:

Wouldn't this check fail in several cases due to integer math?

For example, when a = 40000 and b = 53688:

A * B = 2,147,520,000
INT_MAX = 2,147,483,648

INT_MAX / b = 39999.32, which will be rounded down to 39999.

Since A > 39999, it'll pass the overflow test.
The condition evaluating to true is meant to indicate that the value would overflow (i.e. that the test would fail), try for yourself. (I *think* it works but I wouldn't be too surprised if there are corner cases I haven't spotted.)

Standish fucked around with this message at 22:51 on Sep 2, 2008

floWenoL
Oct 23, 2002

Aredna posted:

INT_MAX / b = 39999.32, which will be rounded down to 39999.

Since A > 39999, it'll pass the overflow test.

So? It's still greater than the "real" answer, 39999.32, which is fine.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

floWenoL posted:

So? It's still greater than the "real" answer, 39999.32, which is fine.

39999.32 is the most you can multiply B by without overflowing.

40000 > 39999.32, so it will overflow. A > INT_MAX / B returns true when A is 40000, so the test works.

39999 < 39999.32, so it will NOT overflow. A > INT_MAX / B returns false when A is 39999, so again the test works.

EDIT: oops, I thought you were replying "So?" to Standish's explanation.

Aredna
Mar 17, 2007
Nap Ghost
Oops... guess I should have looked at a test that passes before replying.

Aredna fucked around with this message at 03:03 on Sep 3, 2008

Wreckus
Dec 15, 2007

From birth, man carries the weight of gravity on his shoulders. He is bolted to earth. But man has only to sink beneath the surface and he is free.

Ranma4703 posted:

I've been looking through a large system recently, since I just started a new co-op and I have to get caught up. This one coder (who I've never met) has stuff like this in all his classes:
private static final int FIVE = 5;
private static final int NEG_ONE = -1;
private static final int FIVE_BILLION = 5000000000;
private static final String SPACE_PIPE_EQUALS = " |=";
private static final String ERROR_WITH_CODE = "Error with code";

I do this (I'm a coding newbie), mostly because I can't figure out how to get poo poo to work correctly in VBscript.

Example:

code:
username = WshNetwork.username
slash = "\"

For Each subkey In arrSubKeys
Wshshell.Regwrite "HKEY_CURRENT_USER\Software\Localapp\" & subkey & slash & username, 1, "REG_DWORD"
drat you slash :argh:

Midelne
Jun 19, 2002

I shouldn't trust the phones. They're full of gas.
This may be a little simple for CoC, but my boss set this as a startup script under the default domain policy yesterday. systems.txt is a text file that contains the names of the computers in our domain.

code:
pushd %~0\..
for /f %%i in (systems.txt) do call :Check %%i
popd 
goto :eof

:check
md \\%1\c$\progra~1\mvterm
copy C:\mvbaseup\files\*.* \\%1\c$\progra~1\mvterm /Y
cacls \\%1\c$\progra~1\mvterm /T /E /C /G everyone:C
goto :eof
It's only horrible code when you consider that this was set to run on every single computer in the domain, all of which would've attempted to perform the update operation on every single computer in the domain.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Ranma4703 posted:

I've been looking through a large system recently, since I just started a new co-op and I have to get caught up. This one coder (who I've never met) has stuff like this in all his classes:
private static final int FIVE = 5;
private static final int NEG_ONE = -1;
private static final int FIVE_BILLION = 5000000000;
private static final String SPACE_PIPE_EQUALS = " |=";
private static final String ERROR_WITH_CODE = "Error with code";

These are some of the things that exist in the code I'm working with now:

code:
  public static final String COLON = ":";
  public static final String COMMA = ",";
  public static final String DASH = "-";
  public static final String DOT = ".";
  public static final String EMPTY_STRING = "";
  public static final String UNDERSCORE = "_";
  public static final String PIPE = "|";
  public static final String RIGHT_ARROW = ">";
  public static final String LEFT_ARROW = "<";
  public static final String PAREN_LEFT = "(";
  public static final String PAREN_RIGHT = ")"; 
  public static final String NEW_LINE = "\n";
  public static final String SPACES_ONE = " ";
  public static final String SPACES_TWO = "  ";
:gbsmith:

Sivart13
May 18, 2003
I have neglected to come up with a clever title

Kilson posted:

These are some of the things that exist in the code I'm working with now:
living with that code sounds like living in a living nightmare

BattleMaster
Aug 14, 2000

Kilson posted:

These are some of the things that exist in the code I'm working with now:

So what is it that makes people think it's a good idea to use these constants with long-rear end names instead of typing two quotes and a character? I've seen this quite a lot and there has to be a reason, right?!

sonic bed head
Dec 18, 2003

this is naturual, baby!

BattleMaster posted:

So what is it that makes people think it's a good idea to use these constants with long-rear end names instead of typing two quotes and a character? I've seen this quite a lot and there has to be a reason, right?!

Increases readability! :2bong:

KaeseEs
Feb 23, 2007

by Fragmaster

BattleMaster posted:

So what is it that makes people think it's a good idea to use these constants with long-rear end names instead of typing two quotes and a character? I've seen this quite a lot and there has to be a reason, right?!

Yeah you could but what if the value of five billion changes next week :( :aaa:

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

KaeseEs posted:

Yeah you could but what if the value of five billion changes next week :( :aaa:

In the case of five billion it sort of makes sense because if you're typing 5000000 over and over again it's really easy to drop a 0 accidentally.

But the constant SHOULD be named something that explains what that number is used for, not just what the number is.

floWenoL
Oct 23, 2002

JoeNotCharles posted:

In the case of five billion it sort of makes sense because if you're typing 5000000 over and over again it's really easy to drop a 0 accidentally.

If you were using Perl you'd be able to type 5_000_000. :colbert:

Vanadium
Jan 8, 2005

floWenoL posted:

If you were using Perl you'd be able to type 5_000_000. :colbert:

We can probably come up with something that lets you type num<5,000,0wait this is not going to work :(

Aredna
Mar 17, 2007
Nap Ghost

floWenoL posted:

JoeNotCharles posted:

In the case of five billion it sort of makes sense because if you're typing 5000000 over and over again it's really easy to drop a 0 accidentally.
If you were using Perl you'd be able to type 5_000_000. :colbert:

For example, 5 billion has 9 zeros instead of 6.

Karanth
Dec 25, 2003
I need to finish Xenogears sometime, damn it.

Vanadium posted:

We can probably come up with something that lets you type num<5,000,0wait this is not going to work :(
code:
int big_number(int thousands, int ones);
int big_number(int millions, int thousands, int ones);
...
code:
num < big_number(5,000,000)
:downs:

_aaron
Jul 24, 2007
The underscore is silent.

Karanth posted:

:downs:
Oh gently caress you that is brilliant and terrible.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Karanth posted:

code:
int big_number(int thousands, int ones);
int big_number(int millions, int thousands, int ones);
...
code:
num < big_number(5,000,000)
:downs:

int num = big_number(5,010,000);
printf("num = %d\n", num);


quote:

num = 5008000

:wotwot:

Standish
May 21, 2001

Flobbster posted:

int num = big_number(5,010,000);
printf("num = %d\n", num);



:wotwot:
gently caress octal seriously, has anyone ever encountered it where it wasn't causing a weird bug with leading zeroes?

Vanadium
Jan 8, 2005

Standish posted:

gently caress octal seriously, has anyone ever encountered it where it wasn't causing a weird bug with leading zeroes?

chmod(1) :geno:

Karanth
Dec 25, 2003
I need to finish Xenogears sometime, damn it.

Flobbster posted:

int num = big_number(5,010,000);
printf("num = %d\n", num);

:wotwot:
You take your practicality and logic and get out, mister. <:mad:> Clearly it's not a bug, it's a feature made to test the skill of anyone using it. Real Programmers will substitute whitespace for leading zeros anywhere it would cause a problem.
code:
num < big_number(5, 10,000)
See that's perfectly readable. Why do you hate readable code? :colbert:

Edit: VVV You could, but then you wouldn't be able to quiz the newbie programmers every time they type a constant. :pseudo:

Karanth fucked around with this message at 20:42 on Sep 4, 2008

That Turkey Story
Mar 30, 2003

Karanth posted:

code:
int big_number(int thousands, int ones);
int big_number(int millions, int thousands, int ones);
...
code:
num < big_number(5,000,000)
:downs:

That won't work, but if you're sly, you can do it with that syntax using macros :clint:

KaeseEs
Feb 23, 2007

by Fragmaster

JoeNotCharles posted:

In the case of five billion it sort of makes sense because if you're typing 5000000 over and over again it's really easy to drop a 0 accidentally.

But the constant SHOULD be named something that explains what that number is used for, not just what the number is.

I suppose I should have been more explicit with what I was getting at, eg. "What if in two months English switches commas with apostrophes!"

Nehle
Dec 7, 2004

Kung Fredrik af Ullevi
I recently started working as a web developer for a small company. My first task was completing and fixing a web shop built by a previous employee. Now, he had built a (mostly) fine MVC framework to handle the whole thing, but the thing was slow as hell, so we tried to find some way to optimize this.

The way it works is that as soon as anyone enter the shop (it's for cellphones, by the way) we give them a session only for that visit, and store all session data in the database. As a session ID, we give them an md5 of the auto_increment value for their order (a simple mask, really, so people won't go poking around with the query string too much).

First he used the brilliant code to get the last insert id

code:
$randnbr = generate_random_nbr();
$time = time();
$userid = mysql_real_escape_string($userid);
$sql->query("INSERT INTO Orders(`userid`,`time`,`insert_id`,....) VALUES ('$userid',$time,$randnbr,.....)");
$id = $sql->query("SELECT Order_ID FROM Orders WHERE userid='$userid' AND time='$time' and randnbr='$randnbr');
code:
SELECT LAST_INSERT_ID()
:ssh:

But the best part was how he got their session from the database using the ID they sent
code:
SELECT * FROM Orders WHERE MD5(CAST(Order_ID AS CHAR)) = $orderid
That's right, he hashed every single ID in the table with a few hundred thousand entries just to get the order row :downs: (Also every time he needed to update that row), which is quite naturally somewhere at the very end of the table. Not that it matters because he didn't LIMIT 1 anyways

We quickly stored the md5 in a seperate field and added an index to that field, lowering the execution speed from a few seconds to a few milliseconds.

Nehle fucked around with this message at 16:46 on Sep 6, 2008

POKEMAN SAM
Jul 8, 2004

Nehle posted:

code:
SELECT LAST_INSERT_ID()
:ssh:

You don't want to do this. What if two people are accessing the website at the same time? Your two queries are not one atomic operation, meaning that two individuals' INSERT statements could fire and then their two SELECT statements (not always INSERT SELECT INSERT SELECT). Then they'd both get the same result back from LAST_INSERT_ID() which is obviously NOT what you want.

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

Ugg boots posted:

You don't want to do this. What if two people are accessing the website at the same time? Your two queries are not one atomic operation, meaning that two individuals' INSERT statements could fire and then their two SELECT statements (not always INSERT SELECT INSERT SELECT). Then they'd both get the same result back from LAST_INSERT_ID() which is obviously NOT what you want.

The function returns the last ID inserted on the current connection. As long as those two users' inserts were performed on different connections, they will NOT get the same result from LAST_INSERT_ID().

No Safe Word
Feb 26, 2005

DaTroof posted:

The function returns the last ID inserted on the current connection. As long as those two users' inserts were performed on different connections, they will NOT get the same result from LAST_INSERT_ID().

I believe you mean transaction instead of connection, but obviously each connection will be a different transaction :)

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

No Safe Word posted:

I believe you mean transaction instead of connection, but obviously each connection will be a different transaction :)

The value of LAST_INSERT_ID() is still connection-specific without transactions.

POKEMAN SAM
Jul 8, 2004

DaTroof posted:

The function returns the last ID inserted on the current connection. As long as those two users' inserts were performed on different connections, they will NOT get the same result from LAST_INSERT_ID().

That's fair then.

kalleboo
Jan 13, 2001

Hjälp

Nehle posted:

code:
SELECT LAST_INSERT_ID()
:ssh:
In PHP you can even do mysql_insert_id() and avoid the whole mysql_query() bit. Of course, you should be using mysqli....

Nehle
Dec 7, 2004

Kung Fredrik af Ullevi

kalleboo posted:

In PHP you can even do mysql_insert_id() and avoid the whole mysql_query() bit. Of course, you should be using mysqli....

We have or own DAO wrapper for MySQl though, and I'm pretty sure I've read somewhere that mysql_insert_id() / mysqli->insert_id may give undesirable results and that doing a proper SELECT is preferred.

Mario Incandenza
Aug 24, 2000

Tell me, small fry, have you ever heard of the golden Triumph Forks?
There's more ifs in the original source but I felt this illustrated the point sufficiently:
code:
foreach my $Field (split /,/, $Params{FieldList}) {
            if ( $Field eq "DomainStatus" ) {
               my @Status = $dri->get_info('status')->list_status();
               for my $Stat (@Status) {
                  $Return{$Field} .= $Stat.",";
               }
               chop $Return{$Field};
            }
            if ( $Field eq "CreateDate" ) {
               $Return{$Field} = $dri->get_info('crDate');
               substr($Return{$Field},10) = "";
            }
            if ( $Field eq "ExpiryDate" ) {
               $Return{$Field} = $dri->get_info('exDate');
               substr($Return{$Field},10) = "";
            }
            if ( $Field eq "TransferDate" ) {
               if ($dri->get_info('trDate')) {
                  $Return{$Field} = $dri->get_info('trDate');
                  substr($Return{$Field},10) = "";
               }
            }

            $Return{$Field} = $Hosts[0]  if ( $Field eq "PrimaryNameServer" );
            $Return{$Field} = $Hosts[1]  if ( $Field eq "SecondaryNameServer" );
            $Return{$Field} = $Hosts[2]  if ( $Field eq "Other1NameServer" );
            $Return{$Field} = $Hosts[3]  if ( $Field eq "Other2NameServer" );
            $Return{$Field} = $Hosts[4]  if ( $Field eq "Other3NameServer" );
            $Return{$Field} = $Hosts[5]  if ( $Field eq "Other4NameServer" );
            $Return{$Field} = $Hosts[6]  if ( $Field eq "Other5NameServer" );
            $Return{$Field} = $Hosts[7]  if ( $Field eq "Other6NameServer" );
            $Return{$Field} = $Hosts[8]  if ( $Field eq "Other7NameServer" );
            $Return{$Field} = $Hosts[9]  if ( $Field eq "Other8NameServer" );
            $Return{$Field} = $Hosts[10] if ( $Field eq "Other9NameServer" );
            $Return{$Field} = $Hosts[11] if ( $Field eq "Other10NameServer" );
            $Return{$Field} = $Hosts[12] if ( $Field eq "Other11NameServer" );
}

Adbot
ADBOT LOVES YOU

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
Hmm
code:
sometype GetInstance(string Reg)
{
      switch (Reg)
      {
            case "first_field":
                  return first_field;
            case "second_field":
                  return second_field;
            case "third_field":
                  return third_field;
            case "fourth_field":
                  return fourth_field;
            case "fifth_field":
                  return fifth_field;
             .
             .
             .
      }
}
For 11,000 lines. This is in C#. Ignoring problems with the program's structure, I was able to turn this into about 5 lines of code with reflection.

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