+14  A: 

Large classes with very long methods.

Fix: break up responsibilities to different classes, refactor to smaller methods. Do all this with good unit tests around the code.

Oded
This is definitely true, but there are different opions about what makes a "large class". For example, I frequently prefer VERY large partial classes (split over separate files) with many private inner classes to do the actual work while the outer class exposes a simple public interface. This increases the degree of information hiding/encapsulation and prevents namespace pollution.
Robert Fraser
Classes that are large because they contain several inner classes are indeed not necessarily a problem (because they're just as well structured as several seperate classes would be). Classes that are just large by themselves, partial or not, on the other hand ...
Joren
This isn't a C# code smell. It happens in many other languages too.
Kelly French
@Robert - The problem I see with private inner classes is that they are difficult to unit test.
Pedro
A: 

I recommend you read Refactoring: Improving the Design of Existing Code by Martin Fowler, it give the code smell samples.

Benny
I'd like to know what are the code smells that you actually see on your code and on the code of your peers. Do you have any example of real C# code smell that I should pay attention for?
Carlos Loth
@Carlos: Contrived complixity is forced usage of overly complicated design patterns where simpler design would suffice.
Steven
@Steven +1 for the answer. Thanks.
Carlos Loth
+3  A: 

Circular depedency, but not always. And sometimes is really hard to get rid of that.

prostynick
Where are circular dependencies a better design than without?
Robert Fraser
I saw somewhere an example (maybe event on SO) with pet having an owner and owner having a pet and both are interacting with each other :)
prostynick
Ah, I see what you mean. Yup; I guess having "parent" and "children" fields is cool.
Robert Fraser
I don't consider parent/child relationships to be a circular dependency.
Gabe
+24  A: 

One that I see most of the time is the use of as instead of a cast, without any null checks. I don't know why people prefer to use as over a cast when they need a type check. I'd rather have an InvalidCastException than a NullReferenceException.

(control as TextBox).Text = ...;

Fix:

((TextBox) control).Text = ...;
Julien Lebosquain
+1 Because I've seen it and I think robust code should never throw a NullReferenceException.
Carlos Loth
I don't like throwing NullReferenceExceptions when casting.Another thing, "as" is slightly faster then casting, as you can see here http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/88420.aspx
Nelson Reis
Nelson don't throw NullReferenceExceptions, throw InvalidCastException instead.
+2  A: 

Here's my list:

  • Duplicate code
  • Big functions
  • Too many method arguments (>3)
  • Using ref & out arguments
  • God objects
  • Deep inheritance structure
  • Contrived complixity
  • Refused bequest (when you break the LSP)
  • Incorrect use of globals
  • Empty catch clauses.
  • Magic numbers.
  • Multiple abstraction levels in one method.
Steven
@Steven What is "Contrived Complexity"? May you provide more information about it?
Carlos Loth
@Steven - what is wrong with *ref* and *out* arguments, they can have quite legitimate uses. Also empty catch clauses can be handy when debugging and you need somewhere to put a breakpoint (provided you always intended for the exception to be caught and not rethrown).
slugster
@slugster +1 for your comment about when it is useful to have an empty catch block. Any other situation when you see it useful?
Carlos Loth
@slugster FYI an even better way of hitting a breakpoint is to use the VisualStudio Exceptions dialog (http://msdn.microsoft.com/en-us/library/aa290821(VS.71).aspx ) to turn on "break when specified exception is thrown". You do not have to drop out of a debugging session and change code just to break execution when an exception is thrown.
SDX2000
"Empty catch clauses. They are not always a bad smell." I'd say a code smell is something that triggers warning flags in your brain, not something that is definitely always wrong. Empty catch clauses may not always be *wrong* (although they probably are), but it definitely always smells.
Joren
@Steven - yep, i am aware of that feature and have used it often, but it isn't always the best method to use when you need to run your app for some time to cause the exception, or you are not always sure what the exception will be. I'm not saying it is good practice, i am just saying it has its uses, needs to be used thoughtfully and should be removed from production code.
slugster
@slugster: Joren described pretty well what a code smell is. Not everything that smells is bad. French cheese smells, but I like it :-) But you need at least to comment your code why you believe the smell is a false warning. And nobody cares how the code looks like that you use for debugging. As long as it isn’t committed to the code repository everything is fine.
Steven
@Carlos: I removed your changes to my answer. Empty `catch` clauses ARE a smell. However, by definition, not every smell is a programming mistake.
Steven
+1  A: 

Most general OO + imperative code smells will be applicable e.g. using explict branching instead of polymorhism, or very long methods

some more slightly more c# specific things things:

  • leaking memory from event handlers
  • overuse of reflection
  • using non-generic containers to contain a single type

StyleCop (and FxCop) can be used to automate this of course

jk
+9  A: 

Mouldy comments

Where 3 year old commented-out test code stays in the code base:

// Not sure if this will be needed
// int result = command.Setup();
// Command.WriteLine(result)
Chris S
Is source control being used on this case?
Carlos Loth
Yep, it's the "if it ain't broke don't fix it/clean it up" mantra
Chris S
Software development without Source Control is a horrible practice. Even a one-man team will benefit from Source Control.
Steven
Especially due to the fact there are plenty of free source control options (SVN, GIT...). I even liked to use source control with my switch/router configs when I was a network admin.
Matthew Whited
Well, I've seen that a lot in a now 20-year old C-application where it uses a lot of maths and algorithms. The original developer had left the company, the remaining ones had to document the soft because it was being sold to another company, and this kind of comments made their appearance.
+5  A: 

A cousin of the large class and/or large functions: i hate it when one file contains many classes.

I have been guilty of this in the past, and it usually happens when you are coding something up in a hurry and you cannot be bothered creating logical files to house the classes, so you end up with one file containing something like 10 classes (i just refactored one of these today, and it wasn't one of mine).

A derivative of this is when one (usually badly named) file contains the definitions of 10 different enums. Usually enum definitions are not so long so it can be hard to justify putting them all in to different files, but if they are going to be communally contained within one file then that file should at least be named appropriately.

slugster
Is it as bad if they're private inner classes? If they're all related to one specific thing, it seems like they should be.
Robert Fraser
@Rob - i could tolerate that, but if they got biggish then you could use partial classes as a way of factoring the inner classes in to their own file. I've abused this one before too - write a reasonably large class, then introduce a few inner classes, by then the code is starting to look a bit ugly.
slugster
I sometimes do this for small model classes, ones with a small number of auto properties and no methods. But i make sure it has a good name, i hate it when the file is still called FirstClassName.cs, even though it has more classes in it!
Paul Creasey
One handy thing for nested classes it to use a partial class. this way you can keep it in another file with a similar name. (I normal would have it be `MyClass.InnerClass.cs`)
Matthew Whited
Partial classes (outside of generated code) are themselves a code smell - they're a sign that a class is probably too big.
Jeff Sternal
@Matthew - if you don't mind getting funky with the project files, it is also quite easy to nest the actual file containing the factored out partial class (just like how .aspx and .aspx.cs files are nested).
slugster
A developer once remarked to a Microsoft employee "wow! These partial classes are cool, it's almost as if you designed the partial class feature to allow multiple developers to work on the class at the same time without getting each others way!" To which the MS guy responded "Ummm, no. Partial classes are just intended to provide a way to extend generated classes with user-written code."
Ogre Psalm33
There are plenty things that were designed for one thing and yet have many other great uses. (See LINQ and Extension methods.) I would contend that too much code generation could be "code smell" (while I think that term is beyond stupid and shouldn't be used.) I was only suggesting a way to put the nested class in its own file as a way to keep the overall size of the class file reasonable. @slugster, I know the project files could also be modified to group these, shame it's not as easy as automatically detecting the similar file names.
Matthew Whited
+18  A: 

Pokemon exception handling

Coined here.

try
{

}
catch
{
   // I'm catching everything as I don't really 
   // know what my application is doing.
}

One 'exception' to this is where you're using 3rd party libraries, and the documentation is so thin you have no idea what exceptions the library might throw.

Chris S
A variant of that is when you have large try blocks and a catch statement for a specific but very common exception, e.g. NullReferenceException. There is no way to know from which line in the try block the exception came, but the code in the catch block often assumes it came from a specific place. This typically leads to more bugs or misleading error messages being shown to the user.
Joh
Another variant is just having empty catch { }. This way you might not notice when something has gone wrong...
Carlos
Agh! I know! I'm maintaining a legacy system with empty catch { } all over the place. The users are like "my documents are disappearing, but there's no error message!", and I'm going "what? how can that be?" Empty catch FTW
Ogre Psalm33
Another one is having a very large try { } block, 300+ lines, then a catch { throw ex; } so the default ASP.NET handler will show the error page.
MadcapLaugher
No matter what, I catch whatever I think is posible to happen and what and I'dont think it going to happen (but Murphy says it will) in an empty catch, especially on Windows Services. I prefer to fail to respond one request than stoping the whole usually critical service.
+2  A: 

Use tools like Resharper. It gives suggestions and best practices to write code. It also examines coding conventions.

nitroxn
A: 

Not particular to C#, but are all valid anyway: http://wiki.java.net/bin/view/People/SmellsToRefactorings

jpbochi
+3  A: 

Not using LINQ when applicable.

Or, in other words, implementing something that could have been implemented using LINQ in a smelly way. Codes like that can become unreadable easily. They also may conceal several responsibilities (hurting the Single Responsibility Principle) like filtering, sorting, selecting, grouping, etc. Even without LINQ, this type of code should be implemented in a clean way.

Eric Lippert has written about this: http://blogs.msdn.com/b/ericlippert/archive/2010/01/11/continuing-to-an-outer-loop.aspx

jpbochi
Any real-world examples?
Carlos Loth
@Carlos: Do you want me to show you a rather big and ugly block with code with multiple nested foreach statements and if statements or do you get the picture? :-)
Steven
@Steven That is the most obvious scenario. I was wondering about the existance of non-obvious situations. Any suggestions?
Carlos Loth
@Carlos: [try this](http://stackoverflow.com/questions/2897026/how-can-modify-or-add-new-item-into-generic-list-of-strings/2897094#2897094 "try this") for an example
slugster
How is that a code smell ? Don't get me wrong, I love LINQ, but we've been coding without LINQ for years, and that doesn't make the code we wrote then "smelly"...
Thomas Levesque
@slugster: nice example. +1 for that.
Steven
Thomas has a good point. The code smell in Jpbochi's 'obvious example' is not that LINQ is missing, but that it doesn't describe the intent well. Refactoring it with a LINQ query is just one solution. Another is way is to use the 'extract method' refactor pattern and create a method with a clear and consise name.
Steven
@Thomas: I agree that pre-LINQ code didn't had an alternative, but, in complex situations, if badly implemented the code can become nearly unreadable. That would be a smell for me. And now, with LINQ, getting a readable declarative code is much easier.
jpbochi
@Thomas: I added some description to the answer so my point become clearer. Feel free to edit, too. It's a wiki.
jpbochi
Eric Lippert's related article: http://blogs.msdn.com/b/ericlippert/archive/2010/01/11/continuing-to-an-outer-loop.aspx
Brian
@Brian: thanks, that's exactly what I was talking about.
jpbochi
A: 

Having member or variable names that don't make their purpose clear, or having too many intermediate variables

This suggests disorganized planning/forethought, and likely also disorganized design. For instance a method implementation might have a load of intermediate variables that are not necessary, leading to names like "tempResultPartial1" and "pretransformAnswer2". I'm not saying intermediate variables are always wrong, just that too many might suggest the code is too complex.

Carlos
A: 

Uncommented LINQ or lambda expressions. Lambda expressions without a sensible name for the variables.

Query type expressions often have unintuitive purposes, and are thus easily misunderstood by someone else reading the code. This is okay if it's a simple expression, but anything with a chain of calls will require a double take.

Also, if you're doing a lambda, you might as well call your variable something that tells the reader what it is. So for instance accounts.select(acnt=>acnt.acntID) makes more sense than accnts.select (x=>x.acntID). This becomes even more important when you chain calls together, for instance if you have a grouping.

Carlos
A: 

This may be a personal thing for me, but I don't think "var" belongs in well-factored Object Oriented code (even though it is a "feature" of C#).

var thing = new Widget();
//...
// manipulate thing later in the code

Or even better, if I'm maintaining code and I see this:

foreach (var item in mysteriousCollection)
{
    item.MethodA();
    item.DoMoreStuff();
    // Manipulate item in other ways, you get the idea...
}

I saw that line of code, and I was like "what's an item? What methods and properties does it have?" Don't make me waste my time ferreting out what the heck the mysteriousCollection is, just so I can figure out what kind of thing the code is iterating through.

By some definitions, a code smell is a driver for refactoring. Consider the foreach loop example above. What's the easiest way to refactor out the code inside the loop into another method? private void ManipulateItem(var item) does not work (The contextual keyword 'var' may only appear within a local variable declaration). Now I've got to go figure out what the item is and how to deal with it.

From the comments, I can see some legitimate reasons why you would declare something "var" instead of the Parent class, but from a OO refactoring standpoint I think the use cases are limited. (Any other comments on good uses of var would still be appreciated)

Ogre Psalm33
Why do you care what `item` is? And it is that important you can always mouse over. If you ever replace the content of `mysteriousCollection` with something else you don't have to go though and change all of the type declaration.
Matthew Whited
Obviously this is a simplistic example (imagine 50 lines of code instead of just item.MethodA()), but I've been at the point before where, maintaining legacy code, I've had to go through and dissect a block of code and figure out what's actually going on because I know there's a bug in there somewhere, but I just don't know what it is. A refactoring tool such as Resharper mitigates changing all the type declearations. However, I do see your point, so thanks. :-)
Ogre Psalm33
This has nothing to do with OO, but with the way you declare variables. I know quite some fully OO languages which function properly even when omitting type declarations everywhere. For me this is code style, not code smell. Especially when the type gets longer, eg with some generic stuff, I find it a smell when the type is expressed twice: `Dictionary<Foo, Bar> foo = new Dictionary<Foo, Bar>();`. I prefer var foo = new Dictionary<Foo, Bar>();
Dykam
@Dykam, from strictly an OO standpoint, perhaps you're right and I can see your point. But I do not agree that this is not a code smell (again my opinion). Code Smells and refactoring go hand in hand, and liberal use of var, in my experience, has gotten in the way of refactoring.
Ogre Psalm33
Agreed. var is just lazy; explicitly and consistently specifying the type of a variable leads to clear, readable and more maintainable code. Anonymous types are just as bad.
David Lively
-1. Couldn't disagree more - var in C# only saves you writing and reading, it doesn't change the rules of the language. That first example won't even compile - the compiler needs to know what type 'thing' is when you declare it. Var is not dynamic typing, it's implicit static typing.
Dan
@Dan. You are right re: the first example. I reverted my edits to the original simpler example I had. It's good to know that C# does that type checking at compile time. However, personally, from a *maintenance* standpoint (i.e.: not the original developer), "var" has cost me "reading" effort (even if it saves writing), as sometimes I have to go rooting through the code to figure out what "item" is.
Ogre Psalm33
-1: Using `var` avoids redundancy, making it easier to read declarations.
Brian
Avoids redundancy? There's no guarantee that the declared type of a variable is what it holds. Object X = new Exception(); Yay polymorphism.
David Lively
@David Lively, what do you mean?
Dykam
A: 

Empty catch blocks like these....

 try{  
      //do something
    }
catch(SQLException sqex){  
        // do nothing  
    }

Exception handling for creating alternate method flows...

 try{  
     //do something  

 }catch(SQLException sqex){  

     //do something else  
 }
CodeToGlory
A: 

If my initials are somewhere in the .cs-file header or if my username is connected with the latest changeset, I know there is something wrong with the code that needs to be looked at. :-)

daft
+1  A: 

Complexity

Simply put, complexity is IMO the most common and most important code smell. Sure there are always bits here and there you can improve upon but if the overall complexity of your application/class/method/solution is too high you have a problem.

Complexity is often a sign that something hasn't been refactored enough, ie you added a bunch of stuff which created "scar tissue" and you didn't refactor to remove it. Sometimes when you add features you hit a "complexity barrier" where you need to introduce some new abstraction in order to keep each discrete part simple and easy to comprehend and digest. When looking at code, ask yourself:

  • Does this method/class do more than one thing? Most often it shouldn't

  • Does this method/class have a lot of dependencies to other methods/classes. They shouldn't

  • If you hadn't written the code yourself and was looking at it, would it make sense?

MattiasK