• 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

    • Visual Studio finally gets long-awaited feature that developers will love by Usama Jawad Visual Studio Code is Microsoft's popular, lightweight, open-source code editor, it is actually Visual Studio that is the company's flagship integrated development environment (IDE). Although the IDE already offers a boatload of useful features for developers, Microsoft has finally introduced a long-requested capability that will be loved by many. While developers have already been able to create Git pull requests (PRs) directly within Visual Studio for the past couple of years, it had not been possible to review a PR without switching to the browser, until now. Microsoft revealed in December 2025 that it is working on UX that enables developers to do just that, and fast-forward to June 2026, and Visual Studio finally has native capabilities to open and inspect a PR, discuss feedback, and wrap up the review, all without switching to the browser. This integration works for both GitHub and Azure DevOps (including on-prem). Developers have access to multiple surfaces to open a PR, including Git Repository, Git Changes, and the Git menu in Visual Studio. Once you open a PR, all the important details will be immediately visible to you, from where you can navigate to various levels of granularity and branch states, depending on the reviews that you are engaged in. As you would expect, you also get a diff view that enables you to see code changes inline or side-by-side in a separate panel. You can also review commit-by-commit. Additionally, this UX fosters collaboration as you can leave comments, reply to threads, and resolve conversations easily. Naturally, you can also leverage Copilot to apply a code suggestion to fix a potential issue. When you are done, you have the ability to approve, complete, and merge the PR. This is a pretty major feature as it has been requested heavily for the past few years. You can try it out in Visual Studio 2026 version 18.7, made available here recently. Microsoft plans to enhance this experience further in future releases with comment filtering, a timeline of PR activity, and more.
    • This AdGuard Family lifetime deal is still only $15.97 by Steven Parker Today's highlighted Neowin Deal comes via our Apps + Software section, where you can get a lifetime subscription and save 90% on a lifetime AdGuard Family Plan. AdGuard is a unique program that has all the necessary features for what they claim to be "the best web experience." The software combines the an advanced ad blocker, a privacy protection module, and a parental control tool—all working in one app. This software deals with annoying ads, hides your data from a multitude of trackers, protects you from malware attacks, and even lets you restrict your kids from accessing inappropriate content. Install AdGuard and see the internet as it was supposed to be: clean and safe. Get rid of annoying banners, pop-ups & video ads once and for all Hide your data from the multitude of trackers & activity analyzers that swarm the web Avoid fraudulent and phishing website and malware attacks Protect your kids online by restricting them from accessing inappropriate & adult content Good to know Family Plan Length of access: lifetime This plan is only available to new users Redemption deadline: redeem your code within 30 days of purchase Max number of devices: 9 Access options: desktop & mobile Software version: AdGuard Family Updates included A lifetime subscription of AdGuard Family Plan normally costs $169.99, but this deal can be yours for just $15.97, that's a saving of $157.02. For full terms, specifications, and license info please click the link below. Get this AdGuard Family lifetime deal for just $15.97 (was $169.99) Although priced in U.S. dollars, this deal is available for digital purchase worldwide. As an online publication, Neowin too relies on ads for operating costs and, if you use an ad blocker, we'd appreciate being whitelisted. In addition, we have an ad-free subscription for $28 a year, which is another way to show support! 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.
    • the MCT currently downloads 26200.8653, so not completely up to date.
    • Around 68% of developers are now using AI to generate code during development, and some experts are saying that a single developer using AI tools can now do the work of an entire team of 4 to 5 engineers.  According to Figma's State of the Designer 2026 report, 72% of designers now use generative AI in their workflows and 91% say it improves the quality of their work, not just their speed.  But does this mean web developers and designers are becoming less relevant, or are they simply evolving into a different kind of role? Would love to hear from developers and designers here has AI made your job easier, or do you feel threatened by how fast these tools are improving
  • Recent Achievements

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

    1. 1
      +primortal
      507
    2. 2
      PsYcHoKiLLa
      179
    3. 3
      +Edouard
      160
    4. 4
      Steven P.
      83
    5. 5
      ATLien_0
      75
  • Tell a friend

    Love Neowin? Tell a friend!