• 0

Rules we learn at school


Question

Hello everyone!

I've recently started my studies (Bachelor of Applied Computer Science), and in our OOP-classes we've been using Java to get familiar with Object Oriented programming concepts in general (so not focusing on the Java API but mainly on object relations, calling methods on other objects, call by reference/value etc etc).

We do learn a few rules for our code though. Things we should do:

  • never use more than one return statement
  • never use break or continue
  • avoid using switch

I am, of course, all but an experienced programmer, but I quite like these principles. Whenever we see a code example that has multiple returns or uses break or continue it takes a while to understand, while code with a single return and without breaks/continues always looks quite clean and easy to understand. I personally never felt limited by these rules either.

What do you guys think?

Link to comment
https://www.neowin.net/forum/topic/1045461-rules-we-learn-at-school/
Share on other sites

Recommended Posts

  • 0

I think break has it's place in code. It's particularly useful for terminating the loop once you have found what you want. Saves you continuing to iterate through the loop.

Multiple returns are also ok, kinda.. You should return only once but set the return at each fork in the code >.<

/shrug

It all depends tbh :)

  • 0

I see absolutely nothing wrong with multiple returns, breaks, continues, or switches. Each one of them is extremely useful.

The following examples are both PHP, but the same concepts apply to Java:

function twoDigits($i)
{
  if($i &lt; 10) return '0' . $i;
  else return $i;
}

switch(true)
{
  case $var = 'something':
	// If var = something, execute some code and then stop looking at the remaining cases
  break;

  case $var2 = 'blah':
	// If var = something, this will never be executed, otherwise it will
  break;

  default:
	// If neither of them conditions matched, then break was never called, so this code will execute
}

  • 0

eh we never were taught "rules" like that, there are reasons to do all those things depending on what and how you are doing things

Agreed.

You may want to use multiple return statements to avoid a lot of if-elses chained together that aren't necessary. Same with continue or break, you can end up doing a lot of comparing you don't need to. Switch statements are very handy for comparing against enum values. The only downside to switch cases is that you have to remember breaks where you need them.

  • 0

Being a 2nd year Computer Science bachelor student who has been mostly taught programming in C++,

Some of those rules would be pretty terrible for C++ (Although it wouldn't matter much in Java I guess)

For instance a Switch is highly efficient way of writing down loads of else-ifs and is also recommended to do so. Both from a readability and efficiency aspect.

Breaks are quite handy in a lot of cases especially if you want to escape a loop once you have what you need (as has been mentioned) and not to forget that breaks are essential in switch statements.

No multiple returns is kind of strict, but I guess they want you guys to learn using exceptions and write focused, short code (we had a restriction of ~20 lines of real code per function in our C++ class during the first semester). If you write a highly specialized short function, it will mostly result in less branching in the code of the function.

Just remember, those rules are mostly to teach you to write code in a more or less 'proper' fashion, but after that you're usually free to write what you want as long as it's not highly inefficient (I have become somewhat obsessed with optimizing the code of assignments).

  • 0
never use more than one return statement
That doesn't necessarily make things more readable. Consider:

// using only one return statement
private int performComputation(String a, String b) {
int result = 0;
if (a != null) {
if (b != null) {
// your
// code
// that
// performs
// some
// computation
// goes
// here
result = something;
}
else {
result = Integer.MAX_VALUE;
}
}
else {
result = Integer.MIN_VALUE;
}
return result;
}[/CODE]

[CODE]
// same logic, several return statements
private int performComputation(String a, String b) {
if (a == null) {
return Integer.MIN_VALUE;
}
if (b == null) {
return Integer.MAX_VALUE;
}

// your
// code
// that
// performs
// some
// computation
// goes
// here
return something;
}
[/CODE]

The version with several return statements has several advantages:

- The code that performs the computation, i.e. the meat of the function, is unindented

- No else statements

- Better locality of statements - both error conditions are immediately accompanied by their results, rather than those being pushed at the other end of the function

- It looks a lot cleaner

So while it's always possible to avoid writing several returns statements, it's doesn't necessarily lead to more understandable code.

If you're interested in a deeper discussion of this sort of issues, I suggest reading Code Complete 2nd Edition by Steve McConnel.

In general what they're saying is "make straightforward functions with as few jumps as possible". I don't think you should follow the advice to the letter. Sometimes the cleanest way to write something is to use a break or continue, or even a switch. As long as you're aware that you're creating jumps in the code, i.e. breaking the flow, and of the impact this has on readability, you can use them where you see fit.

  • 0

Echoing the same thing everyone else said... School programming is a highly artificial environment and they impose all sorts of nonsense on you to teach what they actually want you to "learn". it's quite frustrating for anyone taking a course they already know. "rules" like that really aren't helpful if you know what you're doing.

  • 0

you completely passed over the one no-no that should get you Fs in class and fired from jobs.

No goto statements.

Try writing error handling in C, that deal with memory allocation, file handles, sockets and mutexes.

If the Linux Kernel uses them for error handling, then I think I can as well (when I have to write C, much rather be using C++).

Avoiding anything is a silly thing to do. The language features exist for a reason and there will always be a "right" case to use it.

But there will also be plenty of wrong cases too, so you have to judge what language feature helps you express your intent as clearly as possible.

  • 0

The only time you ever have a "right situation" for using GOTO is if you somehow ended up with a 3 letter keyboard and needed to write a switch to save the world..

Other then that, you should be hung, drawn and quartered. (Possibly even in the above situation as well >.>)

  • 0

Try writing error handling in C, that deal with memory allocation, file handles, sockets and mutexes.

If the Linux Kernel uses them for error handling, then I think I can as well (when I have to write C, much rather be using C++).

Avoiding anything is a silly thing to do. The language features exist for a reason and there will always be a "right" case to use it.

But there will also be plenty of wrong cases too, so you have to judge what language feature helps you express your intent as clearly as possible.

it's a matter of good programming in my opinion.

anytime i've been programming something and felt like i might need to use a goto statement. I know i dun-goofed. There's always a way it can be programmed in a strutured way. When i'm in those situations... i start rewriting.

if any API or other pre-programmed structure is supposedly forcing you to use goto to handle errors then there is something fundamentally wrong with it and is a regular target for hackers. can you probably make more efficient code with goto. Yeah, used correctly. But that's not really the point. If you wanted the worlds most efficient code you would be programming in assembly anyway.

  • 0

The only rule that have been outlined at your school I would agree on would be the switch one.

In C and C++, switchs are not straightforward to use: you have to be extremely careful with break and default.

After that, the one good rule is write the code thinking that you may have to re-read it at 11:00pm in a caffeine-induced frenzy the day before a dead-line and you will not have enough working brain cells ...

So, document the code, give meaningful name to variables: you will not remember what fb and fd are 300 lines later in a method, skip lines, make the code easy to read and therefore understand

  • 0

The only rule that have been outlined at your school I would agree on would be the switch one.

In C and C++, switchs are not straightforward to use: you have to be extremely careful with break and default.

After that, the one good rule is write the code thinking that you may have to re-read it at 11:00pm in a caffeine-induced frenzy the day before a dead-line and you will not have enough working brain cells ...

So, document the code, give meaningful name to variables: you will not remember what fb and fd are 300 lines later in a method, skip lines, make the code easy to read and therefore understand

i feel like they are mostly straight foward. i simply don't like how if you don't put a break in that the program will start executed code from other cases until it gets through them all or does hit a break.

  • 0

you completely passed over the one no-no that should get you Fs in class and fired from jobs.

No goto statements.

Dijkstra was correct. goto is evil when used incorrectly. Otherwise is useful and efficient.
The only rule that have been outlined at your school I would agree on would be the switch one.

In C and C++, switchs are not straightforward to use: you have to be extremely careful with break and default.

9cDPS.jpg

If you are not being careful when programming, why are you even programming at all?

Usually using a single switch or nested switches can be quite efficient and readable (you can see the branching).

  • 0

...

Exactly, the reason why GOTOs were labeled as bad was because the programming languages at that time were all using gotos and programs were littered with them which resulted in highly unreadable code.

Goto statements are quite handy when used conservatively and wise and will not inpact readability. There's a reason why Microsoft has added the goto statement into C#. Also, you can't escape from gotos (jumps) in Assembly ;) But then again, you're usually not reading that code.

And Switches being cumbersome? Seriously? Because it's hard to remember close cases with breaks (if you need to stop after that case that is) and default cases? I guess you should be happy that you have the luxury of a Garbage Collector in java instead of manual memory management (teaches you a lot about how to use your space wise and how much bull**** you might allocate if you're not thinking about efficiency).

  • 0

LOL @ Rules. It's great while it lasts. The dream comes crashing down when you actually start working.

my favorite thing is in college you "document" like wild, get into the real world, good luck if you have time to document.... so goes the saying "real coders don't document, their code should speak for itself" (not that you shouldn't have documentation! just college makes it seem lile you should be writing war and peace about the hello world app)

Dijkstra was correct. goto is evil when used incorrectly. Otherwise is useful and efficient.

9cDPS.jpg

If you are not being careful when programming, why are you even programming at all?

Usually using a single switch or nested switches can be quite efficient and readable (you can see the branching).

evil, now what is evil is having to use JMP in assembly... now that can be evil better hope you go where you want and get back where you wanted to

  • 0

If you are not being careful when programming, why are you even programming at all?

Usually using a single switch or nested switches can be quite efficient and readable (you can see the branching).

And Switches being cumbersome? Seriously? Because it's hard to remember close cases with breaks (if you need to stop after that case that is) and default cases? I guess you should be happy that you have the luxury of a Garbage Collector in java instead of manual memory management (teaches you a lot about how to use your space wise and how much bull**** you might allocate if you're not thinking about efficiency).

No, I have to deal with C++. I like being careful about what I am writing, I do not like having to deal with the pitfalls the language puts on me.


   switch(method )
	 {
	 case OK :
	 case CASE1:
	 case CASE2 :
		  break;
	 case UNDEFINED :
		  return -71;

	 case CASE3 :
	 case CASE4:
	 case CASE5 :
	 case CASE6:
		  return -72;
	 default :
		  return -73;
	 }
   switch( search_type )
	 {
	 case UNDEFINED :
		  return -74;
	 case GLOBAL :
		  break;
	 case SEARCH_CASE1 :
		  error_code = SomeMethod( Some parameters );

		  if(error_code != 0) return error_code;	
		  break;
	 case SEARCH_CASE2:
		  if( some test ) return -80;
		  break;
	 default :
		  return -75;
	 }

Simplified code I have to deal with and no, I am not the author ...

Edit: corrected BBCode, anonymized the code

  • 0

When I was in school they were not very consistent from teacher to teacher as to naming conventions some used camel casing other used Underscores and each one required you name things the way they do. which made for confusion when you wanted to use one or the other on your own projects.

I prefer underscoring one of my best friends (went to the same school) uses camel casing.

  • 0

No, I have to deal with C++. I like being careful about what I am writing, I do not like having to deal with the pitfalls the language puts on me.

Simplified code I have to deal with and no, I am not the author ...

Edit: corrected BBCode, anonymized the code

If you want I can give a bad example of if statements.

Just because you had one bad example doesn't mean that switch is useless.

One example of a good use would be to model a finite state machine (automata), which is great for code that handles parsing.

This topic is now closed to further replies.
  • Posts

    • I disagree here sorry. The majority of their customers are corporations who are locked in to their eco system and have no choice. Private individuals don't contribute that much to their income.
    • Weekend PC Game Deals: Anno 117, Final Fantasy VII, Rematch, and more by Pulasthi Ariyasinghe Weekend PC Game Deals is where the hottest gaming deals from all over the internet are gathered into one place every week for your consumption. So kick back, relax, and hold on to your wallets. The Epic Games Store's mystery giveaways may have ended, but its regular freebies didn't miss a step this week. The double drop was for copies of Warhammer 40K Speed Freeks and The Ouroboros King. Speed Freeks lands for multiplayer racing fans, but with plenty of competitive shooting elements too. You will be piloting Ork buggies, tanks, and aircraft modeled after the popular tabletop miniatures while trying to complete objectives and pass finish lines. Next, Ouroboros King is a crossover between chess and tactical roguelikes, offering the chance to create your own army with special rules to beat incoming foes on the board. The double giveaway on the Epic Games Store will be available until June 11, and replacing it will be Citizen Sleeper and ROBOBEAT. The Humble Store brought a new charity bundle to check out this week too. Landing with the name The Complete Inkle Library, this is a large collection of interactive narrative puzzle games from the publisher Inkle. This begins with Heaven's Vault, four parts from the Sorcery series, 80 Days, Overboard, and Pendragon: Narrative Tactics within the starting tier for $9. Hopping up a step to the $12 tier gets you TR-49, Expelled, and A Highland Song for paying at least $12. If you go for the $20 tier, you get four e-books from the Heaven's Vault series. The bundle has almost three weeks on its counter before it goes away. Big Deals There is a larger than normal amount of weekend specials happening this time, including multiple publisher deals, franchise discounts, and indie gems to grab. With those and more, here's our hand-picked big deals list for the weekend: Anno 117: Pax Romana – $44.99 on Steam Clair Obscur: Expedition 33 – $39.99 on Steam Timberborn – $27.99 on Steam EARTH DEFENSE FORCE 6 – $26.39 on Steam Rust – $19.99 on Steam FINAL FANTASY VII REBIRTH – $19.99 on Steam Street Fighter 6 – $19.99 on Steam Returnal – $19.79 on Steam Shape of Dreams – $17.49 on Steam Far Cry 6 – $14.99 on Steam Assassin's Creed Valhalla – $14.99 on Steam Quarantine Zone: The Last Check – $14.99 on Steam REMATCH – $14.99 on Steam EA SPORTS FC 26 – $13.99 on Steam FINAL FANTASY VII REMAKE INTERGRADE – $13.99 on Steam Magicraft – $12.79 on Steam Cult of the Lamb – $12.49 on Steam Dying Light 2: Reloaded Edition – $11.99 on Steam Cuphead – $11.99 on Steam Assassin's Creed Odyssey – $11.99 on Steam Hunt: Showdown 1896 – $11.99 on Steam Sektori – $11.99 on Steam Just Shapes & Beats – $11.99 on Steam Gunfire Reborn – $10.99 on Steam 33 Immortals – $9.99 on Epic Store Baby Steps – $9.99 on Steam Sifu – $9.99 on Steam Hearts of Iron IV – $9.99 on Steam DREDGE – $9.99 on Steam DAVE THE DIVER – $9.99 on Steam Pacific Drive – $9.89 on Steam Mycopunk – $9.74 on Steam Sons Of The Forest – $8.99 on Steam Jotunnslayer: Hordes of Hel – $8.99 on Steam Nuclear Throne – $8.99 on Steam Mechabellum – $8.99 on Steam Deep Rock Galactic: Survivor – $8.44 on Steam TerraTech Legion – $7.99 on Steam Inscryption – $7.99 on Steam Assassin's Creed Unity – $7.49 on Steam Minishoot' Adventures – $7.49 on Steam The Stanley Parable – $7.49 on Steam Oxygen Not Included – $7.49 on Steam Megabonk – $6.99 on Steam Look Outside – $5.99 on Steam Vampire Hunters – $5.24 on Steam MOTHERGUNSHIP – $4.99 on Steam My Friend Pedro – $3.99 on Steam The Messenger – $3.99 on Steam Vampire Survivors – $3.74 on Steam Brotato – $2.99 on Steam Enter the Gungeon – $2.99 on Steam Loop Hero – $2.99 on Steam GRIS – $2.99 on Steam Exit the Gungeon – $2.49 on Steam Hitman: Absolution – $1.99 on Steam CARRION – $1.99 on Steam Don't Starve Together – $1.49 on Steam Golf With Your Friends – $1.49 on Steam Hotline Miami – $0.99 on Steam The Ouroboros King – $0 on Epic Store Warhammer 40K Speed Freeks – $0 on Epic Store DRM-free Specials Hopping over to the DRM-free deals, the GOG store has plenty of discounts running this weekend too. Here are some highlights: Fallout 4: Game of the Year Edition - $15.99 on GOG Fallout: New Vegas Ultimate Edition - $9.99 on GOG Disco Elysium - The Final Cut - $9.99 on GOG Crysis - $9.99 on GOG Tyranny - Standard Edition - $7.49 on GOG Frostpunk: Game of the Year Edition - $7.35 on GOG Banished - $6.79 on GOG Fallout 3: Game of the Year Edition - $6.59 on GOG The Forgotten City - $6.25 on GOG The Age of Decadence - $5.99 on GOG SimCity 3000 Unlimited - $4.99 on GOG Assassin's Creed: Director's Cut - $4.99 on GOG SimCity 4 Deluxe Edition - $3.99 on GOG Vampyr - $3.99 on GOG Torchlight II - $3.99 on GOG Deus Ex GOTY Edition - $3.49 on GOG Primordia - $3.09 on GOG Theme Hospital - $2.99 on GOG SimCity 2000 Special Edition - $2.99 on GOG Total Annihilation: Kingdoms + Iron Plague - $2.99 on GOG Deus Ex: Human Revolution - Director’s Cut - $2.99 on GOG Master of Orion 1+2 - $2.39 on GOG Prince of Persia: The Sands of Time - $1.99 on GOG Prince of Persia: Warrior Within - $1.99 on GOG EVERSPACE - $1.99 on GOG Total Annihilation: Commander Pack - $0.99 on GOG Keep in mind that availability and pricing for some deals could vary depending on the region. That's it for our pick of this weekend's PC game deals, and hopefully, some of you have enough self-restraint not to keep adding to your ever-growing backlogs. As always, there are an enormous number of other deals ready and waiting all over the interwebs, as well as on services you may already subscribe to if you comb through them, so keep your eyes open for those, and have a great weekend.
    • When will the Photos app be updated to remember the window size and position when reopened? They addressed this issue in a 2024 version of the app (though I can't recall the build number). Unfortunately, after that specific version, the problem persists! Please prioritise this fix in your K2 schedule. Additionally, the Snipping Tool has lost the ability to capture the Windows Taskbar starting from the 2024 version!
    • Same, never saw it on Android or iOS. Guess only some people got it *shrugs*
  • Recent Achievements

    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
    • Rookie
      Rimplesnort went up a rank
      Rookie
    • One Year In
      Markus94287 earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      484
    2. 2
      +Edouard
      171
    3. 3
      PsYcHoKiLLa
      140
    4. 4
      ATLien_0
      92
    5. 5
      Steven P.
      79
  • Tell a friend

    Love Neowin? Tell a friend!