• 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

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)

I always found it interesting that I would get compliments on the tech specs for each of the applications I wrote at work, when my documentation (to me) was minimalist. Now that I work in the other side of the house (ALM/SCM), I can see why my documentation got the praise it did. Not documenting is probably one of the worst habits a developer can get into, and the "I don't have time" excuse is just lame. Documentation should always be a part of your initial estimates, and then pad your estimate again so that when management cuts your timeline, you still have the required time.

I feel better now that I got that out. :D

  • 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.

Man, you should try some functional languages.

But seriously, that switch is crystal clear to understand only I'm not sure if it implements that what the programmer wanted to.

I don't understand what's so hard about a break statement, from the moment I write a case I also write the break;, just like I would with indenting, I write all the brackets needed and only then I write whatever I need to inside that block.

Also, using a decent IDE helps a lot. Sure using Gedit / notepad / Kate / whatever-floats-your-boat and then compiling from commandline/bash/terminal is all cool and nice, but there is a reason why IDEs were made, it's to cut down the time on developing and debugging significantly because of its integrated workflow, syntax checking and autocompletion.

I understand the notion of leaving dangerous stuff (stuff that cause a lot of pitfalls) out of the language, but if you know that when someone gives you a rope and you know that you'll probably hang yourself with it, then the question is: Why don't you just leave the rope alone?

EDIT: Concerning the rope example, I just realized that Vykranth was saying exactly what I've been saying. He doesn't like the rope because he knows that he might hang himself. But I just want to say, that while one programmer will hang himself if you give them a rope, it doesn't mean that another will as well.

  • 0
I always found it interesting that I would get compliments on the tech specs for each of the applications I wrote at work, when my documentation (to me) was minimalist. Now that I work in the other side of the house (ALM/SCM), I can see why my documentation got the praise it did. Not documenting is probably one of the worst habits a developer can get into, and the "I don't have time" excuse is just lame. Documentation should always be a part of your initial estimates, and then pad your estimate again so that when management cuts your timeline, you still have the required time.

I "sold" documentation as a safety-net for clients. We'll document the interfaces, the program flow, the hardware requirements (it was embedded systems stuff), function headers, etc. before we start - it'll cost about $x. If you decide our work isn't acceptable you can take documentation and have it implemented by one of our competitors. If you think our analysis of the problem is good then we can impliment what we've documented and designed for $y. If you hate the final product you can take documentation+code to one of our competitors for maintenance or simply do it in house. Further, by planning ahead like this I can save $z during the actual development because we'll have a clear understanding of the required functionality.

Most clients see documentation as stuff to make the programmer's lives easier. You need to sell it as having value to them: reduced costs to build, insurance against incompetence, better estimates, a contract to ensure they're getting what we promised, etc. On average I'd say I managed to get around 75% of the documentation written before any code was set down to be compiled (more if you count UI design as documentation).

  • 0

Use const on everything (C++)

Code to interfaces and not implementations.

Code stuff that can easily be updated later on with minimal changes.

Unit test your code

std::string over char*

comment your code

never use goto

use your style guidelines consistently

Never use win32. :p

Never use Hungarian notation

There are more than 1 way to code something. Just because you code it one way doesn't mean it's correct, or the best solution. (Goes back to unit test)

  • 0

I always found it interesting that I would get compliments on the tech specs for each of the applications I wrote at work, when my documentation (to me) was minimalist. Now that I work in the other side of the house (ALM/SCM), I can see why my documentation got the praise it did. Not documenting is probably one of the worst habits a developer can get into, and the "I don't have time" excuse is just lame. Documentation should always be a part of your initial estimates, and then pad your estimate again so that when management cuts your timeline, you still have the required time.

I feel better now that I got that out. :D

well I didn't say no documentation, I said the code SHOULD speak for itself, in the code we'd usually just put a comment on what the class did, and if something was unusal we'd explain why it was done that way, I am talking about code documentation not the supporting documents you write up about why you designed it the way you did and stuch and how it should work how tests should turn out etc.... I've seen people write books in the comments in code, and thats basically what they wanted in college..... was stupid as heck I shouldn't need to write a page on how hello world works in comments

  • 0

Some rules that strike me:

1. No line should exceed 80 characters

2. No name: variable, function, etc,. should exceed 32 characters

3. Use appropriate prefixes: u4 for uint4, i1 for int1 etc,.

4. Don't use goto: Nothing reduces readability more than goto.

5. Don't comment things which are obvious

6. Use uniform indentation: I prefer 4 white spaces

I can't think of any real-world function over 200 lines without multiple returns.You just can't invoke action handlers for state-event machines without switches and not make it a mess.

  • 0

I understand the notion of leaving dangerous stuff (stuff that cause a lot of pitfalls) out of the language, but if you know that when someone gives you a rope and you know that you'll probably hang yourself with it, then the question is: Why don't you just leave the rope alone?

EDIT: Concerning the rope example, I just realized that Vykranth was saying exactly what I've been saying. He doesn't like the rope because he knows that he might hang himself. But I just want to say, that while one programmer will hang himself if you give them a rope, it doesn't mean that another will as well.

This is indeed my point. In C/C++, there are plenty of ropes to hang youself with: variables scoping, override method, silent promotion of types, copy constructors ...

I took a course in C# last year: I ended up with a deep envy of C# developers. C# force oneself to be much more explicit and formalized.

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.

I am pretty sure that there are plenty of bad if examples.

I did not say that switch was useless: I am just saying that you have to be careful with switches.

For example

switch( criteria ) {
	 case 1: method1; break;
	 case 2: method2; break;
	 default: method3; break;
}

is transformed into

if( criteria == 1 ) {
	 method1;
} else if( criteria == 2 ) {
	 method2;
} else {
	 method3;
}

but

switch( criteria ) {
case 1: method1;
case 2: method2; break;
default: method3; break;
}

is transformed into

if( criteria == 1 ) {
method1;
method2;
} else if( criteria == 2 ) {
method2;
} else {
method3;
}

or

switch( criteria ) {
case 1:
case 2: method2; break;
default: method3; break;
}

is transformed into

if( criteria == 1 or criteria == 2) {
method2;
} else {
method3;
}

and, to finish,

switch( criteria ) {
case 1: break;
case 2: method2; break;
default: method3; break;
}

is equivalent to

if( criteria == 2) {
method2;
} else if( criteria != 1 ) {
method3;
}

In all the switch examples, I have made some small coding changes which can be easily over-looked but that modify considerably the execution flow.

  • 0

This rule is probably the most contentious one. To each his own. I feel that it brings clarity to the code.

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.

  • 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.

Windows is stuck with _a lot_ of things for the sake of backwards compatibility, haha!

Although I'm pretty sure a lot of it also true for the Linux kernel

  • 0

Goto statements are pure evil.

Break, continue and methods with more return statements should be avoided in my opinion but sometimes of course it's better to write two or three return statements, readability should be most important.

Switches are dangerous since most languages support fall-through (so looking for a mistake caused by a missing break statement in a switch is quite a nightmare especially when the source code consists of an enormous number of lines) but unfortunately it's quite impossible to avoid them without causing any damage to the readability and maintainability of the code.

What I consider very important is to keep the code of every method as short as possible, one screen tops, 10 lines ideally.

Also I think Joshua Bloch's Effective Java (Second edition) shouldn't be left out of this discussion as far as OOP is concerned. There are many best practices that should be known to every developer in the book.

  • 0

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

As a professional programmer and someone with common sense, all of these "rules" are absolutely moronic and can lead to writing horrible code.

And whoever says goto is bad has clearly never looked at OS or C code. :p

  • 0

Prefixes leads to garbage like hungarian notation. Which imho is retarded.

The original hungarian notation was fine, the problem is that it's been morphed to represent the type of the data, rather than the meaning of the data.

If you're dealing with two coordinate systems (say, one screen and one virtual), you would prefix your variables names with how they're used (devPixelsX, virtPixelsY, etc.), so you can see just from reading if you're multiplying a virtual offset by device pixels or such (Knowing you're multiplying two integers together on the other hand doesn't tell you anything, you're multiplying them anyway so you already know the types)

  • 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 < 10) return '0' . $i;
  else return $i;
}

why not just

function twoDigits($i)
{
return ($i < 10) ? '0' . $i : $i;
}

:)

  • 0

Hello Ambroos, congratulations on starting your studies.

Here are my thoughts on the rules you posted:

  • never use more than one return statement

I'm neural to this rule. While I can see where in verbose code it could be confusing to flow the control flow of a program, I don't see the use of a temporary return variable to make the code more readable.

  • never use break or continue

This I agree with. It's not nearly as bad as the infamous 'goto' statement others have mentioned, but it still can make programs harder to read and understand. Especial while maintaining code, the simple uneducated use of a break or continue could be disastrous (see: 1990 AT&T U.S. National Telephone Network Failure). Furthermore, I cannot think of an instance in which a break or continue could be used, that the result could not be achieved by editing the condition of a loop.

  • avoid using switch

I completely disagree with this one. There is no reason why switch statements shouldn't be used. In fact it would probably increase readability over an if-else block. Personally, I tend to favor if-else chains, but that's my own style.

  • 0

Wow, what a discussion :p

This is one of the pieces of code we wrote (and what our teachers consider good coding style). It could just as well be done with multiple returns, I suppose, but I think this feels clean? (checks if an array (part of the object) is empty or not, and outputs the object number (private variable) plus the amount of objects (or EMPTY).


public String toString() {
String output = "choice: " + this.objectNumber() + "\t";
if (this.isEmpty()) {
output += "EMPTY";
} else {
output += this.packages[0].toString() + "\tamount: "
+ this.getPackageAmount();
}
return output;
}
[/CODE]

I'm eager to learn, so I wonder what you guys think about this. Couldn't really find any code with multiple else if's, so not sure on the actual usefulness of switch (I haven't needed it so far, but we didn't do that much yet). Another bit of code on how we avoid using break:

[CODE]
public Student findStudent(String studentNaam) {
Student output = null;
for (int i = 0; i < this.students.length && output == null; i++) {
if (this.students[i] != null
&& this.students[i].getNaam().equals(studentNaam))
output = this.students[i];
}
return output;
}
[/CODE]

As you can see there we check in the for condition if the thing we're going to output is still null (aka hasn't been changed yet). I haven't really seen much other code, but when I take a look at a book and see multiple returns or breaks it usually confuses me, it seems to make it hard to mentally execute the code.

And, is it a good idea to just CTRL-SHIFT-F in Eclipse to indent your code?

  • 0

This I agree with. It's not nearly as bad as the infamous 'goto' statement others have mentioned, but it still can make programs harder to read and understand. Especial while maintaining code, the simple uneducated use of a break or continue could be disastrous (see: 1990 AT&T U.S. National Telephone Network Failure). Furthermore, I cannot think of an instance in which a break or continue could be used, that the result could not be achieved by editing the condition of a loop.

You can always avoid break or continue, but it doesn't necessarily make things more readable. Consider (pseudocode - the file layout isn't supposed to make sense):


while (!eof(file))
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]

[CODE]
while (!eof(file))
header = file.readbytes(22)
if (!isValidHeader(header))
continue

dataOffset = int(file.readbytes(4))
if (dataOffset < 0)
continue

file.seek(dataOffset)
dataLength = int(file.readbytes(4))
if (dataLength < 0)
continue

dataChunk = file.readbytes(dataLength)
store(dataChunk)
// process dataChunk
[/CODE]

The use of continue avoids indenting the entire body with each condition.

  • 0

Wow, what a discussion :p

This is one of the pieces of code we wrote (and what our teachers consider good coding style). It could just as well be done with multiple returns, I suppose, but I think this feels clean? (checks if an array (part of the object) is empty or not, and outputs the object number (private variable) plus the amount of objects (or EMPTY).

public String toString() {
  String output = "choice: " + this.objectNumber() + "\t";
  if (this.isEmpty()) {
   output += "EMPTY";
  } else {
   output += this.packages[0].toString() + "\tamount: "
	 + this.getPackageAmount();
  }
  return output;
}
[/CODE]

I'm eager to learn, so I wonder what you guys think about this. Couldn't really find any code with multiple else if's, so not sure on the actual usefulness of switch (I haven't needed it so far, but we didn't do that much yet). Another bit of code on how we avoid using break:
[CODE]
public Student findStudent(String studentNaam) {
  Student output = null;
  for (int i = 0; i &lt; this.students.length &amp;&amp; output == null; i++) {
   if (this.students[i] != null
	 &amp;&amp; this.students[i].getNaam().equals(studentNaam))
	output = this.students[i];
  }
  return output;
}
[/CODE]

As you can see there we check in the for condition if the thing we're going to output is still null (aka hasn't been changed yet). I haven't really seen much other code, but when I take a look at a book and see multiple returns or breaks it usually confuses me, it seems to make it hard to mentally execute the code.
And, is it a good idea to just CTRL-SHIFT-F in Eclipse to indent your code?

#1 - Seems okay... although you would probably wanna use StringBuilder for this
#2 - I believe this would be faster. It has less potential comparisons because it doesn't need to check the status of 'output' each iteration. And to be quite honest... it is much easier to read this way :)
[code]
public Student findStudent(String studentName)
{
	for(int i = 0; i &lt; this.students.length; i++)
	{
		if(this.students[i].getName().equals(StudentName))
			return this.students[i];  // return here acts as a break as well ;)
	}
	return null;
}

  • 0

You can always avoid break or continue, but it doesn't necessarily make things more readable. Consider (pseudocode - the file layout isn't supposed to make sense):


while (!eof(file))
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]

[CODE]
while (!eof(file))
header = file.readbytes(22)
if (!isValidHeader(header))
continue

dataOffset = int(file.readbytes(4))
if (dataOffset < 0)
continue

file.seek(dataOffset)
dataLength = int(file.readbytes(4))
if (dataLength < 0)
continue

dataChunk = file.readbytes(dataLength)
store(dataChunk)
// process dataChunk
[/CODE]

The use of continue avoids indenting the entire body with each condition.

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

[CODE]
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]

  • 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 :)

You can terminate the loop inside the condition too once you found what you are looking for.

All 2 or 3 books i've read about proper oop programming recommend not using break inside a loop if possible.

I've worked for a company having an IT dept of over 800 heads (IT only company was bigger than that). If all devs start to code the way they want it quickly becomes a mess (and sadly this is always what is hapenning).

If there's coding rules where you are working follow them even if you think they are moronic because you think you are l33t and know how to properly code.

  • 0

As a professional programmer and someone with common sense, all of these "rules" are absolutely moronic and can lead to writing horrible code.

And whoever says goto is bad has clearly never looked at OS or C code. :p

Hum those coding "rules" are about oop and not old C code, or cobol, or asm, or ml, etc ...

This topic is now closed to further replies.
  • Posts

    • Keep in mind Intuit has lobbied like crazy to keep taxes complicated so they can continue to sell tax software. They also got caught hiding their legally mandated free version so they could release a second one that pushed countless people into charges they didn't need to pay to file. Intuit leads the charge on inventing problems so they can sell you the solution and disrespecting you in the process.
    • Oddly, there was a time that UFC games were culturally relevant, largely because of the graphics and gameplay that was different than the norm. But it seems like as the sport grew in popularity, gaming outlets stopped talking about the games.
    • Microsoft Edge 149.0.4022.69 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.69 changelog: Fixed an issue that caused the Downloads dialog to continue displaying the "Keep/Delete" prompt for .rdp files after the download completed. Stable channel security updates are listed here. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User for 1-Year) by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where for only a limited time, you can save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1 Year) for Windows. Take control of your business finances with Intuit® QuickBooks® Desktop Pro Plus 2024 Lifetime Activation for Windows. This powerful accounting software simplifies bookkeeping, expense tracking, invoicing, and financial management—all in one intuitive platform. Designed for small business owners, freelancers, and accountants, QuickBooks® Desktop Pro Plus 2024 ensures accuracy, efficiency, and seamless transaction tracking. Stay organized, save time, and manage your finances with confidence—no subscriptions, just lifetime access! Financial and business management Comprehensive Financial Management: Gain access to a full suite of features designed to handle everything from creating invoices & managing expenses to generating reports and tracking sales. Enhanced Reporting Tools: Generate professional reports & insights to make informed financial decisions and help you stay ahead of your business goals. Job Costing: Track the profitability of specific jobs or projects. Fixed Asset Management: Track the depreciation & value of fixed assets. Customer & Vendor Management: Organize information, streamline communication & enhance customer relations. Sales Order Processing: Create & manage sales orders from start to finish. Purchase Order Processing: Create & manage purchase orders to streamline vendor payments. Improved Inventory Management: Enhanced features for tracking inventory levels & costs. Automation, integration, and support Enhanced Bank Feeds: Web Connect (manual QBO imports), works on all licenses for easier bank reconciliation Time Tracking: Track employee time to accurately calculate payroll and project costs Easy Data Import: Quickly transfer financial data from Excel or older QuickBooks® versions Why choose Intuit® QuickBooks® Desktop Pro Plus 2024? Effortless Installation: Quick and easy setup with step-by-step guidance. No Hidden Costs: One-time payment—no subscriptions or recurring fees. Direct Official Download: Access the software securely from the official QuickBooks® website. Stay Up to Date: Get the latest updates and features for optimal performance. Multilingual Support: Available in multiple languages to suit your needs. Lifetime Access: A one-time purchase means no ongoing costs. IMPORTANT: Cloud integrations (QuickBooks Payments, TurboTax, and Online logins) are NOT included. Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: Windows Max number of device(s): 2 (for 1 user only and can't be used simultaneously) Version: 2024 (United States) 64-bit Available to both NEW and EXISTING users For US customers only Updates included An Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1-Year) for Windows: Lifetime License normally costs $536, but it can be yours for just $299.99 for a limited time, a saving of $236. There are also other plans available. For specifications, and license info please click the link below. Get Intuit QuickBooks Desktop Pro Plus 2024 for just $299.99 This is a time limited deal For US customers only. 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.
    • AFAIK you shouldn't be getting a consent popup at all from Canada, so I think it is to do with a VPN or private/secure DNS.
  • Recent Achievements

    • Week One Done
      agatameier earned a badge
      Week One Done
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      175
    3. 3
      PsYcHoKiLLa
      139
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!