• 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

    • Trailer park trash “sport “, fits the current White House
    • KataLib 5.3.0.0 by Razvan Serea KataLib is more than just a music player — it's a complete audio suite designed for music lovers and creators alike. It combines a powerful audio player, a flexible metadata editor, a capable audio converter, and a music library manager into one streamlined application. Core Features: Audio Player Enjoy seamless playback of virtually any audio format or even streaming video files. DJ Mode lets you mix tracks with manual or automatic crossfades. You can also load and save WinAmp-style playlists for quick access to your favorite sets. Audio Converter Convert between a wide range of audio formats effortlessly. Trim or normalize your output automatically, and even extract audio from streaming video sources. Ideal for preparing files for different devices or platforms. Metadata Editor View and edit ID3v2 tags and other metadata. Batch edit multiple files at once, and fetch missing information directly from the MusicBrainz database. You can also apply or update album art with ease. Music Library Manager Organize your entire audio collection, search across tracks instantly, and download cover images from the internet — or use your own custom artwork. KataLib makes it easy to keep your library tidy and enriched with useful info. Supported Formats: KataLib supports a wide range of both lossy and lossless audio formats: Input: OPUS, AAC, FLAC, M4A, MP3, MP4, MPC, APE, AIF, MKV, AVI, MOV, FLV, WEBM, Ogg Vorbis, WAV, WAVPack, WMA, AC3, OGA, MP2, MPGA, MPEG, DTS, M4B, DSD (DFS) Output: OPUS, FLAC, M4A, MP3, Ogg Vorbis, WAV Under the hood, KataLib uses the trusted FFmpeg engine for audio conversion and media playback, ensuring compatibility with virtually all mainstream media formats. KataLib 5.3.0.0 changelog: Added Option to select the Zoom level of the Oscilloscope visualizer. The taskbar button of the app now displays the progress of its processing tasks. The metadata text of the Visualization Video can now be aligned by the user. We can now reorder the order of the Visualizers and Metadata, in the Visualization Video Setup dialog, by removing any item and adding it again. It will be added at the end. Changed The font size of the Visualization Video can now be more than 30 points. Updated yt-dlp library to version 2026... Fixed Opening the Visualization Video Setup dialog could fail if the settings were wrong. Sometimes there were false duplicates in the Rename Tracks dialog. Tracks without metadata appeared without title in the Recent menu. Download: KataLib 5.3.0.0 | 90.0 MB (Open Source) Links: KataLib Home Page | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • EA Sports UFC 6 review: Brutal, satisfying, and surprisingly accessible to newcomers by Pulasthi Ariyasinghe EA’s UFC series of fighting games has been putting out games for over 10 years now, but it’s a series I have never spent any time with. As a PC guy, the series being console-exclusive is the primary reason for that. The latest entry to the series, EA Sports UFC 6, is still not coming to PC, but I have an Xbox now. When EA reached out to see if I could have a crack at the game and give my opinion about it, I finally got the chance to see what this franchise is about. I have spent about a week playing UFC 6 on the Xbox Series X. Despite my lackluster skill with fighting games, I still have fun with entries like Street Fighter and Tekken. I quickly came to realize this is a different kind of fighting game, not the arcade titles I am usually dabbling with. Most of the week that I spent playing UFC 6 was in the career mode, trying not to get knocked out while slowly improving my combos and reactions. The review below will be from the perspective of a newcomer to the series and an amateur fighting game fan, so please forgive any mistyped lingo or series-staple mechanics I am not comprehending. In the Ring Getting a solid hit in UFC 6 is satisfying. It’s probably the most satisfying impact reaction I have seen in a fighting game. The ripples in the muscles, the spray of sweat (and blood), the meaty sound, and the subsequent stumble all carry a lot of weight. If I miss a heavy swing like that, though, I already know that I'm in for a world of hurt from the incoming counters. The fighting is a real treat. The actions aren’t as snappy as arcade titles, so a miss feels like a much bigger mistake here. This slowness did take some getting used to, but I felt the improvement in my abilities even after a few drills with basic punch and kick combos. If I’m not deliberate with my actions in the ring, whether it be a hasty retreat or a flying punch, the possibility of getting instantly knocked out is always there. The head, chest, and legs all come with their own health bars, so guarding just one area is just asking for trouble. A few hits to the head, and it's game over. Meanwhile, you won’t even be able to stay on your feet if they get damaged enough, drastically lowering the total amount of stamina available for the rest of the match. I was also encountering a large range of fighting styles to customize my own fighter with. There are a huge number of real-life superstars here from multiple eras. It’s not as exaggerated as Street Fighter or Tekken, but the way they move, evade, throw punches, or even take steps is based on their real-life counterparts. I can see this being a big draw for any mixed martial arts fan. One feature I was surprised to see here was the 'Flow State' ability. As rounds progress, a power-up meter can give a temporary boost to the unique fighting style of the selected fighter, essentially boosting what they are good at. There is an entire visual effect that kicks in when activating this, too. The surprising part was seeing something like this in a game that feels like it’s aiming to be more of a simulator than an arcade fighter. My skill level is too low to use this exactly how the game wants me to, so I ended up triggering it whenever the opponent did it as well. Streamlined vs Authentic When I first started it up, UFC 6 asked me about my experience with the series. Being genuinely new, I took its advice and opted for a lowered difficulty level and 'Streamlined' controls. Quickly, I realized that this wasn’t for me. My chosen fighters were throwing random attacks, no matter what combination the game was trying to teach me. Win streaks were happening, and I was already getting bored out of my mind just a few matches in. Turning off this mode and switching to 'Authentic' controls fixed everything right up. I was now able to control my fighter with more precision than I expected. I could control each arm and leg, which body part my attacks would aim at, and the fully customizable controls for setting up unorthodox moves were a cherry on top. None of these made me an expert at the game, but at least I was being beaten up fairly. This is not a point against UFC 6, though. Giving the option for anyone to enjoy the game is always a good thing in my eyes. There is a lot of customizability in the difficulty, with everything from slow-motion reactions to specific assists being offered as toggles. If I had a friend coming over and wanted to try a quick 1v1, the streamlined controls option is one I’d consider to make it a light and fun fight. The one part of the fighting that did not click with me was the grappling. Being taken to the ground brings in an entirely new control mechanism involving mounts and submissions that feel more like quick-time events than the heavy, tactical fighting I had seen so far while standing. The game wants me to hold sticks in certain directions to change the position or pull off submissions, trying to do the opposite actions of the opponent. Even though I tried to get used to this gameplay, it just felt like a momentum killer, and I eventually just wanted to get back on my feet to get back into the action. Legacy and Career It was UFC 6’s career mode that I wanted to play the most when I started it up. I grew up with EA Sports games, and taking my team from the ground to the top has always been my favorite task. UFC 6 has that same option but also offers a more cinematic entrance to the career experience than I expected with ‘The Legacy’ mode. This mini-campaign follows an up-and-coming fighter, Chris Carter, who is attempting to reach the heights his father had reached in the sport. Starting with a small-time gym and coach, the story follows both his growth in the space as well as the growing rivalry with a friend and fighter, Danny Lopez. The fights in this mode are very good at introducing a newcomer like me to the sport and its varying techniques. Cinematics land between the major fights, showing the growing tension between the two fighters as the years go by, feeling the pressure to not miss out on the hard-earned chances. The dialogue can be a little corny at times, especially when the bar fights kick off, but I largely enjoyed the storyline. At the end of it, I was pretty much familiar with all the mechanics of the career mode, unlocking new skills and moves, and how I needed to approach fights, both outside and inside the ring. This story mode isn’t a very lengthy one, so don’t expect an hour-long campaign. Once the conclusion is reached, Carter’s journey continues as if it’s a normal career playthrough, though I decided to start over from scratch now that I have some know-how about the basics. The career mode is very streamlined, which is to be expected considering there isn’t a team to manage like in other EA Sports games. It’s the journey of one fighter. When a fight comes up in the calendar, I could choose how many weeks I dedicate to preparing for it at the gym. A longer prep time gives the opportunity to get my fighter’s fitness up (giving a bonus during fights), earn more money and points for unlocking new skills, and gain more fans to fast-track the rise to stardom. While that sounds like a lot of things to manage, it’s more like a few clicks. There is a social media menu that sometimes pops up with canned replies I can send to fans, and the sponsors are once again a single click away from being assigned as finished. It’s the training aspect that adds a gameplay angle. Using the money from winnings and sponsorships, I was hiring different types of trainers and learning fancier moves to use in the ring. One small thing I appreciated was that it was possible to injure each other during these training sessions. If a trainer goes down in a bad way while sparring, they won’t be available for the remainder of training. If my fighter is injured, it takes valuable time and resources to heal and recuperate. Just like in real life, it makes sense not to go so hard during training sessions and save that energy for the main event. Every training or sponsorship activity I took part in used up the days and weeks I had before the next fight, bringing a balancing element to the whole ordeal. There were times I simulated most of these to just get to the next fight, but the grind for gaining even the slightest bit of advantage while trying not to overdo it is an enjoyable one. Outside of quick fights and career modes, UFC 6 also introduces an almost museum-like mode to explore a trio of fighters considered to be legends of the sport: Max Holloway, Alex Pereira, and Zhang Weili. The aptly named Hall of Legends mode is unlike everything else seen in the game. Each of these fighters has entire levels dedicated to them that I could walk around in and explore their journey into the UFC. This includes footage from real-life fights and interviews about their original inspirations and training methods. Each of these spaces is almost like an interactive documentary. Once the highlights are done, the mode offers the opportunity to take over a deciding fight from the superstars. It’s an impressive transition. Going from the real-life televised event with crowds and commentary to immediately taking over in the game has some real hype behind it. Performance and visuals It’s clear to see that UFC 6 is going for a photo-realism look with its visuals compared to any other fighting game. The fighters don’t look great in selection screens. But inside the arenas, under the flood lights, surrounded by crowds, and facing an opponent, the visuals are more than impressive. As ghastly as it is to witness, things like blood spraying into the mat and muscles reddening as they get pummeled keep improving the immersion. The fluid animations help sell the illusion even further. A missed kick carries the momentum to require a corrective step. Hard punches that glance off blocks give off the air of a hit that still took some wind off the opponent’s guard. The special moves with flips and spins look mega awkward when missing, just as they do in real life. Suffice to say, the Frostbite Engine powering this game is one of the biggest strengths of EA development studios. Playing on the Xbox Series X, the 60 FPS gameplay did not miss the mark or cause any slowdowns that I could detect. I still wish this series were on PC to see just how far the developer can push the engine. One area I continue to have issues with, surprisingly enough, is the menus. The game has fast loading screens, but almost every menu I click through has a large amount of noticeable lag before it registers. This is immensely painful in the career mode, since I have to go through multiple menus between fights to train and do sponsorships, and having a 3-second pause when selecting a simple move between pages is the only time that made me quit the game. Thanks to Xbox’s quick resume, though, I was able to instantly jump back in the next day to the same point (and wade through more laggy menus). Conclusion My primary mission going into this EA Sports UFC 6 review as a newcomer to the series was to find out if this is a good jumping-in point for someone like me. Suffice it to say, the game passed that test with flying colors. Despite the high skill ceiling, the legacy mode introduction campaign, multiple types of accessible controls, and streamlined career had me picking up the basics and fighting styles much faster than I expected. I wish I had gotten to try out competitive multiplayer during my time with the game, too, but the lack of players in the pre-release version prevented this. The impressive visuals and animations, coupled with the impact physics that let me feel every punch and kick easily, made this the most immersive fighting game I have played. The only part that gave me pause was the grappling gameplay, which killed the momentum in most fights. The Flow State amplifying system didn’t hamper the experience, but I also felt like it made more sense for an arcade fighter, not this. Easily the most annoying thing about UFC 6 was its laggy menus, which I hope get some sort of fix later. Returning series veterans might have a completely different experience from me. But for a new fan like me looking to climb ranks and see fighters get floored in spectacular ways, UFC 6 doesn’t miss a step. EA Sports UFC 6 is releasing on June 19 across Xbox Series X|S and PlayStation 5 for $69.99. Ultimate Edition owners can already jump in via advanced access. This review was conducted on the Xbox Series X version of the game provided by EA.
    • No, Microsoft is obviously just spending money on maintaining a product with 0 users.
  • 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
      486
    2. 2
      +Edouard
      173
    3. 3
      PsYcHoKiLLa
      138
    4. 4
      ATLien_0
      94
    5. 5
      Steven P.
      79
  • Tell a friend

    Love Neowin? Tell a friend!