• 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

    • It is such a shame. I used to really respect Neowin's articles.
    • So.... slower fixes and slower security updates are preferred? I mean, there is no goldilocks zone here until it can literally update without ever needing a restart, and even then I'm sure someone would complain.
    • [New Deal] Save 73% on a lifetime EbookMagic Starter Plan by Steven Parker Today's highlighted Neowin Deal comes via our Apps + Software section, where you can get a lifetime subscription and save 73% on a lifetime EbookMagic Starter Plan. EbookMagic helps turn your ideas into complete, professionally formatted ebooks without spending weeks writing, editing or designing. Simply enter your title, genre and key details, and EbookMagic creates structured content, polished layouts and a custom cover in just minutes. Instead of juggling separate writing tools, formatting software and cover generators, EbookMagic handles the entire ebook creation process in one place. Generate content, customize your book and export ready-to-use files designed for publishing, sharing or personal projects. EbookMagic Lifetime gives aspiring authors, creators and entrepreneurs the flexibility to build, publish and scale projects over time without ongoing subscription fees. Whether you're building lead magnets, creating educational resources or starting your self-publishing journey, EbookMagic simplifies the process and helps bring ideas to life faster. AI-Powered Ebook Creation AI Writing Assistant: Transform prompts & ideas into complete ebook content. 12 Professional Writing Styles: Write using multiple styles and tones. Author Style Mimicking: Adapt content to preferred writing styles. Personalized Cover Generator: Produce custom ebook covers automatically. AI Audiobook Creator: Convert your books into professional-sounding audiobooks using a variety of realistic AI voices (1 audio book included). Built to Help You Create Faster Lightning Fast Creation: Build complete ebooks in minutes. Target Audience Optimization: Tailor content to specific demographics and reader preferences. Intelligent Chapter Structure: Automatically organize chapters and generate a table of contents. 15+ Genres Supported: Create fiction, non-fiction, business, romance, self-help and more. Quality Assurance: Improve readability and engagement with built-in content optimization. Convert to Interactive Books: Transform standard content into interactive experiences. 57 Major Languages Support: Produce ebooks across supported languages. Ready for Download & Publishing Ready for Sale: Create professional books that can be published and sold on Amazon KDP and other major publishing platforms Kindle & Print-Ready Formats: Export files prepared for publishing. No Watermarks: Create cleaner deliverables for publishing. Commercial Usage Rights: Sell or publish your ebooks. Built-In Editing Tools: Make edits before export. What You'll Get 5 Ebooks per month Each generated ebook can support up to 500,000 words per book. Up to 50 cover generations 12 professional writing styles Author style mimicking Personalized Cover Generator Convert to Interactive Books Multiple languages support Kindle & Print-ready formats Commercial usage rights No watermarks Good to know Length of access: Lifetime Redemption deadline: Redeem your code within 30 days of purchase Access options: Desktop and mobile Max number of devices: Up to 3 devices can be used per license. Available for both new and existing users that are not on lifetime plan. Updates included A lifetime subscription to EbookMagic Starter Plan normally costs $149, but this deal can be yours for just $39.99, that's a saving of $109. For full terms, specifications, and license info please click the link below. Get this EbookMagic Starter Plan lifetime deal for just $39.99 (was $149) Although priced in U.S. dollars, this deal is available for digital purchase worldwide. Support queries If you have queries or need support for any of the Neowin Deals, please use the contact form here. Neowin Deals are managed and sold by StackCommerce who represent Neowin on an affiliate basis. Why we post these deals We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. So for those that keep moaning and complaining, be thankful we're still online for you to even do that. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
  • Recent Achievements

    • One Month Later
      Clizby earned a badge
      One Month Later
    • One Month Later
      Timaximus earned a badge
      One Month Later
    • Week One Done
      Timaximus earned a badge
      Week One Done
    • Rookie
      FBSPL went up a rank
      Rookie
    • First Post
      davidbazooked earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      492
    2. 2
      PsYcHoKiLLa
      169
    3. 3
      +Edouard
      164
    4. 4
      Steven P.
      85
    5. 5
      ATLien_0
      76
  • Tell a friend

    Love Neowin? Tell a friend!