views:

922

answers:

12

As I do my coding I sometimes wonder if I'm doing things the best way or just the way it's always been done. Does what I'm doing make sense anymore?

For example, declaring all your variables at the top of the function. If I try to declare it twice or below where I start using it my IDE will bark at me at design time - so what's the big deal? It seems like it would make more sense to declare the variables right above the block where they'd be used.

Another one would be hungarian notation. I hate that all my variables related to a particular object are scattered throughout my intellisense.

With modern advancements in frameworks and IDE's, are there some coding practices that don't really apply anymore and others that may be just plain wrong now?

+1  A: 

Although it is in Java, this is the book I recommend for people who want to optimize/modernize their coding style: http://www.amazon.com/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091

cherouvim
+23  A: 

Don't declare variables above the block where they'll be used - declare them in the narrowest scope available, at the point of first use, assuming that's feasible in your language.

Hungarian notation will depend on the conventions for your language/platform. It also depends on which variety of Hungarian you're using - the sensible one (which I'm still not fond of) or the version which only restates the type information already available.

One thing to watch out for: when you take up a new language, make sure you take up the idioms for it at the same time, particularly the naming conventions. This will help your code fit in with the new language, rather than with your old (probably unrelated) code. I find it also helps me to think in tune with the new language as well, rather than fighting against it.

But yes, it's certainly worth revisiting coding practices periodically. If you can't decide why something's a good idea, try doing without it for a while...

Jon Skeet
+1 because, well, it's Jon Skeet!
Steven A. Lowe
(I realise you were probably joking, but it's a real concern.) I really hope that's not the case. How could I be encouraged to improve if people upvote me based on name rather than quality?
Jon Skeet
I was too busy voting you up to read your comments, fortunately, you have lots more questions and answers to vote up. Unfortunately I can only vote you up 30 times a day
1800 INFORMATION
Good one, Jon... In fact I check your posts very sharply for the same reason, i don't think your reputation can be a "fad", but is helpful to learn from someone who knows a lot, "according to StackOF"
Jhonny D. Cano -Leftware-
+1 not because its John Skeet (whoever that is, pshhhha) But because the 3rd paragraph is the real gem, the rest is kind of ho-hum usual stuff.
Neil N
Another +1 because the 3rd paragraph is pure enlightened Zen coding.
Cruachan
Jon if you started another account, say Teeks Noj, you'd still end up with a bazillion rep points after a while - quality tells ;-)
Steven A. Lowe
no way, it's all about quality? your answers are first class informative and helpful. I think when they say, +1 bacause it's Jon skeet, it's shorthand becuase Jon Skeet == Trade Mark of Quality.
Abdullah BaMusa
I don't understand why this was marked as the answer, when Jon never really answered the question... he only commented on what you wrote, but neglected the question, "What other outdated practices are there?"
Mark
@Mark: To quote Steven, "because, well, it's Jon Skeet". ;-)
MiseryIndex
@Mark: The question doesn't include "What other outdated practices are there?" How was I meant to answer a question which wasn't there?
Jon Skeet
+8  A: 

Short identifiers: many old-school coders use short, cryptic identifiers. Brevity is a useful virtue but considering that a good IDE has auto-complete, a descriptive name is far better than something easy to type.

Mr. Shiny and New
What do you want from us? We had only one letter and one letter or digit in GWBASIC.
alex
yes! I remember back in my commodore basic days, I had a peice of notebook paper with about 80 two-letter abbreviations and what they were used for in a large app I was working on
Neil N
Either one letter for local variables or full words. Or abbreviations with one letter from each word (the humps of the camel). Half-words and other arbitrary abbreviations are bad.
starblue
+1  A: 

The variables at the top make sense in a language like javascript. It doesn't has block scope, so it does simplifies the reading.

Consider a function body that contains:

//some code
if(something)
{
   var c = 123;
}

alert(c); // gives 123 when the if is executed and undefined when it doesn't.

That is a remainder that each language is different and that definitely can affect what is and isn't appropriate. Also consider the code you use in the related framework usually uses a certain coding style, if you go with something radically different you will inevitable end up with mixed styles.

Update: The above in javascript is changing (as mentioned in a comment). It doesn't seem to be broadly supported (didn't find a good link on it thought :(), which is also a reminder we can't rush into the new features without considering the context we use them.

eglasius
let has block scope in javascript. var is obsolete.
Pete Kirkham
@Pete is this already broadly supported?
eglasius
@Pete I don't think to get a good reference about it, according to this: http://ejohn.org/blog/versions-of-javascript/ javascript 1.7 isn't supported on IE, Opera and Safari.
eglasius
FF2.0+, Safari 3.2, 4.0, Chrome 1.0. http://en.wikipedia.org/wiki/JavaScript#Versions Unfortunately, it's not uncommon to have to use obsolete forms for compatibility.
Pete Kirkham
Good to know, but as you said we need to keep for some time for compatibility. Given IE8 also isn't supporting it, I would say a long time.
eglasius
+1  A: 

With modern advancements in frameworks and IDE's, are there some coding practices that don't really apply anymore and others that may be just plain wrong now

Depends on the language to a large extent.

W.r.t C:

  • Using the register keyword

W.r.t C++:

  • Abusing static; now you are supposed to use namespaces even if anonymous ones

Or, did I misunderstand your question?

dirkgently
abusing static goes far beyond C++, just take a look at how the singleton is abused in every OOP language out there.
Neil N
not that meaning of static, but the 'this name is restricted to this compilation unit' meaning of static.
Pete Kirkham
+6  A: 

Short lines: Some people insist on 80-column text. The rest of us have real monitors and don't mind if a line is longer than 80 chars. It can improve readability to have longer lines.

Mr. Shiny and New
Agreed, I cant stand it when simple function calls are broken down into 4 lines because the a-hole wants to keep everything narrow.
Neil N
So, what printer fonts do you use...? Avoiding unbounded lines (if not necessarily limiting oneself to 80 characters) isn't a bad practice.
Pontus Gagge
When coding, you should write for the convenience of the largest set of possible readers. Exactly where that balance lies, now, that is a greater challenge.
Pontus Gagge
woah, people still print code? I mean, outside of snippets for article or blog posts, I dont think ive actually printed actual source code in over a decade.
Neil N
FFS get an editor with word wrap on its output. you don't hit return for the end of every line in a word processor.
Pete Kirkham
@Neil N - some of my professors still require that I print out assignments.
Jason Baker
Printing is still useful sometimes, and while it can improve readability to have longer lines, it can really cut it when it doesn't all fit on my monitor.
David Thornley
I find reading code is much easier on paper than a screen. Also, I tend to work with multiple files open side by side, and it works much better when the lines are kept short.
Herms
I agree with Herms. I commonly have 2 files open, side by side, and even on a widescreen monitor, that places a limitation on file length. Plus, most of colleagues don't currently have widescreen monitors.
Steve Melnikoff
Good IDE should have intelligent word-wrap too...
Mark
I always have an 80-character line in my IDE because I find ridiculously long lines hard to read and they prevent me from putting two files on screen side by side. However, I treat it as a guideline, not a hard limit.
dsimcha
@dsimcha: Different people disagree about what is "ridiculously long", but then there are many examples where having lots of really long lines of code in a row actually improves readability if those lines align vertically; then you can scan downwards and compare how each line differs from the previous. I'm not saying every line of code should be 300 chars long, but 80? I'm unique among my colleagues in not using a maximized window and I still have 120 chars visible in the text editor which takes up about 2/3 of the width of my IDE.
Mr. Shiny and New
+13  A: 

I used to seperate all my line numbers by 10, starting each logically seperate peice of code at intervals of 100 or 1000 i.e.

10 Print "Hello"
20 Gosub 100
30 'Peeks and Pokes

For obvious reasons, I no longer code like this.

Neil N
What interval are you using now?
alex
Isn't that the answer to a different question? Wait... What was it?...
xtofl
Wouldn't it be more fun to only use irrational (or possibly transcendental) numbers?
Jon Skeet
This is still a good idea because it allows you room to add new lines of code in between the existing lines, if you want to add new features for example. Languages like C++ are missing this new feature which means that it is harder to add new features to the code
1800 INFORMATION
...but what to do in INTERCAL?
Pontus Gagge
Just go somewhere where you still have some free line numbers and do a COME FROM?
1800 INFORMATION
+2  A: 

As far as variable declaration, the best place to declare them is just before they are used. If your function/procedure is so large that there are tons of variables declared at the top, consider refactoring the function into multiple, smaller ones.

As far as Hungarian Notation goes, the same answer applies. If the function is so large that you can't quickly spot the definition of the variable (even though it should be declared just before being used), then consider refactoring.

In most cases, a well written, well refactored function should make variable declaration and data type obvious with a quick glance at the code page.

HardCode
+17  A: 

Accidental assignment protection:

Putting the lvalue on the right hand side is not needed in some newer languages like C#.

In C# the following won't compile:

if (variable = 0)

So in C# there is no need to do:

if (0 == variable)

This practice is very common in C/C++ programs to avoid accidental assignments that were meant to be comparisons.


Multiple return points:

Disallowing multiple return points was enforced mainly because you don't want to forget to delete your variables.

Instead if you just use RAII you don't need to worry about it.

Disclaimer: There are still good reasons to minimize multiple return points, and sometimes it is useful to have only one.


Header files

In most modern languages, you do not separate your code into declaration and definition.


C++ defines for multiple header file includes

In C++ you used to often do:

#ifdef _MYFILE_H_
#define _MYFILE_H_

//code here

#endif

This sometimes would lead to something like the following though:

#ifdef _MYFILE_H_
#define _WRONGNAME_H_

//code here

#endif

A better way to do this if your compiler supports it:

#pragma once


C variable declarations

With C you had to declare all variables at the top of your block of code. Even later versions of C didn't require this though, but people still do it.


Hungarian notation: (Read, contains some unique info)

Hungarian notation can still be good. But I don't mean that kind of hungarian notation.

Before it was very important in C to have things like:

int iX = 5;
char szX[1024];
strcpy(szX, "5");

Because you could have completely type unsafe functions like:

printf("%i", iX);

Now if I would have called the string x, my program would have crashed.

Of course the fix to this is to use only typesafe functions. So as long as you do that you don't need hungarian notation in this sense.

But still it is a good idea as discussed by Joel in his sense.

Brian R. Bondy
+1, all those old C++ fogies and thier if (0 == variable) in C# are driving me nuts, lol
Neil N
Nice list, thanks.
Liran Orevi
+1 with one small caveat: Having a single point of return makes Eclipse refactoring work better (i.e. extract/inline method).
starblue
@starblue: good point, I added a disclaimer to that one. I felt it needed one anyway when I was originally writing this answer.
Brian R. Bondy
I agree that hungarian notation is outdated, as long as there is a standard within the coding team for variable names, to make them readable and descriptive, and following some type of convention.
pearcewg
`if (0 == variable)` is incorrect (as opposed to just awkward) because it suggests that the value `0` is the most important comparand, when in reality it's `variable` that controls the block.
280Z28
Incorrect in your sense of preference. Correct in someone else's sense that may try to avoid a common bug in C++.
Brian R. Bondy
+1  A: 

Manual ref counting of a pointer is an old practice that drives me absolutely crazy. I fix around 1-2 bugs a month because someone tried to be smart and manually ref count a pointer. Just use a smart pointer. It will save you time.

JaredPar
+3  A: 

Aligning in columns (e.g. variables in declarations or = in assignments).

It is a pain to maintain manually, automatic renaming will mess it up anyway, some lines get very long with things belonging together wide apart so you struggle to see the relation.

starblue
Agreed. Takes too long. If the value is really long, I prefer doing "variable, line-break, tab, value". Especially since I use a variable-width font of my own making.
adam0101
+3  A: 

Like it's been said before, don't try to adapt one language's idioms to another. This is especially true in drastically different languages, such as going from C++ to Python. Also (this might just be a question of personal style), I used to declare a variable, then assign it a value later. I find it much faster and space-efficient to just declare and define it at the same time.

BaconSoap