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
Mista _T
Nov 11, 2000

Mix it with Curly and Larry and Moe, WOOP-WOOP WOOP-WOOP WOOP hey, YO!

Wheany posted:

It's a bunch of initialization functions that need all the previous functions to complete successfully. There is no point in send_http_request() if open_socket() has failed. And I really don't understand what 'testing "status" an unnecessary number of times' even means. Except that I probably could have used a goto after a failure.

That said, my third idea was having an array of function pointers, with the last array entry being NULL, then doing a
code:
status = OK;
while(functions[phase] && status == OK)
{
    status=functions[phase](); // or whatever the syntax is
    phase++;
}

if(status != OK)
{
    DEBUG("failed in phase %d, status %d", phase, status);
}

By "testing 'status' an unnecessary number of times," I mean that the first example has fall-through logic that is better represented in a series of nested "if" blocks rather than, "Did it die here? Did it die here? Did it die here?" checks. It still really falls into the category of personal taste when the question posed amounts to, "Which is the lesser of each of these evils?"

I like your third option far better than the others, but if you have a set of functions closely associated with each other, wouldn't you rather group them in one call, and just test the result from that one call?

Assuming the language is C, and each function returns OK, which equals 0, if no error has occurred:
code:
int functionGroup(int *phase)
{
    int ret = OK;

    if (ret = function1())   // assignment, not equality - returns assignment value
        return ret;
    (*phase)++;

    if (ret = function2())
        return ret;
    (*phase)++;

    if (ret = function3())
        return ret;
    (*phase)++;

    return function4();
}

/* This is the entry point */
int main()
{
    int phase = 0;
    int status = functionGroup(&phase);
    if (status != OK)
        DEBUG("failed in phase %d, status %d", phase, status);
    return 0;
}
It terminates when it has to, your feedback is in one call, you have established the associated significance between each of the functions by abstracting series of tasks in one call, and you still get a return value plus feedback about the "phase." What you don't get in this solution is a means for cleanup if something fails, such as (using your scenario) closing an open socket if it succeeds in opening the socket but fails the "send." The socket will have to be closed either in "send" after we established that it failed (which is a BAD IDEA organization-wise and program flow-wise if other things call the "send" function), or in the function grouping if you check whether the socket is open or not (better idea).

EDIT: Even with preview post I still miss typos goddamn

Mista _T fucked around with this message at 19:16 on Feb 28, 2010

Adbot
ADBOT LOVES YOU

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.
RussianManiac really is hexadecimal, isn't he

markerstore
Dec 5, 2003
Canny!

Wheany posted:

That said, my third idea was having an array of function pointers, with the last array entry being NULL, then doing a

Good lord, just use a real language with exception handling.

BattleMaster
Aug 14, 2000

To be perfectly honest, relying on exception handling rather than checking it that number isn't zero before you divide or that pointer isn't null before you dereference is the biggest coding horror of them all.

Mista _T
Nov 11, 2000

Mix it with Curly and Larry and Moe, WOOP-WOOP WOOP-WOOP WOOP hey, YO!

markerstore posted:

Good lord, just use a real language with exception handling.

To Wheany's defense, there is no elegant way to iteratively call a series of functions without knowing the context of the task at hand, and Exception Handling merely causes a convenient break in control, and you would still have to do cleanup afterwards, if any.

Unless you are being sarcastic, in that case: ITERATIVE PROGRAMMING IS SRS BIZNESS :colbert:

RussianManiac
Dec 27, 2005

by Ozmaugh

Mustach posted:

RussianManiac really is hexadecimal, isn't he

Who is this hexadecimal you all keep implying I am, which I am not?

(USER WAS BANNED FOR THIS POST)

every
Apr 24, 2008

Just a ridiculous piece of code to find out if a passed date came before today.

quote:

if ( (date.getMonth() == today.getMonth() && date.getDate() < today.getDate() && date.getFullYear() <= today.getFullYear()) || (date.getFullYear() < today.getFullYear()) || (date.getFullYear() <= today.getFullYear() && date.getMonth() < today.getMonth()) )

Factor Mystic
Mar 20, 2006

Baby's First Post-Apocalyptic Fiction

Avenging Dentist posted:

Congrats on being ignorant.

lol defending macros

quote:

Who is this hexadecimal you all keep implying I am, which I am not?
We know you'll get perma'd again if you admit it, so don't feel like you have to individually respond to everyone who outs you.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

markerstore posted:

Good lord, just use a real language with exception handling.

I would if I could.

Kelson
Jan 23, 2005

Wheany posted:

which is worse:
code:
int status = OK;
int phase = 0;

status = function1();
if(status == OK)
{
   phase++;
   status = function2();
}
if(status == OK)
{
   phase++;
   status = function3();
}
if(status == OK)
{
   phase++;
   status = function4();
}
if(status != OK)
{
   DEBUG("failed in phase %d, status %d", phase, status);
}
vs

Mista _T posted:

code:
int functionGroup(int *phase)
{
    int ret = OK;

    if (ret = function1())   // assignment, not equality - returns assignment value
        return ret;
    (*phase)++;

    if (ret = function2())
        return ret;
    (*phase)++;

    if (ret = function3())
        return ret;
    (*phase)++;

    return function4();
}

/* This is the entry point */
int main()
{
    int phase = 0;
    int status = functionGroup(&phase);
    if (status != OK)
        DEBUG("failed in phase %d, status %d", phase, status);
    return 0;
}
vs

Wheany posted:

code:
int status = OK;

status = function1();
if(status == OK)
{
	status = function2();
	if(status == OK)
	{
		status = function3();
		if(status == OK)
		{
			status = function4();
			if(status != OK)
				DEBUG("function4 failed, status %d", status);
		}
		else
		{
			DEBUG("function3 failed, status %d", status);
		}
	}
	else
	{
		DEBUG("function2 failed, status %d", status);
	}
}
else
{
	DEBUG("function1 failed, status %d", status);
}

Mista _T
Nov 11, 2000

Mix it with Curly and Larry and Moe, WOOP-WOOP WOOP-WOOP WOOP hey, YO!

Kelson posted:

[All of the code snippets]

I'm not even going to defend my code. It's all bad. Bad, bad, bad.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Factor Mystic posted:

lol defending macros

If you think that macros are the problem, then you haven't really thought about what the issue is. It's not the existence of macros that is the problem, it's the non-existence of other important features (modules, inline functions*) that require fallback to macros.

* Inline functions are available in C99, but people would rather use a 20 year old standard.

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Avenging Dentist posted:

Labels are local to functions so this is wholly unnecessary.

oh, and he even said "two loops in a function". welp, guess that's reading_comprehension--;

Contra Duck
Nov 4, 2004

#1 DAD
Hi all! I saw a new code pattern today that I think has the potential to revolutionise the industry and I wanted to share it with you. I call it antipolymorphism. In general it looks like this:

code:

public class ClassB extends ClassA
{
    ...
}

public class ClassA
{
    public void someMethod()
    {
        if (this instanceof ClassB)
        {
            // do something
        }
        else
        {
            // do a different thing
        }
    }
}
Quite powerful I think you'll agree, and the advantages of keeping all your logic in the one place rather than scattered amongst different files cannot be overstated.

Sprawl
Nov 21, 2005


I'm a huge retarded sperglord who can't spell, but Starfleet Dental would still take me and I love them for it!

Contra Duck posted:

Hi all! I saw a new code pattern today that I think has the potential to revolutionise the industry and I wanted to share it with you. I call it antipolymorphism. In general it looks like this:

code:

public class ClassB extends ClassA
{
    ...
}

public class ClassA
{
    public void someMethod()
    {
        if (this instanceof ClassB)
        {
            // do something
        }
        else
        {
            // do a different thing
        }
    }
}
Quite powerful I think you'll agree, and the advantages of keeping all your logic in the one place rather than scattered amongst different files cannot be overstated.

They are using an overloaded version of the base class within the class? that's all kinds of retarded.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

Contra Duck posted:

Hi all! I saw a new code pattern today that I think has the potential to revolutionise the industry and I wanted to share it with you. I call it antipolymorphism. In general it looks like this:

code:

public class ClassB extends ClassA
{
    ...
}

public class ClassA
{
    public void someMethod()
    {
        if (this instanceof ClassB)
        {
            // do something
        }
        else
        {
            // do a different thing
        }
    }
}
Quite powerful I think you'll agree, and the advantages of keeping all your logic in the one place rather than scattered amongst different files cannot be overstated.

My god, it's almost beautiful. Was there anything in ClassB?

Italian Stalin
Jul 4, 2003

You-a gonna get-a purged!
This comes from a Java class I am currently taking. It's part of a program that simulates a bank account. The student in question posted this on the forum asking why the code wasn't passing the unit tester given to him by the professor.

code:
/** 
Deposits the money 
*/ 
public void deposit(double amount) 
{ 
    if (amount >= balance) 
    { 
        balance = balance + amount; 
    } 
    else 
    { 
        balance = balance + 0; 
    } 
}  

/** 
Withdrawe the monety 
*/ 
public void withdraw(double amount) 
{ 
    if (amount >= balance) 
    { 
        balance = Math.abs(balance - amount); 
    } 
    else 
    { 
        balance = balance - 0; 
    } 
}  

Italian Stalin fucked around with this message at 08:14 on Mar 2, 2010

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

armed2010 posted:

This comes from a Java class I am currently taking. It's part of a program that simulates a bank account. The student in question posted this on the forum asking why the code wasn't passing the unit tester given to him by the professor.

code:
/** 
Deposits the money 
*/ 
public void deposit(double amount) 
{ 
    if (amount >= balance) 
    { 
        balance = balance + amount; 
    } 
    else 
    { 
        balance = balance + 0; 
    } 
}  

/** 
Withdrawe the monety 
*/ 
public void withdraw(double amount) 
{ 
    if (amount >= balance) 
    { 
        balance = Math.abs(balance - amount); 
    } 
    else 
    { 
        balance = balance - 0; 
    } 
}  


Gee, that's how it works? Nobody told me! I'm heading down to the bank right now to withdrawe £1,000,000 of monety immediately!

MasterSlowPoke
Oct 9, 2005

Our courage will pull us through
Making fun of intro to programming "horrors" is kind of unsporting.

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

MasterSlowPoke posted:

Making fun of intro to programming "horrors" is kind of unsporting.
Indeed, I recall doing Contra Duck's antipolymorphism back in my first semester of CS. I think it's awfully low-hanging fruit unless it's absolutely hysterical

Mill Town
Apr 17, 2006

Personally I'm willing to let this one in just for

code:
/** 
Withdrawe the monety 
*/ 

Contra Duck
Nov 4, 2004

#1 DAD

Dijkstracula posted:

Indeed, I recall doing Contra Duck's antipolymorphism back in my first semester of CS. I think it's awfully low-hanging fruit unless it's absolutely hysterical

I had my share of laughs back when I used to take first year CS classes at uni, but sadly my last example was from industry. Thank god for code reviews though!

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
I think that example's funny because I'm sure that even if I had no experience of programming, I'd be able to look at it and think "else balance = balance + 0? What's the point of that?"

Plus withdraweing monety and stuff I guess.

Sebbe
Feb 29, 2004

To be fair, I've seen quite a few people write that sort of code in introductory programming classes; it's more of a sign that they don't really understand what they're writing than a horror, in my opinion.

Usually the people writing these don't have illusions that what they're doing is right, as opposed to the real horrors, where they do.

Hammerite
Mar 9, 2007

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

Sebbe posted:

To be fair, I've seen quite a few people write that sort of code in introductory programming classes; it's more of a sign that they don't really understand what they're writing than a horror, in my opinion.
Yes, I agree; as I said, I can't see how someone would, for example, think it worthwhile to put in those obviously redundant else {} clauses if they really understood properly what they were writing.

This is something I was thinking about only yesterday, as I was doing some teaching for a first-year calculus course (I'm a postgrad and we're asked to give a certain amount of help teaching every semester). It's fairly basic stuff that all of the first-year mathematics students have to do, and so you can understand how some of them will find it boring and switch off. But you do come into contact with students who seem not to readily engage with the idea that they need to think critically about what they're doing. By this I mean that they often seem to be used to the idea that there is some algorithmic, rote method that they will be able to learn and apply dutifully to whatever problem they're presented with. To do mathematics at a higher level they need to try and have a real understanding of the ideas they're working with, but while the introductory courses we give try to instill this in them, I have the uncomfortable impression they often don't succeed.

I'm talking about my discipline which is maths, but I can readily believe it applies to other technical disciplines too. I know you weren't criticising the student who wrote this, just observing that he didn't understand what he was writing. I tend to feel that while there is a value in "learning by doing", you shouldn't present a piece of work, purporting to be a genuine solution to a problem, in which you've written something you don't understand. I'm not sure in what way it is best to get students to understand that they really need to engage with the material they are learning, however.

I'm rambling so I'll shut up now.

FateFree
Nov 14, 2003

Sometimes its the one liners that really get you.

code:
private QuoteRP () { /*protected to allow inheritance*/ }

dancavallaro
Sep 10, 2006
My title sucks

MasterSlowPoke posted:

Making fun of intro to programming "horrors" is kind of unsporting.

I want to agree with this, but the code armed2010 posted just shows a complete inability to think critically or reason through anything. Just read that deposit method aloud in plain English:

"If the amount to deposit is greater than or equal to the current account balance, then add the amount to the current balance. Otherwise, add nothing to the balance."

What is it about parentheses and curly braces that cause beginners to turn their brains off?

Italian Stalin
Jul 4, 2003

You-a gonna get-a purged!

MasterSlowPoke posted:

Making fun of intro to programming "horrors" is kind of unsporting.

For context, this is a person that was also with me in a much more difficult C language class during the previous semester where we were doing things far more complicated than this by this exact same time, and stayed the entire way through. I'm talking data structures, pointers, functions, etc. Based on the examples I've seen of his code such as this he must have failed the class outright, but you'd think that at least SOME of what the class taught would have rubbed off on him.

sonic bed head
Dec 18, 2003

this is naturual, baby!
code:
...
User user= new User();
if(user!=null){
...

}else{
logger.error("user is null");
}
This is everywhere in my current project. I understand null checks when you're calling methods but this makes no sense. It's actually getting a little frustrating because the person who writes this is telling me that my code isn't null pointer safe because I don't check every single object I use.

Flobbster
Feb 17, 2005

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

sonic bed head posted:

This is everywhere in my current project. I understand null checks when you're calling methods but this makes no sense. It's actually getting a little frustrating because the person who writes this is telling me that my code isn't null pointer safe because I don't check every single object I use.

Can "new" in Java ever even return null? I would assume that in circumstances where that's a possibility (out of memory), you'd get shut down with the OutOfMemoryError instead before that statement had a chance to return.

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD

MasterSlowPoke posted:

Making fun of intro to programming "horrors" is kind of unsporting.
There's no coding horror there. It compiles, it runs. Code is nicely laid out, names are clear and the functions do a very clean job of encapsulating a discrete set of operations. If there's a business logic bug in there somewhere, it'll be caught in testing, or customers can simply file a bug report.

EDIT: vvvv I'm missing the reference :confused:

Bhaal fucked around with this message at 23:15 on Mar 2, 2010

ColdPie
Jun 9, 2006

Bhaal posted:

There's no coding horror there. It compiles, it runs. Code is nicely laid out, names are clear and the functions do a very clean job of encapsulating a discrete set of operations. If there's a business logic bug in there somewhere, it'll be caught in testing, or customers can simply file a bug report.

Hey Rob, didn't know you had an account here.

Mista _T
Nov 11, 2000

Mix it with Curly and Larry and Moe, WOOP-WOOP WOOP-WOOP WOOP hey, YO!

Flobbster posted:

Can "new" in Java ever even return null? I would assume that in circumstances where that's a possibility (out of memory), you'd get shut down with the OutOfMemoryError instead before that statement had a chance to return.

This is correct. "new" in Java NEVER returns null. Even in lovely implementations of a JVM. My guess is that the guy is or used to be a C++ programmer (where "new" is basically malloc plus constructor).

Sprawl
Nov 21, 2005


I'm a huge retarded sperglord who can't spell, but Starfleet Dental would still take me and I love them for it!

Mista _T posted:

This is correct. "new" in Java NEVER returns null. Even in lovely implementations of a JVM. My guess is that the guy is or used to be a C++ programmer (where "new" is basically malloc plus constructor).

Or it could be C# that can sometimes be null or default values.

Milotic
Mar 4, 2009

9CL apologist
Slippery Tilde
I'm seriously worried by the number of goons in this thread who cannot spot the fundamental flaws in that Bank Account coding horror.

Bhaal posted:

...If there's a business logic bug in there somewhere, it'll be caught in testing, or customers can simply file a bug report...

This is probably the best troll in the history of man.

Sprawl posted:

Or it could be C# that can sometimes be null or default values.

Directly calling .NET constructors will always return a non-null value. Also, silently logging and proceeding with execution flow on an unexpected null is not necessarily better than just having an exception thrown and letting it percolate up the stack and trapping it further up.

e:I can't type.

Milotic fucked around with this message at 00:33 on Mar 3, 2010

Sprawl
Nov 21, 2005


I'm a huge retarded sperglord who can't spell, but Starfleet Dental would still take me and I love them for it!

Milotic posted:

I'm seriously worried by the number of goons in this thread who cannot spot the fundamental flaws in that Bank Account coding horror.

yea there is a huge logic flaw among other things its really bad code but like the guy said a class of into students that wouldn't know any better.

code:
    if (amount >= balance) 
    { 
        balance = balance + amount; 
    }
I can't really understand the logic of testing the balance when all your doing is adding? Shouldn't it just be add the loving number if its a loving number?

code:
    if (amount >= balance) 
    { 
        balance = Math.abs(balance - amount); 
    } 
This could turn a negative balance into what looks like a positive balance but shouldn't be huge problems. Not to mention it will only process if your trying to take out more then you have.

Vanadium
Jan 8, 2005

Mista _T posted:

My guess is that the guy is or used to be a C++ programmer (where "new" is basically malloc plus constructor).

It still never returns NULL, unless you turn off exceptions or do something crazy like that.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Bhaal posted:

or customers can simply file a bug report.

Heh, yeah, it'll look like this

code:
Leonard J Crabs
State Bar No: 1
Attorney for Client

     SUPERIOR COURT OF THE STATE OF FAILURE
	
PLAINTIFF(S) NAMES	)	CASE NO.:  1
Client			)	
			)
		v	)
			)
DEFENDANT(S) NAMES	)
You			)
			)
---------------------------------------------- 

                BUG REPORT

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD

Sprawl posted:

code:
    if (amount >= balance) 
    { 
        balance = balance + amount; 
    }
I can't really understand the logic of testing the balance when all your doing is adding? Shouldn't it just be add the loving number if its a loving number?
Well no, it can't be less than the current balance. It doesn't make sense for the balance to be a larger amount BEFORE you deposit the money, so you have to check for it.

quote:

code:
    if (amount >= balance) 
    { 
        balance = Math.abs(balance - amount); 
    } 
This could turn a negative balance into what looks like a positive balance but shouldn't be huge problems. Not to mention it will only process if your trying to take out more then you have.
Exactly. The programmer accounted for edge case of negatives by throwing that abs() in there.

Adbot
ADBOT LOVES YOU

Sebbe
Feb 29, 2004

Sprawl posted:

yea there is a huge logic flaw among other things its really bad code but like the guy said a class of into students that wouldn't know any better.

code:
    if (amount >= balance) 
    { 
        balance = balance + amount; 
    }
I can't really understand the logic of testing the balance when all your doing is adding? Shouldn't it just be add the loving number if its a loving number?

code:
    if (amount >= balance) 
    { 
        balance = Math.abs(balance - amount); 
    } 
This could turn a negative balance into what looks like a positive balance but shouldn't be huge problems. Not to mention it will only process if your trying to take out more then you have.

To me it looks like someone who hasn't learned to break problems properly up into discrete steps. They know some of what they need, but don't think how to put them together properly through. It's looks a lot like some of the stuff I saw the first few weeks of being a programming intro instructor.

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