25

My colleague insists on explicitly specifying the namespace in code as opposed to using the using directive. In other words he wants to use the fully qualified name for each type every time this type occurs in code. Something like

public class MyClass
{
    public static void Main()
    {
        System.Console.WriteLine("Foo");
    }
}

instead of:

using System;
public class MyClass
{
    public static void Main()
    {
        Console.WriteLine("Foo");
    }
}

You can imagine the consequences.

The pros he gives:

  1. It's simpler to copy and paste code into other source files.
  2. It is more readable (you see the namespaces right away).

My cons:

  1. I have to write more
  2. The code is less readable (I guess de gustibus non disputandum est)
  3. No one does it!

What do you think about this?

8
  • 2
    I've changed the title to reflect that you mean the using directive rather than the using statement. (The latter being what you use with IDisposables.) Hope you don't mind!
    – Jon Skeet
    Oct 18, 2008 at 11:10
  • 24
    Time to get a new colleague
    – Greg Dean
    Oct 18, 2008 at 13:06
  • Your colleague needs to learn their FCL namespaces and not compensate by making everybody else jump through hoops.
    – John K
    Jan 8, 2010 at 21:25
  • If it won't compile after a Copy + Paste, click or select the part that refuses to compile and ask your IDE (In VS this defaults to alt+shift+F10) to generate a using statement for you. The copy and paste argument is pretty weak.
    – Brian
    Jan 8, 2010 at 21:26
  • 7
    In fact I'd start drinking heavily if your colleague gets his way. It's either using or the bottle IMHO.
    – John K
    Jan 8, 2010 at 21:28

25 Answers 25

65

If you need to copy and paste code around so much as to actually benefit of having fully qualified types, you've got bigger problems.

Also, do you plan on remembering which namespace every single class is in in order to be able to type it fully qualified?

48

For a slightly different answer: LINQ.

Extension methods are obtained only via "using" statements. So either the query syntax or the fluent interface will only work with the right "using" statements.

Even without LINQ, I'd say use "using"... reasoning that the more you can understand in fewer characters, the better. Some namespaces are very deep, but add no value to your code.

There are other extension methods too (not just LINQ) that would suffer the same; sure, you can use the static class, but the fluent interface is more expressive.

1
  • 1
    +1 I'd vote this one up to oblivion if I could.
    – John K
    Jan 8, 2010 at 21:26
37

What do I think about this?

I think that a person who would come up with an idea like this, and who would justify it the way he has, is very likely to have a number of other fundamental misunderstandings about the C# language and .NET development.

3
  • Up-vote to take you to 3,000 :-)
    – HTTP 410
    Dec 17, 2008 at 1:55
  • Such as? The answer isn't very helpful to people who need it if you don't give examples. Feb 18, 2010 at 17:42
  • 2
    Such as: the first reason given for doing this - that it makes copying and pasting code easier - is essentially saying, "You should take on the enormous cognitive overload of fully qualifying every type you use because it simplifies a task that experienced C# programmers avoid like the plague it is." Feb 18, 2010 at 19:13
23

The minute your colleague said "copy-and-paste code", he lost all credibility.

0
19

The biggest problem I find with not using the "using" directive isn't on instantiantion and definition of classes. It's on passing in values to functions that are defined defined in the namespace. Compare these two pieces of code (VB.Net, because that's what I know, but you get the picture).

Module Module1

    Sub Main()
        Dim Rgx As New System.Text.RegularExpressions.Regex("Pattern", _
            System.Text.RegularExpressions.RegexOptions.IgnoreCase _
            Or System.Text.RegularExpressions.RegexOptions.Singleline _
            Or System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace)


        For Each result As System.Text.RegularExpressions.Match In Rgx.Matches("Find pattern here.")
            'Do Something
        Next
    End Sub

End Module

And this

Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        Dim Rgx As New Regex("Pattern", _
            RegexOptions.IgnoreCase _
            Or RegexOptions.Singleline _
            Or RegexOptions.IgnorePatternWhitespace)


        For Each result As Match In Rgx.Matches("Find pattern here.")
            'Do Something
        Next
    End Sub

End Module

In cases like this where lots of enums are used, as well as declaring your variables inline in a for loop, to reduce scope, not using "using" or "imports" in the case of vb.Net, can lead to really bad readability.

2
  • 1
    This is the most effective demonstration of what is wrong with this approach in my eyes. Note that your example is VB; in C# it would be even worse, because every variable has a type attached to it. Oct 18, 2008 at 13:55
  • @Simon, you can infer it with var.
    – Dykam
    Jan 8, 2010 at 22:21
9

Making it easier to move code around by copy and paste is simply a non sequitur, and quite possibly a warning sign of potentially dangerous practice. The structure and legibility of code shouldn't be dictated by ease of edit.

If anything it makes the code less readable and more specific - personally I'm not interested where standard objects live, it's akin to addressing your colleague by their complete given name, prefixed with the street address of your workplace.

There are times, however, where occasionally it makes the code more readable, so hard and fast rules are not applicable, just common sense.

6

Because we have a tool in C# for auto-setting the using statement, by pressing Ctrl+. - I can't see any reason not to use it. The other "cool" thing here, is:

Think about you have a two namespaces:

ConsoleNamespace1

and

ConsoleNamespace2

Both have a Console class. Now you can change all the references to ConsoleNamespace2, with just a single line of code - that's cool.

My advice: Use using if you can, the full if you must. I don't think the fully one, if easier to read. Know your framework, and this will never be a problem.

4
  • Um, ctrl+dot sounds more like something an IDE would offer rather than a programming language.
    – David Holm
    Oct 18, 2008 at 9:53
  • Couldn't you do this without the "using" keyword. Simply create objects that inherit the same base object, or implement the same interface, and you can accomplish the same thing.
    – Kibbee
    Oct 18, 2008 at 12:44
  • Uh oh !? Can you explain this ctr+dot, please. Sounds interesting. TIA. Oct 18, 2008 at 13:05
  • Ctrl+. is the keyboard shortcut for the right-click "Resolve=>" menu. (actually it does any of the "squiggle" popups). For example, with no "using" directives, type Console"[Ctrl]+." and it will add "using System;" to the top, and your code now works. Oct 18, 2008 at 13:21
4

It's also worth noting that a tool like ReSharper (why aren't you already using it?) will add the appropriate 'using' lines for you pretty much automatically.

3

One of the reasons you use "using" is that it tells anyone reading the source the sort of things your class will be doing. Using System.IO tells a reader you're doing I/O operations, for example.

1

My general rule is that if I am going to use items from a particular namespace more than a few times, it gets a using directive. However I don't want to clutter up the top of the file with using directives for things that I only use once or twice.

1

Install ReSharper on you machines. Sit back and let it guide your colleague to righteousness. Seriously, there are bigger battles but this is the kind of coder to avoid if it takes more than two minutes to try to educate.

1

"The minute your colleague said "copy-and-paste code", he lost all credibility." ditto.

"The Law of Demeter says..." ditto

...and I add. That's just absurd, not using using statements. Get ReSharper, find some way to teach this fellow how it's done, and if it doesn't seem to take effect - with the reasons given, it's time to start looking into a different job. Just the correlations of what goes along with such notions as not using using statements is scary. You'll be stuck working 16 hr days fixing mess if that's one of the rules. There is no telling what other type of affront to common sense and logic you'll face next.

Seriously though, this shouldn't even be brought up with tools like ReSharper available. Money is being wasted, buy ReSharper, do code cleanup, and get back to making usable software. :) That's my 2 cents.

1

if you are repeatedly copying and pasting code, doesn't that point to creating a standard DLL to include into each of your projects?

I've worked on projects using both methods before and have to say having the "Using" statements makes sense to me, it cuts down on the code, makes it more readable and your compiler will ultimately optimise the code in the right way. The only time you may have an issue is if you have two classes from two namespaces which have the same name, then you would have to use the fully qualified name...but thats the exception rather than the rule.

1

I think with the IntelliSense features in Visual Studio and using some third-party products like ReSharper, we no longer care about either to make our code fully qualified or not. It became no longer time consuming to resolve the namespaces when you copy and paste your code.

1

You can also use aliases...:

using diagAlias = System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            diagAlias.Debug.Write("");
        }
    }
}
3
  • Normally, though, you only need an alias to disambiguate between two classes because of conflicting "using" statements. extern alias would be a more concrete example, but it is very rarely used... Oct 18, 2008 at 12:20
  • So we shouldn't use them just to save typing...? Thank you.
    – user10178
    Oct 18, 2008 at 12:23
  • Well, you can use an alias to save typing, but that isn't the main use. In the case given, you could save even moer typing by just using "Debug.Write" with a "using System.Diagnostics" - 20 fewer characters, in fact, and no need to ask "what is diagAlias". Oct 18, 2008 at 12:44
1

I have been coding for 25 years. USINGS are essential and should always be utilized and is a good coding practice. HOWEVER any good developer should have a repository of code. Sharing snippets of code is much easier when including fully qualified namespaces.

The comment COPY & PASTE is a bad technique usually comes from the mouth of those developers who haven't taken the time to build a robust repository of code and haven't stopped to truely understand generic code is tested code. Fully qualified namespaces I see as a necessity in code repositories or else your hunting around trying to determine where the heck the namespace comes from.

1

Oh boy. One step might be teaching your collegue about Ctrl+. It will automatically insert using statements for you.

0

I recommend against the proposition of your colleague. For me reading code is much easier if you don't have a long namespace cluttering the line. Just imagine this:

Namespace1.Namespace2.Namespace3.Type var = new Namespace1.Namespace2.Namespace3.Type(par1, par2, par3);

as opposed to:

Type var = new Type(par1, par2, par3);

Regarding copy-paste - you do have Shift+Alt+F10 that will add the namespace, so it shouldn't be a problem.

0

You really want to maintain code that way? Even with intellisense all that typing is not going to be productive.

0

Instead of 'copy-n-paste' I call it 'copy-n-rape' because the code is abused 99.9% of the times when it is put through this process. So there, that's my answer to your colleague's #1 justification for that approach.

On a side note, tools like Resharper will add the using statements at the top when you add code that needs them to your code (so even if you 'copy-n-rape' code like that you can do so easily).

Personal preferences aside, I think your justifications are much more valuable than his, so even assuming they are all valid points, I'd still reccomend writing the using statements at the top. I would not make it a 'ban' though, since I see coding standard as guidelines rather than rules. Depending on your team size it might be very hard to enforce things like that (or how many spaces for indentation, or indentation styles, etc etc).

Make it a guideline so that all the other developers feel free to replcae the fully qualified names with the shorter versions and, over time, the code base will fall in line with the guideline. Keep an eye out for people taking time away from doing work to simply change all the occurrences of one style to the other - 'cause that's not very productive if you're not doing anything else.

0

He might have a point with somethings. For instance, at a company I work at we have a lot of code generated classes and so all of our code generated classes we use the fully qualified names for classes in order to avoid any potential conflicts.

With all the standard .NET classes that we have, we just use the using statements.

0

In a system like .NET, where there are types in namespaces, you have to make a decision: is a namespace part of the name, or is it an organizational tool for types?

Some systems choose the first option. Then, your using directives would be able shortening the names that you use the most often.

In .NET, it's the latter. For example, consider System.Xml.Serialization.XmlSerializationReader. Observe the duplication between the namespace and the type. That's because in this model, type names must be unique, even across namespaces.

If I remember correctly, you can find this described by the CLR team here: http://blogs.msdn.com/kcwalina/archive/2007/06/01/FDGLecture.aspx

Its simpler to copy and paste code into other source files.

True, but if you're copy/pasting a lot of code, you're probably doing it wrong.

It is more readable (you see the namespaces right away)

Seeing the namespaces isn't important, since, at least when you're following Microsoft's guidelines, type names are unique already; the namespace doesn't really provide you with useful information.

0

I'm someone who has a tendancy to fully qualify namespaces. I do it when I'm using components which i'm not familiar with/ haven't used for a long time. I helps me remember what's in that namespace so next time I'm looking for it/ related classes.

It also helps me twig to whether I have the appropriate references in the project already. Like if I write out System.Web.UI but can't find Extensions then I know I forgot/ who ever set up the project forgot to put in the ASP.NET AJAX references.

I'm doing it less and less though these days as I'm using the shortcut to qualify a class (Ctrl + .). If you type out the name of the class (correctly cased) and press that shortcut you can easily fully quality/ add a using statement.

It's great for the StringBuilder, I never seem to have System.Text, so I just type StringBuilder -> Ctrl + . and there we go, I've added the using.

0

The Law of Demeter says you should use only one dot:

For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code "a.b.Method()" breaks the law where "a.Method()" does not.

Of course, this is not always practical. But long strings of dot-separated identifiers violate accepted practice.

EDIT: This answer seems controversial. I brought the Law of Demeter up mostly as a style guide, and most replies here seem to agree that limiting the number of dots is a good idea. In my opinion, jQuery (and JavaScript) suffer from readability problems, partly because excessive dots creep into any non trivial program .

4
  • 1
    This really doesn't apply to namespaces though. It has more to do with that one object shouldn't operate outside the world of its nearest friends.
    – David Holm
    Oct 18, 2008 at 9:53
  • (stretching it a lot) Can you think of namespace as an object?
    – gimel
    Oct 18, 2008 at 10:06
  • 1
    I agree with David - Demeter is not about dots, that's just a way of describing it simply - it's about coupling and information hiding, neither of which apply here
    – Will Dean
    Oct 18, 2008 at 10:20
  • Note that jQuery syntax is almost entirely long strings of dot-separated identifiers.
    – J c
    Oct 18, 2008 at 10:49
0

Isn't the fact that Visual Studio includes lots of using statements at the top of pretty much every file it creates a hint that using statements are considered good practice?

Not the answer you're looking for? Browse other questions tagged or ask your own question.