Related
My resources are stored in an assembly of their own, and I have a reference to that assembly in my web app. I am able to access resources in two different ways - via compiled constants or by using a ResourceManager.
var method1 = Prototype.Localization.CustomerRecord.BillingId;
or
var resx = new ResourceManager(typeof (Prototype.Localization.CustomerRecord));
var method2 = resx.GetString("BillingId");
Using the first approach seems like a no brainer (but that generally means it's going to come back and bite me when things get more complicated), so what are the advantages or disadvantages to the second approach? Is the first approach going to cause me issues down the road?
So what are the advantages or disadvantages to the second approach?
2nd approach is what resx compiler does under the cover. IMO 2nd one is always worse because you have a string (then it may goes detached and you won't know until run-time) and because of that you'll lack of compile-time checks and design-time support.
Is the first approach going to cause me issues down the road?
No, at least no more than anything else (because you'll catch errors in your HTML pages when you'll first compile them at run-time).
So I may ask: if first approach is shorter and easier then is there any good reason to use the 2nd one? My answer is "no" (moreover you can mix them, in case you'll need it for a special thing).
Yeah, I agree with Adriano that the 2nd is worse because of those "Magic" strings.
The first approach you have some more advantages that would include compile time check, since you reference a class and a property if this property doesn't exist you will get an error back, intellisense is another one.
Another advantage, is that if you decided to move away from the built in resource manager, you could just replace the generated class (resource class) by your own respecting the namespace and so on, with your own internal logic.
IMO, I would stick with the first one.
I've noticed a pattern recently in our codebase at work, where most of our model class have a name such as User, and there is an inheriting type that has extra fields on it called UserEx. I've also noticed this in the C# async CTP where they put the additional static methods for Task in a class called TaskEx (due to technical restrictions, since they couldn't alter the existing library). Talking to someone at work, I learned that -Ex classes exist to optimize network transfers (you can pull only the bare minimum if you need). My question, then, is what does -Ex stand for? The only thing I can think of is possibly "Extra".
The other answers all got it correct: the Ex suffix stands for "extended". It's a way of introducing a new class or method without obsoleting or removing the old one, a common way of retaining backwards compatibility while introducing new features.
The Windows API does this all over the place, as explained here.
Hans hints at the problem with this approach in his explanation: it doesn't scale. What if you want to extend an "extended" function? Do you call it FunctionExEx? That looks stupid.
So stupid, in fact, that Microsoft's own coding guidelines for .NET (subjective though they are) specifically recommend against appending Ex to a type. Instead, if you must do this, you should use a number:
MyType
MyType2 // modified version
MyType3 // oh wait, we had to modify it again!
Blaming this on poor planning as dowhilefor tries to do is a bit premature. When writing real world applications and frameworks, you often need to ship. That means getting out a quick-and-dirty version of the function that works. Later, you decide this is a poor design and something needs to change. Rather than throwing up your hands and completely re-writing (producing giant delays and obsoleting all of the old code), you introduce a new type with a different name. Hindsight is always 20/20.
Ending a new class or method or type in Ex is a naming convention, and like any naming convention, it is subject to the whims of those implementing it.
There are no hard and fast rules, and it is no more or less correct than appending 2 to the end of the class (or Extra, or More, or DidntWantToMessWithThePublicApi).
As for why it is used, Microsoft has a long history of using it to provide a revision to an existing API without breaking older code. You can find examples of this in classes, in methods, and in structures. You can also find different examples, which instead use 2.
It stands for "Extension" or "Extended", as far as I know. It's a common suffix to when you need to add functionnality to something that you can't change. A good example was the various -Ex functions in the Win32 APIs, which were added because C does not support function overloading.
This practice is NOT industry-standard. I'll admit I do it myself, but it's mostly vestigial emulation of some of the old win32 kernel functions. for example, they initially had a "beginthread" C function and later created another new-and-improved "begintreadEx".
I would suggest that you start using the [Deprecated] attribute to signal to other coders (or yourself) to stop using the old function in favor of the new one. That has more intrinsic meaning.
Long story short -- you should name classes & functions based on what they are or do, and try to avoid pseudo-meaningful prefixes/suffixes that create confusion such as this. That is the industry-standard approach.
I thought possibly:
external
extricated
simply 'ex' (as in 'out of' or 'beyond')
Honestly, i think it means "We didn't plan this feature long enough, didn't thought about the changed requirements, and we have to deal with this now close to the deadline". Of course this is not always the case, but everytime i find a class with Ex i try to figure out why it was introduced and not properly added into the framework. For me its mostly like // HACK:
This only counts for our code, if it is in a framework i "hope" thats just naming convention.
What it could mean was already answered, my guess was always "Extended"
Developing a series of POCOs on my project, and just realized that some of them doesn't need the using System; clause.
Is there any performance or size penalty for leaving unused using <module>; on my objects or project ?
Will my classes get bigger, or slower, or bloated because of this or the compiler/optimizer is smart enough to take care of this?
no there are not performance issue .
it is just a readability matter(I would suggest to remove them)
more info at:
Why should you remove unnecessary C# using directives?
All the "using System;" statement does is allow you to use that namespace without fully qualified names. It doesn't affect run-time performance in any way.
There is no runtime performance penalty for having unused using statements in your code. They don't appear is the compiled DLL in any form (they do exist in the PDB).
However if you know them to be invalid it's generally considered good style to remove them. Having unused usings is essentially stating a false dependency your code has on a set of types and extension methods.
Determining which usings are not used is a tedious process. I find it's best to just install a tool like PowerCommands and let it do the work on file save.
http://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99
That brings neither performance gain nor hit.
I remove all unused and sort all used usings as code style (neatness). You can do this via Visual Studio context menu (I bound it to a hotkey).
If you are not using a reference / assembly or extended functionality
for example using System.Linq; by default gets added to VS2010 projects.. if you don't use it.. just remove it.. no performance issues
The using directive is just syntactic sugar.
Adding using references will not affect performance other than a marginal compile-time difference.
It in no way affects the output of the compiler or the performance of the compiled program!
It can be removed a as part of personal preference. I would personally recommend it as it would make the compilation faster (fewer namespaces for the compiler to look up) and also improve the performance of intellisense.
It has no impact on performance. It can be kept or removed at your discretion.
However, consider keeping it. The System namespace contains the most commonly used parts of the .NET Framework, and at some point during the lifetime of your file, you (or someone) will probably end up needing it. That means inevitably putting it back, possibly after wasting time wondering why none of the system classes exist.
I'm wondering if there are any reasons (apart from tidying up source code) why developers use the "Remove Unused Usings" feature in Visual Studio 2008?
There are a few reasons you'd want to take them out.
It's pointless. They add no value.
It's confusing. What is being used from that namespace?
If you don't, then you'll gradually accumulate pointless using statements as your code changes over time.
Static analysis is slower.
Code compilation is slower.
On the other hand, there aren't many reasons to leave them in. I suppose you save yourself the effort of having to delete them. But if you're that lazy, you've got bigger problems!
I would say quite the contrary - it's extremely helpful to remove unneeded, unnecessary using statements.
Imagine you have to go back to your code in 3, 6, 9 months - or someone else has to take over your code and maintain it.
If you have a huge long laundry list of using statement that aren't really needed, looking at the code could be quite confusing. Why is that using in there, if nothing is used from that namespace??
I guess in terms of long-term maintainability in a professional environment, I'd strongly suggest to keep your code as clean as possible - and that includes dumping unnecessary stuff from it. Less clutter equals less confusion and thus higher maintainability.
Marc
In addition to the reasons already given, it prevents unnecessary naming conflicts. Consider this file:
using System.IO;
using System.Windows.Shapes;
namespace LicenseTester
{
public static class Example
{
private static string temporaryPath = Path.GetTempFileName();
}
}
This code doesn't compile because both the namespaces System.IO and System.Windows.Shapes each contain a class called Path. We could fix it by using the full class path,
private static string temporaryPath = System.IO.Path.GetTempFileName();
or we could simply remove the line using System.Windows.Shapes;.
This seems to me to be a very sensible question, which is being treated in quite a flippant way by the people responding.
I'd say that any change to source code needs to be justified. These changes can have hidden costs, and the person posing the question wanted to be made aware of this. They didn't ask to be called "lazy", as one person inimated.
I have just started using ReSharper, and it is starting to give warnings and style hints on the project I am responsible for. Amongst them is the removal of redundant using directive, but also redundant qualifiers, capitalisation and many more. My gut instinct is to tidy the code and resolve all hints, but my business head warns me against unjustified changes.
We use an automated build process, and therefore any change to our SVN repository would generate changes that we couldn't link to projects/bugs/issues, and would trigger automated builds and releases which delivered no functional change to previous versions.
If we look at the removal of redundant qualifiers, this could possibly cause confusion to developers as classes in our Domain and Data layers are only differentiated by the qualifiers.
If I look at the proper use of capitalisation of anachronyms (i.e. ABCD -> Abcd), then I have to take into account that ReSharper doesn't refactor any of the Xml files we use that reference class names.
So, following these hints is not as straight-forward as it appears, and should be treated with respect.
Less options in the IntelliSense popup (particularly if the namespaces contain lots of Extension methods).
Theoretically IntelliSense should be faster too.
Remove them. Less code to look at and wonder about saves time and confusion. I wish more people would KEEP THINGS SIMPLE, NEAT and TIDY.
It's like having dirty shirts and pants in your room. It's ugly and you have to wonder why it's there.
Code compiles quicker.
Recently I got another reason why deleting unused imports is quite helpful and important.
Imagine you have two assemblies, where one references the other (for now let´s call the first one A and the referenced B). Now when you have code in A that depends on B everything is fine. However at some stage in your development-process you notice that you actually don´t need that code any more but you leave the using-statement where it was. Now you not only have a meaningless using-directive but also an assembly-reference to B which is not used anywhere but in the obsolete directive. This firstly increases the amount of time needed for compiling A, as B has to be loaded also.
So this is not only an issue on cleaner and easier to read code but also on maintaining assembly-references in production-code where not all of those referenced assemblies even exist.
Finally in our exapmle we had to ship B and A together, although B is not used anywhere in A but in the using-section. This will massively affect the runtime-performance of A when loading the assembly.
It also helps prevent false circular dependencies, assuming you are also able to remove some dll/project references from your project after removing the unused usings.
At least in theory, if you were given a C# .cs file (or any single program source code file), you should be able to look at the code and create an environment that simulates everything it needs. With some compiling/parsing technique, you may even create a tool to do it automatically. If this is done by you at least in mind, you can ensure you understand everything that code file says.
Now consider, if you were given a .cs file with 1000 using directives which only 10 was actually used. Whenever you look at a symbol that is newly introduced in the code that references the outside world, you will have to go through those 1000 lines to figure out what it is. This obviously slows down the above procedure. So if you can reduce them to 10, it will help!
In my opinion, the C# using directive is very very weak, since you cannot specify single generic symbol without genericity being lost, and you cannot use using alias directive to use extension methods. This is not the case in other languages like Java, Python and Haskell, in those languages you are able to specify (almost) exactly what you want from the outside world. But even then, I will suggest to use using alias whenever possible.
For example, I rarely need:
using System.Text;
but it's always there by default. I assume the application will use more memory if your code contains unnecessary using directives. But is there anything else I should be aware of?
Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?
Edit: Note that this question is not about the unrelated concept called a using statement, designed to help one manage resources by ensuring that when an object goes out of scope, its IDisposable.Dispose method is called. See Uses of "using" in C#.
There are few reasons for removing unused using(s)/namespaces, besides coding preference:
removing the unused using clauses in a project, can make the compilation faster because the compiler has fewer namespaces to look-up types to resolve. (this is especially true for C# 3.0 because of extension methods, where the compiler must search all namespaces for extension methods for possible better matches, generic type inference and lambda expressions involving generic types)
can potentially help to avoid name collision in future builds when new types are added to the unused namespaces that have the same name as some types in the used namespaces.
will reduce the number of items in the editor auto completion list when coding, posibly leading to faster typing (in C# 3.0 this can also reduce the list of extension methods shown)
What removing the unused namespaces won't do:
alter in any way the output of the compiler.
alter in any way the execution of the compiled program (faster loading, or better performance).
The resulting assembly is the same with or without unused using(s) removed.
It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.
Mainly, it's just to clean up for personal preference.
Code cleanliness is important.
One starts to get the feeling that the code may be unmaintained and on the browfield path when one sees superfluous usings. In essence, when I see some unused using statements, a little yellow flag goes up in the back of my brain telling me to "proceed with caution." And reading production code should never give you that feeling.
So clean up your usings. Don't be sloppy. Inspire confidence. Make your code pretty. Give another dev that warm-fuzzy feeling.
There's no IL construct that corresponds to using. Thus, the using statements do not increase your application memory, as there is no code or data that is generated for it.
Using is used at compile time only for the purposes of resolving short type names to fully qualified type names. Thus, the only negative effect unnecessary using can have is slowing the compile time a little bit and taking a bit more memory during compilation. I wouldn't be worried about that though.
Thus, the only real negative effect of having using statements you don't need is on intellisense, as the list of potential matches for completion while you type increases.
You may have name clashes if you call your classes like the (unused) classes in the namespace. In the case of System.Text, you'll have a problem if you define a class named "Encoder".
Anyways this is usually a minor problem, and detected by the compiler.
Leaving extra using directives is fine. There is a little value in removing them, but not much. For example, it makes my IntelliSense completion lists shorter, and therefore easier to navigate.
The compiled assemblies are not affected by extraneous using directives.
Sometimes I put them inside a #region, and leave it collapsed; this makes viewing the file a little cleaner. IMO, this is one of the few good uses of #region.
if you want to maintain your code clean, not used using statements should be removed from the file. the benefits appears very clear when you work in a collaborative team that need to understand your code, think all your code must be maintained, less code = less work, the benefits are long term.
Your application will not use more memory. It's for the compiler to find classes you use in the code files. It really doesn't hurt beyond not being clean.
It’s personal preference mainly. I clean them up myself (ReSharper does a good job of telling me when there’s unneeded using statements).
One could say that it might decrease the time to compile, but with computer and compiler speeds these days, it just wouldn’t make any perceptible impact.
They are just used as a shortcut. For example, you'd have to write:
System.Int32 each time if you did not have a using System; on top.
Removing unused ones just makes your code look cleaner.
The using statement just keeps you from qualifying the types you use. I personally like to clean them up. Really it depends on how a loc metric is used
Having only the namespaces that you actually use allows you to keep your code documented.
You can easily find what parts of your code are calling one another by any search tool.
If you have unused namespaces this means nothing, when running a search.
I'm working on cleaning up namespaces now, because I'm constantly asked what parts of the application are accessing the same data one way or another.
I know which parts are accessing data each way due to the data access being separated by namespaces e.g. directly through a database and in-directly through a web service.
I can't think of a simpler way to do this all at once.
If you just want your code to be a black box (to the developers), then yes it doesn't matter. But if you need to maintain it over time it is valuable documentation like all other code.
The 'using' statement does not affect performance as it is merely a helper in qualifying the names of your identifiers. So instead of having to type, System.IO.Path.Combine(...), you can simply type, Path.Combine(...) if you have using System.IO.
Do not forget that the compiler do a lot of work to optimize everything when building your project. Using that is used in a lot of place or 1 shouldn't do a different once compiled.