• 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

Switches and if - else if - else statements some times lead to messy code

Point is to make the code small in size and easy to understand - this may refactoring to use continue and break statements or vice-versa refactoring breaks and continues to loop conditions and if statements and switches

  • 0

Wouldn't initializing your variables (another good rule of thumb) solve that problem:


while (!eof(file))
dataOffset = -1;
dataLength = -1;
header = file.readbytes(22)
if (isValidHeader(header))
dataOffset = int(file.readbytes(4))
if (dataOffset >= 0)
file.seek(dataOffset)
dataLength = int(file.readbytes(4))
if (dataLength >= 0)
dataChunk = file.readbytes(dataLength)
store(dataChunk)
// process dataChunk...
[/CODE]

That mitigates the issue, but leaves most of the code indented. Also, it's not strictly equivalent because you'll have to go through all the ifs everytime whereas my version continues to the next loop as soon as the first error is detected. Also, now you initialise your variables twice (once to the error value, and another time to the real value) instead of once. (btw my code didn't have any uninitialised variables. They were declared at the point of initialisation)

Also your version is more error-prone because what happens if someone adds some logic before the end of the while loop. He has to remember to put it inside the last if (condition) because otherwise it'll execute for an invalid record. Whereas when you break early with continue, no code can be executed for invalid records by mistake.

  • 0
If you need to know the type of a variable, get a good IDE and hover your mouse over it. Including the type in the variable name, leads to garbage in front of the useful name. It also adds a maintenance nightmare when variable types are changed. A good example is in Win32 LPCSTR is defined to be a char const * It stands for "Long Pointer to Constant STRing" the long part is completely irrelevant nowdays. But Windows is stuck with it for backwards compatibility.

I prefer not to use the mouse too much while programming. I also don't see the big deal about changing variable types. Good code is portable and thus, you don't need to change the notation. I am not suggesting that all type information should be in the name, just a p for pointers, a for arrays, t for typecasts: that sort of thing.

I implement network protocols and there is a lot of packet encoding and decoding involved. Seeing a variable and knowing what it is definitely helps.

I am not claiming that this is useful everywhere, just that it is a rule I like to follow.

  • 0

I prefer not to use the mouse too much while programming. I also don't see the big deal about changing variable types. Good code is portable and thus, you don't need to change the notation. I am not suggesting that all type information should be in the name, just a p for pointers, a for arrays, t for typecasts: that sort of thing.

I implement network protocols and there is a lot of packet encoding and decoding involved. Seeing a variable and knowing what it is definitely helps.

I am not claiming that this is useful everywhere, just that it is a rule I like to follow.

If you can't remember the types that you're using, or anything of that nature. Then you shouldn't be programming. You should be using smart variable naming conventions, not crappy polluted names that are not helpful at all. If you wanna change the type then you will have to change the variable name, and yet bring source compatibility and even binary compatibility. I write a network protocol, and I don't use all that garbage type in variable stuff. Btw it's not a rule, it's just your preference, and a bad one at that.

  • 0

If you can't remember the types that you're using, or anything of that nature. Then you shouldn't be programming. You should be using smart variable naming conventions, not crappy polluted names that are not helpful at all. If you wanna change the type then you will have to change the variable name, and yet bring source compatibility and even binary compatibility. I write a network protocol, and I don't use all that garbage type in variable stuff. Btw it's not a rule, it's just your preference, and a bad one at that.

Do you honestly remember the type of every variable you declare? I wonder if you have ever written more than 1000 lines in a program. UINT4 u4Variable is 4 bytes of memory, plain and simple. If you are porting it to a different platform, you modify what UINT4 refers to so that it still means 4 bytes of memory. If there is a possibility that you may need more than 4 bytes of memory for that particular purpose in the future, you should be using a more flexible type in the first place.

Naturally, there are tools that make all this redundant, but there is nothing wrong in relying less on them. I honestly feel that all these tools take the fun out of programming- you feel like a part of an assembly line rather than a human being capable of making intelligent decisions.

  • 0

Do you honestly remember the type of every variable you declare? I wonder if you have ever written more than 1000 lines in a program. UINT4 u4Variable is 4 bytes of memory, plain and simple. If you are porting it to a different platform, you modify what UINT4 refers to so that it still means 4 bytes of memory. If there is a possibility that you may need more than 4 bytes of memory for that particular purpose in the future, you should be using a more flexible type in the first place.

Naturally, there are tools that make all this redundant, but there is nothing wrong in relying less on them. I honestly feel that all these tools take the fun out of programming- you feel like a part of an assembly line rather than a human being capable of making intelligent decisions.

If you are changing types to match a new system, you are doing it wrong. You should be using uint32_t and friends and having it done for you.

The tools are there to help you, the way I see it is that I'm the creative one coming up with the way it should be done. My lovely IDE just colours it nicely and puts a squiggly red line if I make a mistake typing it in.

  • 0

If you are changing types to match a new system, you are doing it wrong. You should be using uint32_t and friends and having it done for you.

The tools are there to help you, the way I see it is that I'm the creative one coming up with the way it should be done. My lovely IDE just colours it nicely and puts a squiggly red line if I make a mistake typing it in.

I am not sure I follow. Each chipset manufacturer provides a set of APIs and basic data types that their OS variant (usually some variant of Linux butchered to suit their requirements) supports. Our code is completely portable: we just have to match our data types with what the underlying architecture supports. As we cannot compromise on performance, we have to port for each environment.

Edit: Just to be clear, I am talking about C.

  • 0

I am not sure I follow. Each chipset manufacturer provides a set of APIs and basic data types that their OS variant (usually some variant of Linux butchered to suit their requirements) supports. Our code is completely portable: we just have to match our data types with what the underlying architecture supports. As we cannot compromise on performance, we have to port for each environment.

Edit: Just to be clear, I am talking about C.

Ah, I was thinking that you had stdint.h available and configured for each system

  • 0

Do you honestly remember the type of every variable you declare? I wonder if you have ever written more than 1000 lines in a program. UINT4 u4Variable is 4 bytes of memory, plain and simple. If you are porting it to a different platform, you modify what UINT4 refers to so that it still means 4 bytes of memory. If there is a possibility that you may need more than 4 bytes of memory for that particular purpose in the future, you should be using a more flexible type in the first place.

Naturally, there are tools that make all this redundant, but there is nothing wrong in relying less on them. I honestly feel that all these tools take the fun out of programming- you feel like a part of an assembly line rather than a human being capable of making intelligent decisions.

I've wrote a project with code lines over 25,000. I remember everything, that I write. I also use "auto" a lot in C++. My code completion gives me all the type information. Obviously you ain't using a decent IDE that does that. You can blame that on yourself. Just because you probably develop in notepad, or vim, or something doesn't make you better. But wasting your time prefixing every stupid variable with a type makes no sense. You are just making yourself do that much more work, and to maintain. If you prefer that much work, then continue. I rather just get the stuff over with, and keep my source compatibility and binary compatibility, while keeping my source code neat and not have "hungarian notation" garbage in my code.

If you really want to see my code, just pm me and i'll give you the link (even though my repo is outdated, and the most updated isn't on there).

  • 0

I've wrote a project with code lines over 25,000. I remember everything, that I write. I also use "auto" a lot in C++. My code completion gives me all the type information. Obviously you ain't using a decent IDE that does that. You can blame that on yourself. Just because you probably develop in notepad, or vim, or something doesn't make you better. But wasting your time prefixing every stupid variable with a type makes no sense. You are just making yourself do that much more work, and to maintain. If you prefer that much work, then continue. I rather just get the stuff over with, and keep my source compatibility and binary compatibility, while keeping my source code neat and not have "hungarian notation" garbage in my code.

If you really want to see my code, just pm me and i'll give you the link (even though my repo is outdated, and the most updated isn't on there).

Tell me this. When you are browsing a lot of code, wouldn't you like to see at a glance what the type of each variable is, especially when much of the code is written by someone else? Would you rather hover over each variable to see what type it is? If you are not convinced by my argument, let us agree to differ.

  • 0

Tell me this. When you are browsing a lot of code, wouldn't you like to see at a glance what the type of each variable is, especially when much of the code is written by someone else? Would you rather hover over each variable to see what type it is? If you are not convinced by my argument, let us agree to differ.

Why would I care about that? You're trying too hard to convince me into supporting MS Hungarian notation.

  • 0

Tell me this. When you are browsing a lot of code, wouldn't you like to see at a glance what the type of each variable is, especially when much of the code is written by someone else? Would you rather hover over each variable to see what type it is? If you are not convinced by my argument, let us agree to differ.

I work on a project that has 1.3 million lines of code, and I've never had a problem with that, Visual Studio just makes it to easy to figure stuff out on the fly as you type

  • 0

Tell me this. When you are browsing a lot of code, wouldn't you like to see at a glance what the type of each variable is, especially when much of the code is written by someone else? Would you rather hover over each variable to see what type it is? If you are not convinced by my argument, let us agree to differ.

So do you create an abbreviation for every type you create? Or is it just for built-in types? There are about a million built-in types in .NET (or Java or whatever framework you use): do you have abbreviations for all those? Or is it just for basic numeric types and strings? I don't see how that convention can be enforced in a way that is both coherent and practical.
  • 0

I use multiple returns especially in validation functions. Default the return to invalid and put the validated return inside an if--makes for a very short function:


bool CheckBounds(int number, int upper, int lower)
{
if (number >= lower && number <= upper)
{
return true;
}
return false;
}
[/CODE]

  • 0

I use multiple returns especially in validation functions. Default the return to invalid and put the validated return inside an if--makes for a very short function:

bool CheckBounds(int number, int upper, int lower)
{
	if (number &gt;= lower &amp;&amp; number &lt;= upper)
	{	  
		return true;
	}  
	return false;
}
[/CODE]


Even Shorter :)
[code]
bool CheckBounds(int number, int upper, int lower)
{
    return (number &gt;= lower &amp;&amp; number &lt;= upper);
}

  • 0
Do you honestly remember the type of every variable you declare? I wonder if you have ever written more than 1000 lines in a program. UINT4 u4Variable is 4 bytes of memory, plain and simple. If you are porting it to a different platform, you modify what UINT4 refers to so that it still means 4 bytes of memory. If there is a possibility that you may need more than 4 bytes of memory for that particular purpose in the future, you should be using a more flexible type in the first place. Naturally, there are tools that make all this redundant, but there is nothing wrong in relying less on them. I honestly feel that all these tools take the fun out of programming- you feel like a part of an assembly line rather than a human being capable of making intelligent decisions.

What are you actually writing, because really you shouldn't have to change your code every time you port it to a different system (In that case the code isn't that portable), unless you're dealing with some strange embedded systems.

But even then, in your example you're using a plain 32bit integer, I don't know what type of computer wouldn't handle those well.

  • 0

So do you create an abbreviation for every type you create? Or is it just for built-in types? There are about a million built-in types in .NET (or Java or whatever framework you use): do you have abbreviations for all those? Or is it just for basic numeric types and strings? I don't see how that convention can be enforced in a way that is both coherent and practical.

I work on C. We follow this convention for basic data types (numerical, p-pointer, a-array, g-global), not for structures.

What are you actually writing, because really you shouldn't have to change your code every time you port it to a different system (In that case the code isn't that portable), unless you're dealing with some strange embedded systems.

But even then, in your example you're using a plain 32bit integer, I don't know what type of computer wouldn't handle those well.

The code isn't changed, the portability layer is. The point I was trying to make is that there will be no need for me to change the prefixes every time I port to a different architecture. That is why I chose that particular example.

Let me reiterate: this is a rule my department follows and I am a fan. There may be many reasons why the Hungarian notation is not used, but the disadvantages do not affect us and it also provides valuable information about data types at one glance. I think many of you are referring to higher level languages that don't have direct memory manipulation, where the editor will provide type checking. It is not possible in the code we write and we need to easily know how many bytes to memcpy.

To be honest, when I put up the post about rules, it was a set of personal rules I like to follow. I am not saying that these rules that are applicable or convenient to everyone.

  • 0

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.

Finally, something we can agree upon. :)

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!