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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 0

Some rules that strike me:

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

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

Link to comment
Share on other sites

  • 0

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

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 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;
}

:)

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 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;
}

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This topic is now closed to further replies.