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
That Turkey Story
Mar 30, 2003

Fehler posted:

I actually had a good reason for this as well, as there was gonna be a final else that handled all lines after the third one.

If you think that was a good reason to do this you need to quit programming forever!

Adbot
ADBOT LOVES YOU

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Fehler posted:

I actually had a good reason for this as well, as there was gonna be a final else that handled all lines after the third one.

code:
fgets(line, sizeof(line), file);
do stuff with first line
fgets(line, sizeof(line), file);
do stuff with second line
while (!feof(file)) {
do stuff
}

spiritual bypass
Feb 19, 2008

Grimey Drawer
My task today at work is to get our software configured to send data to somebody else's SOAP service. I do this all the time, so it shouldn't be a big deal.
This service is a bit different; it's expecting to receive a single argument to its function rather than a whole list of arguments like usual. This single argument is a huge XML document that just gets pasted into a node in the SOAP document. No, it's not a complex type. It means the WSDL file is almost useless now, defeating the purpose of SOAP.

How did this happen??

Zombywuf
Mar 29, 2008

royallthefourth posted:

How did this happen??

You've only ever used SOAP to communicate between services written using the same SOAP framework haven't you?

SOAP and WSDL represent about 4 different protocols all disguised as the same standard.

Fehler
Dec 14, 2004

.

Ryouga Inverse posted:

code:
fgets(line, sizeof(line), file);
do stuff with first line
fgets(line, sizeof(line), file);
do stuff with second line
while (!feof(file)) {
do stuff
}

code:
if(!feof(file)) {
 fgets(line, sizeof(line), file);
 do stuff with first line
 if(!feof(file)) {
  fgets(line, sizeof(line), file);
  do stuff with second line
  while (!feof(file)) {
    fgets(line, sizeof(line), file);
    do stuff
  }
 }
}
Is that really so much better?

spiritual bypass
Feb 19, 2008

Grimey Drawer

Zombywuf posted:

You've only ever used SOAP to communicate between services written using the same SOAP framework haven't you?

I've communicated with lots of services, all written by people working at different companies. I've also written a couple services of my own, but never used a framework for it. I've seen poor design decisions with SOAP services before, but never seen an XML node represent another XML document. That's just ridiculous!

heeen
May 14, 2005

CAT NEVER STOPS

duck monster posted:

I think they are great, because it lets you have resources that really really should be singular , like data base connections,
Until you want to have a development database. Or until you want to have a second window. Or a second monitor.

Janin posted:

That code is C++, so "reference" is actually the insanely dangerous "any future code could change the variable used in this context to anything" kind, not Java/C#/Python copied pointers.

Really, we need to write in dumb c++, just like there is a "simple english" wikipedia.

heeen fucked around with this message at 19:57 on Mar 19, 2009

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Fehler posted:

code:
if(!feof(file)) {
 fgets(line, sizeof(line), file);
 do stuff with first line
 if(!feof(file)) {
  fgets(line, sizeof(line), file);
  do stuff with second line
  while (!feof(file)) {
    fgets(line, sizeof(line), file);
    do stuff
  }
 }
}
Is that really so much better?

eh. But your code is unclear: what if there IS only one line? Is that okay? It would seem to me that if I had to write special cases for lines 1 and 2, I should expect that the file will always have at least those two lines, and something else is an exceptional condition.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

heeen posted:

Until you want to have a development database. Or until you want to have a second window. Or a second monitor.

Actually, this is the second of two problems that singletons are specifically designed to solve.

The first problem is the inherent "staticness" of a call to a global function; by using an instance method instead, you grant yourself the option of converting that to a virtual call without modifying any of the call sites. Obviously you could instead just modify the global function, but then you're stuck with an extra level of indirection; C++ would also allow you to turn the original function into a function-pointer variable of the same name, which is, er, not an appealing alternative.

The second problem is that global data often doesn't stay global, in which case you'll eventually need an instance anyway. The important point here is that you're not supposed to repeatedly assume the globalness of a singleton; if every access to the singleton goes through the global accessor, you're completely sabotaging this advantage of the pattern. Instead, you should have only a few places in the code that read the global reference, and those places should pass around the reference to everything else that needs it. That way, you only need to modify those few places if the data ever becomes global.

That Turkey Story
Mar 30, 2003

rjmccall posted:

The important point here is that you're not supposed to repeatedly assume the globalness of a singleton; if every access to the singleton goes through the global accessor, you're completely sabotaging this advantage of the pattern. Instead, you should have only a few places in the code that read the global reference, and those places should pass around the reference to everything else that needs it. That way, you only need to modify those few places if the data ever becomes global.
Quoted for truth. I go so far as to say ditch the entire concept of direct global access completely and instead favor a monostate pattern with an interface and associated behavior that allows an internal implementation using either a shared global resource or an owned implementation, where the distinction is specifically designed to be an implementation detail. I.E. Consider a memory allocator that uses a shared memory pool for all allocations that you instantiate like any other type -- you just do some_allocator_type my_allocator. Instead of implementing your type as a singleton with a global access point simply because it uses an internal shared, global pool for all allocations, just implement it as any other type except that it internally has a shared state, given that the shared state can be viewed as an implementation detail by design.

For instance, if designed correctly, declaring multiple "some_allocator" objects should work fine even though they may all use the same, shared, global pool underneath. Given its interface, which would include basic operations like allocating an deallocating blocks of memory, there should be no problem if at some point in time you decide to go back and change the type to use an individual pool per object. If you are using some static "get_instance" function to access your object instead of what I describe above, you can still use it appropriately as long as you only call "get_instance" in the same places you would logically grab a new instance of the type as though it were a factory. Once you obtain your object, pass it around like you would any other object (don't keep calling get_instance). The fact that only one instantiation actually exists should be an implementation detail. Using a monostate instead of an explicit global access point just makes proper usage more consistent with other types (and even more usable with generic code).

In my opinion, what it all boils down to is that if your desired use of a singleton is based around the fact that you can provide global access to a single object, you're just making a pretty global, which is fine if that's what you want, but don't think you're making things any different by attaching a fancy name to it. All too often I see people say "man, I hate globals, I use singletons instead" and then proceed to use it as a global without giving it a second thought.

Kelson
Jan 23, 2005

That Turkey Story posted:

In my opinion, what it all boils down to is that if your desired use of a singleton is based around the fact that you can provide global access to a single object, you're just making a pretty global, which is fine if that's what you want, but don't think you're making things any different by attaching a fancy name to it. All too often I see people say "man, I hate globals, I use singletons instead" and then proceed to use it as a global without giving it a second thought.

Your post took a couple readings to hash out the actual meaning... and I've yet to see a pretty name for a singleton, just hugely long names with multiple colons. Interesting design perspective though, do you have any examples?

MarsMattel
May 25, 2001

God, I've heard about those cults Ted. People dressing up in black and saying Our Lord's going to come back and save us all.
I think this is what TTS is talking about :

code:
class shared_pool {
  char* pool;
public:
  char* allocate(size_t bytes) {
    ...
  }

  // ...
};

class some_allocator {
  static shared_pool pool;
public:
  char* allocate(size_t bytes) {
    return pool.allocate(bytes);
  }

  // ...
};

Zombywuf
Mar 29, 2008

MarsMattel posted:

I think this is what TTS is talking about :

code:
class shared_pool {
  char* pool;
public:
  char* allocate(size_t bytes) {
    ...
  }

  // ...
};

class some_allocator {
  static shared_pool pool;
public:
  char* allocate(size_t bytes) {
    return pool.allocate(bytes);
  }

  // ...
};

Now the cycle is complete.

TheSleeper
Feb 20, 2003

Kelson posted:

Your post took a couple readings to hash out the actual meaning... and I've yet to see a pretty name for a singleton, just hugely long names with multiple colons. Interesting design perspective though, do you have any examples?

I think he means 'singleton' is the pretty name. Because calling it a 'global' is the 'dirty' name, but when they use it just like a global that's all it is, just with a different name.

rasactive
Dec 25, 2007
o hai

Mustach posted:

And now we flame each other over currying.

Memoization is stupid! Why would I want evaluation to be LAZY when speed is a priority?

raminasi
Jan 25, 2005

a last drink with no ice

That Turkey Story posted:

Quoted for truth. I go so far as to say ditch the entire concept of direct global access completely and instead favor a monostate pattern with an interface and associated behavior that allows an internal implementation using either a shared global resource or an owned implementation, where the distinction is specifically designed to be an implementation detail. I.E. Consider a memory allocator that uses a shared memory pool for all allocations that you instantiate like any other type -- you just do some_allocator_type my_allocator. Instead of implementing your type as a singleton with a global access point simply because it uses an internal shared, global pool for all allocations, just implement it as any other type except that it internally has a shared state, given that the shared state can be viewed as an implementation detail by design.

For instance, if designed correctly, declaring multiple "some_allocator" objects should work fine even though they may all use the same, shared, global pool underneath. Given its interface, which would include basic operations like allocating an deallocating blocks of memory, there should be no problem if at some point in time you decide to go back and change the type to use an individual pool per object. If you are using some static "get_instance" function to access your object instead of what I describe above, you can still use it appropriately as long as you only call "get_instance" in the same places you would logically grab a new instance of the type as though it were a factory. Once you obtain your object, pass it around like you would any other object (don't keep calling get_instance). The fact that only one instantiation actually exists should be an implementation detail. Using a monostate instead of an explicit global access point just makes proper usage more consistent with other types (and even more usable with generic code).

In my opinion, what it all boils down to is that if your desired use of a singleton is based around the fact that you can provide global access to a single object, you're just making a pretty global, which is fine if that's what you want, but don't think you're making things any different by attaching a fancy name to it. All too often I see people say "man, I hate globals, I use singletons instead" and then proceed to use it as a global without giving it a second thought.

Wow, this has completely changed how I understand singletons (and given me actual respect for them). No one ever explained them as "like a factory, except it happens to return the same object every time," they were always taught to me as pretty globals.

That Turkey Story
Mar 30, 2003

Kelson posted:

Your post took a couple readings to hash out the actual meaning... and I've yet to see a pretty name for a singleton, just hugely long names with multiple colons. Interesting design perspective though, do you have any examples?

I'm pretty sure I gave an example.

POKEMAN SAM
Jul 8, 2004

That Turkey Story posted:

I'm pretty sure I gave an example.

Even TTS isn't willing to read his wall of text to answer that question definitely though.

:smugissar:

That Turkey Story
Mar 30, 2003

Here's a wall of text for you:

Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer Ugg boots is a lovely programmer

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
Continuing exploration has revealed that at least one programmer tried to use namespaces for organization, but "gave up because it was too much typing".

code:
namespace Backend {
namespace Database {

class BackendDatabaseConnection {
public:
	static void ExecuteCommand(std::string sqlCommandText);
	...
}

} // namespace
} // namespace

[in another file...]

void SomeProcedure() {
	Backend::Database::BackendDatabaseConnection::ExecuteCommand("UPDATE ...");
} // SomeProcedure
(this time I picked an example that is entirely and solely the programmer's fault)

Standish
May 21, 2001

This code was written by my boss:
code:
string findMapForString(vector< pair<string, string> > map, string search)
{
  for (vector<pair<string, string> >::iterator it = map.begin(); 
        it != map.end(); it++)
  {
    if (it->first == search)
        return it->second;
  }
  return "";
}
(it's even called "map" for christ's sake.)

Standish fucked around with this message at 10:15 on Mar 21, 2009

StickGuy
Dec 9, 2000

We are on an expedicion. Find the moon is our mission.

Standish posted:

This code was written by my boss:
code:
string findMapForString(vector< pair<string, string> > map, string search)
{
  for (vector<pair<string, string> >::iterator it = map.begin(); 
        it != map.end(); it++)
  {
    if (it->first == search)
        return it->second;
  }
  return "";
}
(it's even called "map" for christ's sake.)
The pass-by-value is also a nice touch.

spammy davis jr
Mar 21, 2009

We have a self-serve advertising platform, and there are these navigation pieces at the top of the content with little titles under them. One of our past frontend guys decided this was a reasonable way to do it (the page id's, cat= values, curPage, and the pageTitles have been changed to hide who we are), because javascript is great for everything, right?
code:
else if (curPage == 'advert.aspx' || curPage == 'advert2.aspx')
	{
		if ( curQuery.match('cat=1') )
			{ hNavID = '2';
			pageTitle.innerHTML = 'Frames'; }

		else if ( curQuery.match('cat=2') )
			{ hNavID = '2';
			pageTitle.innerHTML = 'Doors'; }

...
Basically, he's parsing the url, which then defines which of the tabs should highlight, and which title it should display. This is fine in a pinch, but this specific block is over 100 lines of "else if" statements.

To make it even funnier, our VP of Technology found out and got a little angry, because we could've accomplished the same exact thing by adding a column to a db, and adding a few lines of ASPX to the frontend to automatically do this. This single piece created hours of work for anybody trying to create it.

Oh yeah, this guy couldn't format JS properly to save his life, either.

Randel Candygram
Jun 21, 2008

College Slice
Here's a real gem from the codebase I'm working with right now. It's in the middle of a few hundred nearly uncommented message definitions.
code:
message PeerXXX {
	required PeerAddr thisAddr = 1;
	// This field is tricky. Ideally, I could define a fixed size 7-bit
	// field, to represent values from 0 to 127, roughly the range of values
	// we're dealing with here. However, protocol buffers do not support this.
	// As a workaround, all but the first 7 bits are discarded. If taking the
	// modulo of 128 of this value is greater than 100, it should be ignored.
	required uint32 XXXPercent = 2;
	// Also, to you 'clever' programmers out there, don't even think of mangling
	// my protocol by assigning new behavior to 101-127. Use extensions.
	// They're there, they're supported, they don't break things, and I won't
	// feel compelled to find out where you live and draw pickles doing silly
	// things on your windows.
}
	// And don't think living in another country will stop me.

Zombywuf
Mar 29, 2008

A lovely bit of code I had to write.

code:
row = self.cursor.fetchone()

if row != None:
    retval = row[0]
else: # Horrible bug woraround ahoy!
      # It seems pymssql doesn't work here under fedora I don't know why
      # This code reaches inside the cursor and grabs the return value anyway
      # If this function is not returning the correct redirect log id, this is why
    retval = self.cursor._result[1][2][0][0]

tef
May 30, 2004

-> some l-system crap ->
Did I mention pyodbc yet? Because I'm pretty sure it's installed on the machine you're using, and works with mssql

And there's an example somewhere in my old svn folder.

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Randel Candygram posted:

Here's a real gem from the codebase I'm working with right now. It's in the middle of a few hundred nearly uncommented message definitions.
code:
message PeerXXX {
	required PeerAddr thisAddr = 1;
	// This field is tricky. Ideally, I could define a fixed size 7-bit
	// field, to represent values from 0 to 127, roughly the range of values
	// we're dealing with here. However, protocol buffers do not support this.
	// As a workaround, all but the first 7 bits are discarded. If taking the
	// modulo of 128 of this value is greater than 100, it should be ignored.
	required uint32 XXXPercent = 2;
	// Also, to you 'clever' programmers out there, don't even think of mangling
	// my protocol by assigning new behavior to 101-127. Use extensions.
	// They're there, they're supported, they don't break things, and I won't
	// feel compelled to find out where you live and draw pickles doing silly
	// things on your windows.
}
	// And don't think living in another country will stop me.

I enjoy how the final comment is after the brace, almost as a "P.S.".

gold brick
Jun 19, 2001

no he isn't
code:
            try
            {
                if (!IsPostBack)
                {
                    foo();
                }
                else
                {

                }
            }

            catch
            {

            }

Seth Turtle
May 6, 2007

by Tiny Fistpump

Mick posted:

code:
            try
            {
                if (!IsPostBack)
                {
                    foo();
                }
                else
                {

                }
            }

            catch
            {

            }


Clearly someone was getting paid per line.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Mick posted:

code:
Your avatar is perfect to go with that post.

Ogive
Dec 22, 2002

by Lowtax
This was the best comment I ever read.
code:
// This needs to be set to the really weird value initially, so that

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa
Really small one but thought I'd share this, this snippet of Java is from a JUnit test suite:
code:
new File("test").delete();
Guess what the name of the root source folder was :)

gold brick
Jun 19, 2001

no he isn't

TSDK posted:

Your avatar is perfect to go with that post.
I think I like this one better. I promise this has been in (at least) the last two releases.
code:
            if (!IsPostBack)
            {
            }
            else
            {
                
            }
The else block is a great use of negative space.

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.
Must be an embedded whitespace script.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
Hmm I wonder why our test cases take so long to run...

code:
void FooTest() {
}

void BarTest() {
  FooTest();
}

void BazTest() {
  BarTest();
}

... (x 50)

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Mick posted:

I think I like this one better. I promise this has been in (at least) the last two releases.
code:
            if (!IsPostBack)
            {
            }
            else
            {
                
            }
The else block is a great use of negative space.

This code.. is art.

spiritual bypass
Feb 19, 2008

Grimey Drawer

Strong Sauce posted:

This code.. is art.

No matter how many words you put inside the braces you must ask yourself:
am I really doing anything?

Mikey-San
Nov 3, 2005

I'm Edith Head!

royallthefourth posted:

No matter how many words you put inside the braces you must ask yourself:
am I really doing anything?

It's a pretty clever way to find out if the compiler accidentally generates new code for you.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
Can't actually post the code, but at work today I figured out that if you have the product I'm testing installed, anyone can create a webpage that can invoke any arbitrary dos command or change any setting in the registry with like three lines of setup.

Adbot
ADBOT LOVES YOU

bouyancy
Apr 17, 2003
I stumbled across this at work a while back. Somebody decided to be clever and make a data structure that could read any value from a bunch of different tables and queries. The setRow method is called on each row returned from a query. And they wonder why the appliction runs slowly.

code:
public class Row {

    public static int USERNAME = 0;
    public static int USER_PHONE = 1;
    public static int USER_DOB = 2;
    ...


    public void setRow(ResultSet result) {
        try { values[Row.USERNAME] = result.getString("username")} catch (Exception ignored) {}
        try { values[Row.USER_PHONE] = result.getString("user_phone")} catch (Exception ignored) {}
        try { values[Row.USER_DOB] = result.getString("user_dob")} catch (Exception ignored) {}
        
	... 

        continues like this for about 300 lines
    }

}

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