views:

4469

answers:

48

A recent post about the 'with' statement in Delphi - which in practice I never use because it trades clarity and ease of debugging for superficially 'cleaner' looking code got me thinking; what other language features, in any language, do you think should never be touched? - or at least avoided where at all possible?

The classic example of this would be the COBOL ALTER statement, which dynamically rewrites the executing code to change the destination of a GOTO. Use of ALTER was just about a sackable offense in every COBOL shop I ever worked in.

My supposition would be that as language design is better understood nowadays there may be fewer of these 'features' coming through - but is that true of the newer more exotic paradigms such as the functional programming languages?

+16  A: 

The only thing that comes to mind are GOTO statements :)

Vincent Van Den Berghe
While I agree with the spirit of this, the problem I've run across when programmers follow this rule without really understanding why they should avoid gotos is that they wind up creating bizarre constructs like: do { ... break; ... } while (false); which technically follow the rule, but [continued]
Ferruccio
[continued] lets face it, they are still gotos masked as a structure. In those cases, I would prefer to see gotos. The intent of the code is clearer.
Ferruccio
I like to use goto in order to have a single point of return from C functions that need to do some clean-up before returning, rather than repeating the clean-up before each return statement.
divideandconquer.se
try/catch is basically just a fancy goto, so if coding in C, goto can be OK for that purpose
Slartibartfast
two votes for @divideandconquer.se
kenny
@Ferrucio, divideandconquer.se: Full ACK
bene
Also, I've used goto when I wanted to break out of nested loops cleanly.
Hans Sjunnesson
Gotos are also important if you are coding up a state machine. For example: lexical analyzers.
T.E.D.
I did use it 3 or 4 times in my development life, and it was quite a good feature when you need it and when you do it right.
dr. evil
Gotos still have merit in the loop-and-a-half case. It's clearer than using conditionals to exit the loop.
Loren Pechtel
Definitely not a *never* feature. Nested loops are a prime example where the alternative is worse. Assuming a language without multilevel break.
Draemon
Brad Gilbert
@divideandconquer.se In Java that could be simply avoided by using try-finally block.
Malcolm
You mean like using an exception for flow control? Wouldn't that be worse than using goto?
Patrick Huizinga
There is a paper called "Goto considered harmful", and another paper in response to it, titled "Goto considered harmful, considered harmful". Which I understand basically says never again should an element of a language be banned.
barlop
+29  A: 

You should always use Option Explicit in Visual Basic (i.e.: you should never use implicit variables).

Stewart Johnson
I think you should also be using Option Strict also. It takes a little more typing to cast when needed, but can prevent a lot of bugs.
Kibbee
I believe this has been a recommendation for VB-ers since... VB4??
chakrit
@Kibbee: in general yes but consider MS Office interop code as a counterexample.
Konrad Rudolph
I don't ever envision a program to stay as is if Option Explicit and Option Strict are not set to On.I even switch Option Infer to On to forget about types the "clean way"
controlbreak
If it's a small program, then you can keep it short and sweet without declaring variables. So for such situations, it's good that VB gives the option to not declare them. In a large program then it's not a good idea because can lead to some bugs and thus increase debugging time somewhat.
barlop
+20  A: 

I think no language feature should never be used. It's just a matter of knowing when and how to apply each feature. Of course there are features you almost never would want to use, but can still have their place in certain contexts.

Well, as every rule has to have at least one exception, here's one, PHP related:

  • Having register_globals set to on should never happen :-)
Vinko Vrsalovic
Whilst I think you're probably right in that nearly everything does have a place, I *never* saw a case for ALTER. It really was totally toxic and to this day the only example of dynamically rewritable compiled code I know.
Cruachan
register_globals should be an offense punishable by state laws...
Michael Stum
Oh, come on guys, there are so many things worse than register_global. In fact, I'm maintaining one huge (200k+ loc) application that requires it and it's really ok. As long as the programmer was smart enough to declare used variables and uses finite-state machine approach for everything.
Milan Babuškov
Yes, you're spot on Milan. It's really okay if the programmer is smart enough to create a convoluted approach that would not be necessary with the feature turned off.
Vinko Vrsalovic
Unfortuantely, PHP has quite a raft of features You Should Never Use; register_globals is but one. However, embedded variables and dynamic variables would also be high on the list.
staticsan
I think magic_quotes_gpc is a million times more evil than register_globals. At least you can code around register_globals, but magic quotes are right there staring you in the face, laughing at you as they corrupt all your input.
Ant P.
+68  A: 

In Java, calling a static method via a reference. My favourite example:

Thread t = new Thread(someRunnable);
t.start();
t.sleep(1000); // This doesn't do what it looks like...

It makes the current thread sleep, not the newly created one. Thread.sleep is a static method and only ever affects the calling thread - but this snippet makes it look likes it's telling a different thread to sleep.

Jon Skeet
It certainly does what it looks like, once you know what it does :-)
Vinko Vrsalovic
By the way, that's a bug, not a feature! (in the spec)
Vinko Vrsalovic
I've only worked with Java Threading a few times...what does that code do (as I know what it looks like it does)?
Thomas Owens
It makes the *current* thread sleep, not the newly created one. Thread.sleep is a static method and only ever affects the calling thread - but this snippet makes it *look* likes it's telling a different thread to sleep.
Jon Skeet
Well, you could say this about any OO language. This is just a bad name for the method. Not very familiar wtih Java, but I think you may want to call static methods by reference when sub-classed objects (with overridden static methods) are passed around.
smo
Jon, this answer would be lots better if you were to move your explanation into the body. Right now it's more of a puzzle than an answer.
Chris Noe
@Chris: Will edit. @smo: C# doesn't have this problem. You'd have to call "Thread.Sleep()" which makes it obvious that you can't call it "on" a particular thread. There's no benefit in calling static methods via references - it just confuses things.
Jon Skeet
@Chris: Ooh, Simucal did the editing for me. Hurrah :)
Jon Skeet
So, `Thread.sleep()` should actually not be implemented as `static`. What would be better?
Svante
Doesn't the IDE alert you to this stuff? I'm fairly sure that Eclipse throws a warning.
Uri
@Uri: Yes, Eclipse gives a warning. I was the one who originally put the feature request in :) (It may well have been in progress anyway, admittedly.)
Jon Skeet
@Harleqin: It should be a static method (what would it be an instance method on?) but would perhaps be better has: "sleepCurrentThread". Then again, there are similar things around elsewhere, and it would get very tiresome. When you are forced to use it as Thread.sleep, it's reasonably clear.
Jon Skeet
It's a static so you shouldn't do that anyway, in VB.NET IDE will warn you that you are trying to call a static in a wrong way, It's not a bug, just you doing something wrong.
dr. evil
@Slough: The bug is that the language *allows* you to do something that you shouldn't do. (It's good that VB.NET optionally warns you now. It didn't do so originally. It's a hard error in C#, which is preferable IMO.)
Jon Skeet
@smo - you can't override a static method
Draemon
Well, that's a minor thing, just t.sleep(100) being an unclear way of writing Thread.sleep(..) . Because with t.sleep some people might assume that sleep is an instance method. There is no difference in the execution of the code. You are almost just making a point of aesthetics. To the point that if there was a comment with that line , so it wasn't misunderstood, then it wouldn't matter quite as much.
barlop
Anyhow.. practically, if you're using a method, then just as you should know what the method does, you should know as part of that, whether it's static or instance..and if you know java syntax, then you wouldn't assume just based on the notation of the call. But I agree that a static method should be called as classidentifier.method, and not as obj.staticmethod
barlop
@barlop: If you think readability is a minor issue, I think we'll have to agree to disagree. There's no reason for Java to allow this, and it shouldn't. This is a "feature" you should never use, hence the answer to this question.
Jon Skeet
I agree with you
barlop
+3  A: 

In C#, extern aliases. These allow you to cope with the situation where you have two different assemblies both containing a type with the same name, including namespace, and you want to refer to a particular one of them. Avoid wherever possible.

EDIT: Just to be clear, this isn't a fault in the language. The feature allows you to get out of otherwise intractable situations. It's just a feature you don't want to have to use.

Jon Skeet
+3  A: 

I agree with Vinko Vrsalovic. And my exception is the Delphi With statement. The only time I used it was to create a test set for the delphi frontend of my metrics tool.

The with statement has a very big "I want to shoot myself in the foot" factor. Which is fine if you are the only developer, but in a team it can be very nasty.

Maybe there should be a compiler option that gives warnings if with statements are encountered ;-).

Gamecat
+20  A: 

You should never do using namespace std; in a header file in global scope in C++.

And you should be shocked if you see using namespace std; in global scope. Never do it, it throws away the names scope separation gained using namespaces.

Johannes Schaub - litb
I'd go even farther: never write "using namespace X" in a header file, for any X. +1!
Drew Hall
...at global scope
Dustin Getz
Dustin, fix it :)
Johannes Schaub - litb
The first part is OK, the second really isn't. In many code files it's completely fine to globally import the `std` namespace. Still, I tend not to do it. But that's quite different from “you shold be shocked to see …”.
Konrad Rudolph
there may be cases where it is ok, which can be analyzed after you've been shocked and took a coffee - hehe. but generally i think you should avoid doing so. usually you have namespaces, and doing "using namespace std;" *within* that namespace is ok IMHO. but doing it at the :: level isn't, IMHO :)
Johannes Schaub - litb
I’ve had to wrangle with libraries that do this; it’s pretty miserable.
A: 

Multiple Inheritance in C++, of course. There's a good reason it's been dropped in C#/java.

(Though "every rule does has exceptions, including this one").

ripper234
Having multiple inheritance also simplifies a lot of other problems. The problem is not with MI, but with programmers who try to used it without RTFM-ing first.
Milan Babuškov
@Milan: That could be said of any of the "forbidden" language features mentioned here. If you know how and when to use it appropriately then you won't have problems. Most of these examples lead to problems later, when another developer tries to maintain your code.
Bill the Lizard
I dissagree. MI can be very useful, and in some cases essential (COM)
Nemanja Trifunovic
MI can be critical, especially in a language that doesn't officially support interfaces.
Uri
I don't know aoout C#, but they didn't drop it from java--they just renamed it "implements". -1.
Drew Hall
@Drew: It works a lot differently in Java. In C++ implementation can be inherited from multiple sources, in Java only an interface can be. (I'm sure you probably know this, but others might be wondering.)
Bill the Lizard
@Bill: A valid point, but in my experience MI usage in C++ tends to be with ABCs, effectively interfaces themselves. But you're right that the language-level enforcement is a difference.
Drew Hall
+1  A: 

In C#, you should (almost) never use [assembly: ComVisible(true)] in your AssemblyInfo.cs. It is far too easy to generate wads of COM coclasses and interfaces you're not even aware of. After all, FxCop itself considers it bad practice and recommends specyfing the [ComVisible] attribute on specific classes and interfaces explicitly.

petr k.
+15  A: 

You should never write Perl code without:

use warnings;
use strict;

Also, you should never use a JAPH in production code. Those are strictly for use in .signature files and golf. Their misuse elsewhere is, IMHO, one of the main reasons for Perl's reputation as a "write-only" language.

Sherm Pendley
+12  A: 

Global Variables.

danimajo
Yes. Definitely be prepared to defend the decision to use global data at a code review.
Bill the Lizard
Globals have their merits in storing configuration info and sometimes resource lists.
Loren Pechtel
But you would be better served using a static class in an OO language.
Ed Swangren
I used to not think globals were so bad. But as I've worked on complicated systems (that I didn't write) I've come to really dislike them.
Slapout
A static class is just a global in disguise. It has all the same problems and advantages.
Jules
Globals should be avoided whenever possible but you cant say you will NEVER need them.
Tanmoy
How is a static class any different to a global variable?? It's just OO's version of a global variable :(
Jacob Stanley
+3  A: 

It's not a language feature, but a compiler option that you should never use.

javac -nowarn myApp.java
Bill the Lizard
+1  A: 

I cannot find a good use for the Shadows keyword in VB .NET.

Shadows is the same as declaring a method with no modifiers, which VB's compiler doesn't otherwise allow. It creates a new name, effectively blocking all all of the overloads with that name in the inheritance hierarchy. I don't think there is a C# equivalent - for example, C#'s new is not equivalent, as it targets the hidebysig IL construct, like VB's Overloads.

If you only have one overload when you use Shadows, the behaviour matches Overloads. But maintenance developers will find out that new overloads are also hidden!

What makes this worse is that Shadows is the default. I think this may be because of VB's way of resolving an overloaded method. Unlike C#, the VB compiler does a depth-first analysis of the entire inheritance chain. Having Shadows as the default prevents base type changes modifying the behaviour of your existing code. I suppose this is a necessary evil in a world where you may not be able to control base type behaviour.

RoadWarrior
The reason why it's needed is when you don't own the base class - if author of said base class adds a new member, you do not want your class which happens to contain a member with the same name for a long time to suddenly stop compiling, or to compile but silently override it. It's the default for the same reason.
Pavel Minaev
Yup, that's exactly what my last sentence says :-)
RoadWarrior
+6  A: 

In C# there are a number of caveats, e.g.

Never lock on a value type - the lock keyword prevents you from doing this, but if you call Monitor.Enter() directly, you'll be locking on a boxed instance of the value. Fortunately when you try to call Monitor.Exit() on a boxed value, you'll get an exception.

Never lock on a literal string. In C# literal strings are interned for the entire application. Thus local strings, strings in different AppDomains etc. are all shared. This could lead to weird deadlock issues.

Be very careful with finalizers and try to avoid them if possible. One problem: an unhandled exception in a finalizer will take down the entire process.

Brian Rasmussen
continued: never lock on anything that is a System.Type, never lock on (this).
Jimmy
@Jimmy lock on (this) is useful sometimes.@Brian about finalizers, when you are working with unmanaged resources, you must implement a finalizers.But every time you do, you ought to implement IDisposable and call GC.SuppressFinalize(this);Finalizers are a good backup in case the programmer forgets to free the resources.
dig
@dig: why would you ever lock (this) when you could create a private object member and lock on that? when you do "lock(this)" then any client code creating an instance of your class could deadlock when they lock(instance_of_your_class).
Jimmy
@Jimmy If you are implementing your own container for example. lock(this) is good enough.
dig
+12  A: 

Never use the C / C++ language feature of chaining code in a switch statement by appending code to a previous switch case:

OK -

switch (x) {
  case 1:
  case 2:
  case 3:
    ...
    break;
  case 4:
    ...
    break;

  }

Evil -

switch (x) {
  case 1:
  case 2:
  case 3:
    ...
  case 4:
    ...  // Add to the 1,2,3 case here
    break;

  }

It's too easy for someone to edit the behaviour of case 4 without noticing that it'll also affect cases 1-3.

Mike
That looks temptingly clever on first glance, but I can see that it would turn into a maintenance hassle.
Bill the Lizard
You don't like Duff's device?
divideandconquer.se
I see uses for falling between cases...
Thomas Owens
The way you've written it here makes it look worse than it is. I'd usually write:case 1: case 2: case 3: case 4: doStuff(); break;
Pramod
With all the cases on a single line, I mean.
Pramod
I agree with Thomas Owens. There are some situations when this is useful. However, it's good practice to add a comment noting the lack of a break.
Jay Conrod
@Pramod: He's doing stuff in case 3, not breaking, then adding to it in case 4.
Bill the Lizard
I might have uses for this construct, actually, but I always document the fallthrough.
PhiLho
Sometimes it is very useful but all intentional fall through should be documented.
some
I started in the VB world and you a matched case automatically breaks without the keyword. When I switched to C# I thought being able to match mutiple cases was a very useful feature... why is it bad, or am I misunderstanding the issue?
Richard B
BTW... most of these answers do not bother to specify why they are declaring the language "feature" as bad or dangerous.. I know why on many of these, but others I don't and I thought that was the point of this site, to learn!
Richard B
The problem is not matching multiple cases, it's implementing code, then continuing on with more cases without a break. This cannot be distinguished from the programmer forgetting the break statement. C# addresses this problem by requiring a break after code within a set of case statements.
Mike
I disagree. This is a situationally useful feature.
korona
Duff's device is awesome. But I think any usage of the above example *must* be documented clearly, it's too easy to overlook it.
For what it's worth, some compilers provide syntax to officially annotate these "fall-through" cases. For an example, see the description of __falltrhough here: http://msdn.microsoft.com/en-us/library/ms235402(VS.80).aspx)
Reuben
In Perl 6 the default is to not fall through, you have to do that explicitly.
Brad Gilbert
A: 

C interprets nonzero values to signify true and zero values to signify false. You shouldn't have to rely on this feature any more.

Edit: Number of people are not buying my disliking nonzero-as-true. What about this?

if (status = UNDER_ATTACK) {
    launch_nuclear_missiles();
}

or this?

if(x & 2 == 1)
{
    launch_nuclear_missiles();
}
eed3si9n
What's wrong with that?
divideandconquer.se
Because int is for integers and not for true/false value. Using non-zero as a test is a legacy hack from assembly jz (jump if zero).
eed3si9n
Nope, sorry, don't buy it.
Leonardo Herrera
Using non-zero as a test in C is unrelated to using jz in asm. The smallest convenient data type in C was the char, and using 0 for false is just good sense. And it's equally sensible that if it's not false then it's true.
Gerald
In the first example you assign the value of UNDER_ATTACK to status, and if that is non-zero you launch the missiles. Shouldn't it be "status == UNDER_ATTACK" ?
some
As long as you understand that the numeric types are also how Booleans are implemented and that C really is just shorthand for assembly, you're OK. I'd say that = vs == nonsense in a conditional is a much more egregious shortcoming of C.
Barry Brown
@some, it's an intentional typo borrowed from "syntax gotcha" question.
eed3si9n
The crux of the issue is that this is how C was designed and you can't simply NOT use ints as Booleans. There is no adequate built-in substitute. You could do something with typedef and #define, but it would be at best a preprocessor kludge.
Barry Brown
Your first examples seems to be an argument against using assignments in conditional, not against integers in conditionals. For the second example, I don't remember the operator precedence, but either way, it evaluates to false, so you won't accidentally launch anything.
Rob Kennedy
+36  A: 

In C:

  • Taking advantage of the commutative property of array indexing to swap the array name and the index:

    int array[5];
    3[array] = 0;
    
  • Using the preprocessor to try to turn C into another language:

    #define IF if (
    #define BEGIN {
    
  • The register keyword, which at best is likely to be ignored, at worst it will make performance worse, and in either case you lose the ability to take the address of your variable.

  • The auto keyword, simply no need to use this.

  • More of a library issue than a language feature but the gets() function should never be used.

Robert Gamble
I didn't even know array indexing was commutative in C. Why is it possible anyway? Is there any use of it?
utku_karatas
a[b] is shorthand for *(a+b). As a consequence, a[b] is equivalent to *(a+b) is equivalent to *(b+a) is equivalent to b[a].
Adam Rosenfield
I was going into this question thinking there was no such thing as a language feature *never* to use. I stand corrected. Good answer.
T.E.D.
1 - does anyone actually do this? 2 - ditto 3 - Not true for some embedded compilers
Draemon
Brad Gilbert
Also, remember that a quoted string is an array of `char`, so `4["abcdef"]` is `'e'`.
David Thornley
+4  A: 

I find Python's backtick repr quite nasty (and especially since there are better ways to do it.)

`some_var` == repr(some_var)     # yikes Batman (gone in 3.0 - thanks Greg)

And then there is this implicit string concatenation thing:

>>> 'a''b''c'     # holy moly Robin
'abc'
Ali A
The backtick syntax is gone in Python 3.0: http://docs.python.org/dev/3.0/whatsnew/3.0.html
Greg Hewgill
yeah that implicit string concatenation baffles me too. who the heck needs that? It's way less readable than a '+'
Triptych
The implicit string catenation thing makes it a little easier to makemulti line strings. Not much easier, not so much easier that i'd recommend it over regular triple quotes, but thats why it's there, (i think...)
TokenMacGuy
I dislike backticks in general. They're based on a misunderstanding: they looked sort of like left quotes on some old systems, but they're actually acute accents, and are generally displayed as such in modern fonts. They're also annoying to type on some keyboard layouts. Even in shell scripts, I much prefer $(this) to `this`.
LaC
A: 

C++: protected inheritance

Itay
What's wrong with C++ protected inheritance. In fact, you could find plenty of examples of it in the Stroustrup's book
Nemanja Trifunovic
Sometimes do...while loops are just the thing you need. Why do you warn against them?
Bill the Lizard
What Biil said - sometimes a guaranteed execution prior to test in a loop is _exactly_ what is required. What is the danger?
Ken Gentle
do while is a really useful loop. It is just not needed that often.
Leonardo Herrera
Drew Hall
i agree with the other commenters. -1
Johannes Schaub - litb
C# out parameters are a necessity when using TryParse, awkward though they be.
Kyralessa
do while loops are just fine in any language, so long as you always encode a break-out condition that can never fail
Cruachan
A: 

In PHP, never use exec or even passthru. Of course, most languages have some sort of contemporary to these functions.

patricksweeney
I'd disagree. However, I'd never write an exec command in code I wasn't in control of - like a public release etc.
Josh Smeaton
+7  A: 

Another PHP one: magic quotes. It's a terrible idea, and you still see lots of web apps that use it. Any time you type " and it turns into \", someone's probably got magic quotes turned on.

JW
+5  A: 

I won't say you should never use it (I am not dogmatic) but I try hard not to use automatic conversion of some values to booleans (NULL as false in C, nil as false in Lua, undefined or null as false in JavaScript, etc.).
Ie. I prefer to do an explicit comparison against the value and reserve tests like if (foo) to pure booleans.
It results in slightly more verbose code, but might avoid surprises...

In the same spirit, even though I would indulge in an occasional while (*p++ = *q++), which is at least a well known pattern, I would avoid constructs like if (a = b) even if it has the intended behavior...

PhiLho
In the rare if(a = b) cases, I prefer to write it as if((a = b) != 0) (or replace 0 with false or NULL, depending on the types of a and b).
Adam Rosenfield
some
@some: that means your variable is probably a bit too flexible. Dynamic typing is good, but shouldn't be abused... :-) Beside, in JS, == returns true for both undefined and null (you use === for exact comparison). And you can do something like PHP's isset function.
PhiLho
@PhilHo: your just reinforced the point; == returns true between 0, false, [], and "" but not null or undefined or NaN (which isn't even a keyword, you can easily do "var undefined = true;")
Jimmy
+12  A: 

Never omit curly braces when the target statement is on the next line

OK:

if(foo) potato

OK:

if(foo) {
  potato
}

NEVER:

if(foo)
  potato

when there's other stuff going on, it's too easy to miss that potato depends on foo.

Personally I *never* (well, hardly ever) use the first construct. Writing all your if statements with brackets may look anal, but I've spent more hours debugging other people code where hanging ifs have caused subtle errors than I care to remember.
Cruachan
Of course if you put the opening brace on the next line, it's really easy to see visually.
smo
With the years I've learned to use braces everywhere.Except in Perl. Those postfix conditionals are a guilty pleasure.
Leonardo Herrera
I agree with Cruachan here. The first construct is *evil* and the later two are OK (including the third)
Nemanja Trifunovic
Curly brace fail.
moffdub
I think you've got it backwards, the first two options are bad, the third option is okay. As long as you have a blank line before and after there's not much chance of misunderstanding the intent. And I've never understood the rationale behind starting your curly brace on the same line as the if.
Gerald
The "to brace or not to brace" argument is heavily dependant on how well the code is indented.
staticsan
The second option is the only right way IMHO, but I see all three on a daily basis. Nothing gets a flame war started faster than a curly-brace style debate. :)
Bill the Lizard
I'd say that if your code is unreadable or error prone without indentation, it ought to be part of the language (F#, Boo, YAML).
Benjol
lol, talk about disagreement, I find 1 and 3 to be acceptable, but 2 to be evil.
Kevin
It's purely pragmatism. 1 and 3 will generate maintenance errors, 2 won't. All three are arguable on theoretical grounds, but in practice if you don't want to spend hours a couple of years down the line tracing code you use 2.
Cruachan
I like that in Perl you can't even do `if(foo) potato` instead it is `potato if foo`
Brad Gilbert
Python. Why { at all?
mavnn
If you use an IDE that automatically formats your source code (like Eclipse can) 1 and 3 are absolutely equivalent. I never had any problems with option 3 in Java, but I always get confused by it if I work in another language/another editor that does not enforce proper indenting. But in this case, all three options may drive you crazy when the indentation is totally messed up.
Brian Schimmel
@mavnn: Because that way when some guy who's used to {} goes and looks at your code, he can see what's going on more easily.So, readability.
Christian Mann
Dudes, if you learn to read the code, and know what it looks like then they are all EXTREMELY EASY to read, and you'd have to be a complete wolly to misread them!! And important thing is to indent, when multi-line, and you have done. So in all cases it's obvious. And you've done all you can to deter human error in reading it.
barlop
+2  A: 

I don't think there's many cases of when something should truly never be used, especially something so benign as a "with" statement (especially if it relies on non-idempotent expressions with side-effects).

Most of the issues mentioned amount to taste in formatting and syntactic sugar.

The exception may be if a feature is deprecated and replaced with an equivalent due to e.g. security issues. Even then, if you're dealing with an existing code base, it may not be worth it to go back and change to use the new features.

Some low level features that seem like security problems may be needed to communicate with other components of the system in rare cases (e.g., exec, ActiveX controls, inline assembly, p-invoke, etc). If your application doesn't need to do this, then obviously, don't use it, but it's there for those who do, and they should use it carefully. But saying "never" is way too general.

smo
Don't agree about formatting sugar - many of the examples here are of code practices that are known to cause maintenance gotchas, not things that won't work *per se*.
Cruachan
+3  A: 

with in Javascript. It's a scope obfuscator/polluter and performance killer.

porneL
+2  A: 

I can think of very few reasons to use exception specifications in C++:

void func() throw()
{

}

(but of course, there really are no nevers)

Jason Baker
For those of you playing along at home, this is because exception specifications don't do what it seems at first glance that they should. They're enforced at runtime (and require RTTI overhead to check exception types), not compile time, and the default response to an exception that violates the specification is to call std::unexpected(), which by default calls std::terminate(). An empty exception specification might in theory let the compiler make some optimizations... someday.
Derrick Turk
A: 

Bitfields in C. They're not portable, and they can cause concurrency problems (race conditions) when shared between threads.

mseery
Could you elaborate on the concurrency issues you're thinking of? I can see how atomic, "interlocked" operations might not work as normal, but you should still be able to use some other synchronization mechanism to restrict access to them. Performance might be a concern, though...
Reuben
A: 

Variable argument lists (...) unless you are writing some low level system API. In most cases, there is some cohesive intent for these lists so they're better served with a class that can take a range of things and grow its own list if necessary.

Uri
Dramatically depends on the language and features you're talking about. The C var arg feature that walks up the stack? Ooof. The perl slurpy list as a final argument? Hell yes.
Robert P
Or even the C# params argument is decent enough.
Robert P
I was thinking C. Not familiar with C#/perl style
Uri
how do you suggest to use format strings for example (let's say in logger)Implement a function for every possible format?
dig
+5  A: 

Variable variables in PHP.

$foo = 'Hello World!';
$bar = 'foo';

// prints Hello World
echo $$bar;

Makes debugging complicated, especially when they are combined with calling functions by name.

function hello()
{
    return "Hello World!";
}

$foo = 'hello';
$bar = 'foo';

// prints 'Hello World' too
echo $$bar();
Matthewd
Eh. In other languages those would be called pointers or references. No big deal. Some programmers would rather die if their language didn't support calling functions by reference.
Barry Brown
In above example call isn't the essence of the problem. The worst part is $$bar which refers to variable by _name_.
porneL
So $bar is a reference to $foo. $$bar dereferences $bar and points to whatever $foo points to; in this case 'Hello World'. What's the issue?
Barry Brown
Huh, I didn't know PHP had this. I don't see anything wrong with that, function pointers can be extremely useful.
dancavallaro
It's not the same as pointers. PHP's variable variables can only point to other variables that are in scope.
Jules
It's not the same as a pointer, because $bar is a string in its own right, too (at least in PERL, where I'm guilty of using this, but only once ... :P )
drhorrible
I once had a very specific need for this, but everybody I asked said it was not possible >_<. I ended up having to rewrite my code to be 2-3 times longer... I wish i'd known about these
Mala
ARGHMYEYES! The dollar signs... the awful double dollar signs...
deworde
+3  A: 

Never rely on the compiler to initialize a variable. For example, never assume that integers are initialized to 0 or pointers to null. It may work fine in the current compiler you are using but could work differently when you port your code to another compiler. And, when initialization doesn't work as you expect, it will likely create a subtle and difficult to detect bug.

mxg
File-level static variables (in C) are guaranteed by the standard to be initialized to 0.
JesperE
This is C specific. Member variables in (say) java are always initialised to null,0,whatever.
Draemon
In some languages the standard clearly defines auto-initialized values for new variables.
Tadeusz A. Kadłubowski
A: 

Personally in Java I do not like do while loops, I seem to be able to use While and For loops just fine, but I wouldn't say you should NEVER use them.

ParseTheData
They're seldom used, but I wouldn't recommend against them. Sometimes they're exactly what you need. For example, any time you want to guarantee that your loop body executes at least once.
Bill the Lizard
A: 

All I can add is: try to avoid platform specific APIs (Windows programmers generally don't think much about it, rather Windows is meant for this purpose). Portability is one thing you should keep in mind (as far as you can).

Next thing I can see is scalability. Make sure you don't rely on hard and fast numbers and try to keep your design flexible and agile.

Then make sure your code is understandable. Avoid magic numbers, proper documentation and naming are essential.

FL4SOF
Platform specific APIs is not something that should never be used. They are something that *should* be used, particularly if you're writing code for use on only one platform. Nothing wrong with using C#, either.
Brian
+1  A: 
Rafael Romão
This can actually be useful to add a setter in a derived class on a property with only a getter in a base class. But I agree it must be used with care.
Trillian
A: 

In VB.NET, I avoid using Parse like Decimal.Parse.

I use TryParse instead.

Nakul Chaudhary
And what do you if the Parse failed? Raise your own exception?
dig
A: 

Don't use any of the new C# 4.0 features... it's like coding with "option explicit" turned off in VB. :) I joke, but seriously, some of these new features scare the crap out of me from a maintenance point of view.

Jon Tackabury
+1  A: 

Yup. The With statement is a throwback to Pascal, where it wasn't so harmful. It should have been removed from Delphi or reworked. Personally I don't agree with "with" statements (Pascal or Vb) they're sugar are are often misused e.g.

  • You find yourself glancing (or worse paging) up more than once trying to figure out which object you're "With"
  • You find a nested With (don't get me started).
  • You find a block of old well maintained code, 20 lines long in a with block and - wait for it - the "with" object is null and is not used by any of the code (saw this about 2 weeks ago and laughed out loud - it was that or weep)

Other than "I'm not with with"

  • Option Strict and Option Explicit MUST ALWAYS BE ON in Vb (I don't care if you can roll feature X in 30 minutes because it relies on late bindings where as it'll take a week if you've to write and implement a heap of interfaces because SWITCH THEM OFF AND YOU WILL LOOSE A FINGER)
  • Don't Dim x as new Y in Vb6 (actually, don't use any VB6 feature if you can get away with it)
  • C/C++/VB: Don't use Static variables in procedures
  • C++ Don't use old ansi string handling LEARN THE STL

I known there's more rattling around in the back of the ould brain, I'll update this as I think of them

Binary Worrier
Perl6: given($obj){ .method() }# $_ = $obj; $_.method()
Brad Gilbert
A: 

JavaScript one: never prototype against object.

annakata
A: 

In Java, it is possible to use generic types without to inform the generic parameters:


public class MyList<T> {
//...
}

public class Main {
    public static void main(String[] args) {
        MyList<String> a = new MyList<String>(); //OK
        MyList b = new MyList(); //OK, but should not
    }
}
Rafael Romão
While mixing typed and untyped generic objects is dangerous, it's a) no problem for the compiler because the type information gets erased either way, and b) sometimes necessary to convert from one type to a superclass.
Stroboskop
+12  A: 

SELECT *

It may be fine for ad-hoc queries, but should never be used in actual code. Always give a list of the columns you want in the order you want them in.

The Weak Reason: It's wasteful, as you almost certainly don't need all the columns.

The Strong Reason: Because you haven't specified the columns you want or the order you want them in, if anyone changes the natural column order or inserts a new column between 2 others, the code that extracts the information from the table will now be pointing to the wrong fields.

Valerion
What are your reasons for this?
ammoQ
Because you generally don't want ALL the data in the table. Returning more than you need wastes time and bandwidth. Plus if new columns are added you might not be able to cope with them properly. Plus you should always use a column-list so the column ordering in the DB becomes a non-issue.
Valerion
it would be good if you add this comment as a part of the reply
Gabriel Sosa
Unless you are writing a DB management tool :)
dig
A: 

All forms of popular non-explicit lazy-up-the-stack error handling. People have trouble seeing the aftermath of their use is no different than the shunned GOTO command. Proper coverage is impossible to verify, perfect way to leak all manner of resources (even in garbage collected environments) and contrary to wildly popular opinion stack traces or low level messages simply passed up are ususally chunk full of nonsense which are not in any way useful to most developers let alone end users.

A: 

Never use autoboxing introduced in Java 1.5.

Integer i = getNumber(); // assume this method returns null
int j = i; // boink

There's really no good use for autoboxing unless you don't understand or don't care about the difference between objects and primitives - and then you better stay away from it anyway.

Stroboskop
Autoboxing is dangerous, but can have its uses, provided you know what it is you're doing. The mistake is in not seeing the cost of the hidden conversion. I far prefer Scala's approach, but as always that's not what the day job uses.
Marcus Downing
A: 

In Python, you should avoid running a bunch of methods on one line. I still do it, though.

"  hello\n\n".upper().replace('o','0').lstrip().rstrip()[::-1]
sli
A: 

'extern' keyword in C.

C's linker doesn't check if the functions (or variables) match. The function is simply called or the variable used.

A contrived example,

// file1.c written by programmer A.
extern int function_b( void );
int num;
num = function_b();

// file2.c written by programmer B with no knowledge of programmer A.
static int global_b;
int function_b( void ) { return global_b; }

Now suppose programmer B changes function_b() to take a parameter. Or return an uint64_t instead of an int.

// contrived new file2.c
static uint64_t global_b;
uint64_t function_b( int caller ) 
{ 
    LOG_CALLER(caller);
    return global_b; 
}

We now have a corrupted stack and/or corrupted memory because programmer A's call to function_b() doesn't know function_b() has changed. The C compiler/linker doesn't check.

I see externs in cases where programmers take shortcuts. Instead of using the proper #include file, it's simpler to slap an extern into the code and hope for the best.

David Poole
Don't you need "extern" if there is a global variable in an application that is shared between files? Although it's not good practice in general, there are occasions where it is important. (esp. on embedded systems where the global variable represents a resource)
Jason S
We'd still have the trap of the variable changing and the 'extern' holder not knowing it. Putting the 'extern' into a header file assiduously shared between the two source files is one solution. Using an accessor function is safer, though.
David Poole
+3  A: 

eval in the vast majority of cases in any language that has it (MATLAB, Javascript, etc). There are exceptions like parsing JSON if the input has been properly checked for validity.

It usually presents a security risk and there are often other ways to solve the desired problem. In MATLAB and Javascript there are facilities to get dynamic field names, e.g. if I have a structure S and it has a member somefield, and I have a variable containing the string of a field name v = 'somefield', then in MATLAB I can access this field with S.(v) and in Javascript I can access this field with S[v]. No need to call eval() in either place.

Jason S
eval/exec can be very useful when you are trying to create code generation.I've used it in python recently in order to create wrapper functions dynamically from metadata.
dig
+1  A: 

VB.NET has several "features" to maintain backward compatibility with older VB 6 code. Instead of using these "features" you should probably write your code to do things the .NET way.

Slapout
+6  A: 

In Python, multiple wild card imports:

from songsmith import *
from web import *

@publish
def create_bad_song(uri):
    return add_soulless_backing(get(uri))

It makes it difficult to find the source of a name when reading the code. Did get come from songsmith or web?

It is much better to say something like this:

from songsmith import add_soulless_backing
import web

@web.publish
def create_bad_song(uri):
    return add_soulless_backing(web.get(uri))
Will Harris
Never! If they got rid of the * my life would be much less mysterious.
drozzy
A: 

SQL: INSERT statement without a column list, i.e.

INSERT INTO foobar VALUES (foo, bar)

Immediately breaks when another column is added to the table.

Exception: In PL/SQL, a record variable can be declared by table%rowtype; it doesn't hurt to write something like

DECLARE
  v_foobar foobar%rowtype;
BEGIN
  v_foobar.foo := 'foo';
  v_foobar.bar := 'bar';

  INSERT INTO foobar VALUES v_foobar;
END;
ammoQ
A: 

The using keyword of C#.

Intead of destroying the object with a command, you have to follow the braces to find where it ceases existing. Does not decrease much the ammount of code you write, but decrease readbility a lot.

kurast
It's called scope. -1.
Aaronaught