• 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

    • 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*
    • Anthropic pulls Fable 5 and Mythos 5 after US export control order by Pradeep Viswanathan In April this year, Anthropic launched the Claude Mythos Preview frontier model with state-of-the-art cyber and coding capabilities for a select set of companies around the world. After preparing appropriate guardrails, early this week, Anthropic launched Claude Fable 5 and Mythos 5, its most capable AI models. Claude Fable 5 is for general users and comes with strict safeguards, while Mythos 5 is designed with fewer safeguards for cybersecurity and biology use cases. Today, Anthropic abruptly suspended access to its Fable 5 and Mythos 5 AI models for all customers after receiving an export control directive from the US government. The company received the directive from the government today at 5:21 p.m. ET, and the received letter did not provide any details regarding the national security concern. Anthropic understands that the government became aware of a method to bypass, or “jailbreak,” Fable 5, which might be the reason behind the directive. The order was issued under national security authorities and requires the company to suspend all access to Fable 5 and Mythos 5 by any foreign national, whether they are inside or outside the United States. The restriction also applies to foreign national employees working at Anthropic. As a result, the company has disabled both models for all customers to ensure compliance. Access to previous Anthropic models like Opus and Sonnet is not affected by this government order. The company highlighted that it had developed strong safeguards to reduce the possibility that Fable is misused for tasks related to cybersecurity. In fact, many developers are complaining that the safeguards are going overboard. Additionally, the company worked with the US government, the UK AISI, multiple private third-party organizations, and internal teams to red-team Fable’s safeguards for thousands of hours. Finally, Anthropic noted that no testers have yet been able to find a universal jailbreak on Fable 5. As expected, Anthropic disagrees that a narrow potential jailbreak should lead to the recall of a commercial model used by hundreds of millions of people. It warned that applying this standard across the AI industry could effectively halt new frontier model deployments. Anthropic concluded by mentioning that it is working to restore access to Fable 5 and Mythos 5 as soon as possible and plans to share more details within the next 24 hours.
    • Brave Browser 1.91.172 is out.
  • 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
      503
    2. 2
      +Edouard
      176
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      ATLien_0
      92
    5. 5
      Steven P.
      79
  • Tell a friend

    Love Neowin? Tell a friend!