When I am looking at my code and I am writing things like..
if (role == "Customer")
{
bCustomer = true;
}
else if (role == "Branch")
{
bIsBranch = true;
}
Or
foreach(DataRow as row in myDataSet.Tables[0].Rows)
{
row["someField"]=somefield.Tostring()
}
Are you guys doing this? When is this ok to do and when shouldn't you be doing this? What if any would be a better approach to write this if any?
Thanks For the Comments: I guess I should add what if (for this example purposes) I am only using this role comparison once? Is it still a better idea to make a whole new class? Also should I have 1 class called "constants" are multiple classes that that hold specific constants, like "roles" class for example?
No. Don't use "magic strings". Instead create a static class with constants, or an enum if you can.
For example:
public static class Roles
{
public const string Customer = "Customer";
public const string Branch = "Branch";
}
Usage:
if (role == Roles.Customer)
{
}
else if (role == Roles.Branch)
{
}
Here's a good discussion on various solutions.
It is always better to declare the hard coded strings separately as constants rather then declaring a new string every time. It keeps code clean and reduce errors which are caused by typing mistakes.
Regarding should or shouldn't be done totally depends on scenario.
I would make a Roles static class:
public sealed class Roles
{
public const string BRANCH = "Branch";
public const string CUSTOMER = "Customer";
public static bool IsCustomer(string role)
{
return role == CUSTOMER;
}
}
Then in your code:
bCustomer = Roles.IsCustomer(role);
Alternatively, this requires a little more setup but the RoleProvder (depending on Web or Not) provides a lot of good methods.
I believe a better approach is to use application settings which means you won't ever need to recompile your code if "Customer" or "Branch" values change. Magic values are obviously bad, and this would be a good first step/option getting away from them. Additionally it keeps your values in one place, and I also believe you can reload the settings at runtime without restarting the application (although I haven't tried this myself).
E.g.:
if (role == Properties.Settings.Default.CustomerRole)
{
bCustomer = true;
}
else if (role == Properties.Settings.Default.BranchRole)
{
bIsBranch = true;
}
Eliminate the use of magic strings in your C# code by using the nameof expression
Using the nameof expression, you can retrieve the literal casing of types, classes, structs, properties, methods, functions, fields, arguments, parameters, locals, and more to the casing they appear in the code at compile time. This will not eliminate or solve all your "magic string" problems, but its a good start and worth discussing.
For example, getting the literal casing of an enum value.
public enum ExportType
{
CSV,
Excel
}
nameof Usage
nameof(ExportType.CSV); // "CSV"
nameof(ExportType.Excel); // "Excel"
nameof(ExportType); // "ExportType"
Returns the literal casing of the expression in the argument.
No more "magic strings"
If you are referring the code names of specific type names, classes, etc., strongly consider replacing those fragile magic strings with nameof. You will not fear changing the name of a internal type, or property without fear of breaking the code. Using renaming features IDEs like Visual Studio has will rename all references anywhere in your code base referring to that expression.
Type Safety
This operation is done at compile time. Ultimately, if you are relying on the names of types, classes, etc. in your code, you can introduce compile time type safety via nameof expression into your code when referring to them.
Performance
You can eliminate a lot of reflection in your code as well that gets the names of these objects or types.
Caveats
Getting the name of generic types
nameof(T); // "T"
nameof(TEntity); // "TEntity"
In these cases, you must continue to use reflection to get the name of the type at runtime. typeof(T).Name.
For example:
var enumValuesNames = typeof(ExportType).GetProperties().Select(p => p.Name).ToArray();
Polimorphism is one thing, but using hardcoded strings along your code is not good at all. It's way better to define a variable holding the string and use this variable along the code. This case if you need to change something (believe me you will), you can just change the value of this variable and it's done (less errors too!)
For the sake of maintainability, you should formalize string comparators when possible, either as named constants or as an enumeration. The benefit for the programmer is that you can localize changes. Even when using a refactoring tool, finding all the places a string is used can be tedious and error prone. You may only have one place where you're doing this comparison today, but you or a future maintainer may extend this to other parts of the code. Also, the class itself may grow and need to be broken apart. These things tend to creep up on a program over time.
I would simply declare these strings as constants close to where they're used, but together. Don't bother with a new abstraction like Roles until you know you need it. If the number of roles you need to compare grows, or is needed outside of this class, then you can create a Roles enum or Roles class, depending on the complexity of the comparison.
Also, by using constants, you signal the intended use to the compiler, so you get some minor memory management benefits, which, given your comparison is in a loop, is generally a good practice.
Well, in my opinion it is up to you and it depends on your application design.
I uaully look at it from the positive side- if application works the way it supposed to work, it is all good. IMHO
Related
What is the limitation of
public class A
{
public string Stuff {get;set;}
}
...
repository.GetAll().Select(x=> new A { x.Stuff });
That doesn't work. You have to add
{ Stuff = x.Stuff }
repository.GetAll().Select(x=> new { x.Stuff });
But this works. It creates an anon class with a very similar definition to class A.
Conceptually I don't see a big difference in what is going on here. Anyone shed some light?
The short answer - the C# compiler and language team didn't implement it this way - they either didn't think of it (unlikely) or decided that it was not a good idea....
repository.GetAll().Select(x=> new A { x.Stuff });
That doesn't work. You have to add
This is an object initializer. This works by calling the default constructor on an object, and then matching property names to a value, ie: Stuff = x.Foo, and is really just a shortcut for matching properties, so the syntax is really just "short hand" for:
A tmp = new A();
tmp.Stuff = x.Stuff;
Now, I suppose the compiler team could have assumed that an initialization statement with no left hand side on the equation should search for a matching property where the name matched and the type was implicitly convertible, but I suspect this would fall into the realm of "flirting with the bad idea list" if or when it would've been discussed by the language team. In general, C# is fairly explicit in its syntax, and this would be loosening that up a bit in a way that requires two separate matches (name + type) and would be non-obvious in many scenarios. Since you're working with a public API here (A), it'd also be very easy for a refactoring in either side (A or whatever type "x" is defined as being) to break this completely.
Finally, this also isn't really necessary - if you want an instance of A to be constructed this way, just add a constructor with an overload (which is safer in many ways in any case), and use:
repository.GetAll().Select(x=> new A(x.Stuff));
This makes the intention and meaning very explicit, and takes out the brittle maintainability.
repository.GetAll().Select(x=> new { x.Stuff });
This is doing something completely different - here, you're initializing an anonymous type, and letting the compiler completely determine the type names and types for you. I suspect this was determined to be "safe" since you're never really working with a public API - anonymous types aren't really supposed to "leak" out of the method where it's defined. The risk of having a refactoring change a property name and effectively change values, etc, gets dramatically reduced and isolated to a single method in this case, which in turn keeps this "automatic" naming feature lower risk overall. Also, there isn't an easy alternative here, as you can't define constructors on anonymous types, so there wouldn't be a simple way to have a concise syntax in this case. This adds benefit without introducing a lot of risk.
One possible reasoning: if implicit property assignment would be allowed for real types than change in item of repository (i.e. x.Stuff renamed to x.Other) would cause compile time error in very surprising place as new property no longer match A.Stuff.
I started working on a large c# code base and found the use of a static class with several const ints fields. This class is acting exactly like an enum would.
I would like to convert the class to an actual enum, but the powers that be said no. The main reason I would like to convert it is so that I could have the enum as the data type instead of int. This would help a lot with readability.
Is there any reason to not use enums and to use const ints instead?
This is currently how the code is:
public int FieldA { get; set; }
public int FieldB { get; set; }
public static class Ids
{
public const int ItemA = 1;
public const int ItemB = 2;
public const int ItemC = 3;
public const int ItemD = 4;
public const int ItemE = 5;
public const int ItemF = 6;
}
However, I think it should be the following instead:
public Ids FieldA { get; set; }
public Ids FieldB { get; set; }
I think many of the answers here ignore the implications of the semantics of enums.
You should consider using an enum when the entire set of all valid values (Ids) is known in advance, and is small enough to be declared in program code.
You should consider using an int when the set of known values is a subset of all the possible values - and the code only needs to be aware of this subset.
With regards to refactoring - when time and business contraints allow, it's a good idea to clean code up when the new design/implementation has clear benefit over the previous implementation and where the risk is well understood. In situations where the benefit is low or the risk is high (or both) it may be better to take the position of "do no harm" rather than "continuously improve". Only you are in a position to judge which case applies to your situation.
By the way, a case where neither enums or constant ints are necessarily a good idea is when the IDs represent the identifiers of records in an external store (like a database). It's often risky to hardcode such IDs in the program logic, as these values may actually be different in different environments (eg. Test, Dev, Production, etc). In such cases, loading the values at runtime may be a more appropriate solution.
Your suggested solution looks elegant, but won't work as it stands, as you can't use instances of a static type. It's a bit trickier than that to emulate an enum.
There are a few possible reasons for choosing enum or const-int for the implementation, though I can't think of many strong ones for the actual example you've posted - on the face of it, it seems an ideal candidate for an enum.
A few ideas that spring to mind are:
Enums
They provide type-safety. You can't pass any old number where an enum value is required.
Values can be autogenerated
You can use reflection to easily convert between the 'values' and 'names'
You can easily enumerate the values in an enum in a loop, and then if you add new enum members the loop will automatically take them into account.
You can insert new enunm values without worrying about clashes occurring if you accidentally repeat a value.
const-ints
If you don't understand how to use enums (e.g. not knowing how to change the underlying data type of an enum, or how to set explicit values for enum values, or how to assign the same value to mulitple constants) you might mistakenly believe you're achieving something you can't use an enum for, by using a const.
If you're used to other languages you may just naturally approach the problem with consts, not realising that a better solution exists.
You can derive from classes to extend them, but annoyingly you can't derive a new enum from an existing one (which would be a really useful feature). Potentially you could therefore use a class (but not the one i your example!) to achieve an "extendable enum".
You can pass ints around easily. Using an enum may require you to be constantly casting (e.g.) data you receive from a database to and from the enumerated type. What you lose in type-safety you gain in convenience. At least until you pass the wrong number somewhere... :-)
If you use readonly rather than const, the values are stored in actual memory locations that are read when needed. This allows you to publish constants to another assembly that are read and used at runtime, rather than built into the other assembly, which means that you don't have to recompile the dependant assembly when you change any of the constants in your own assembly. This is an important consideration if you want to be able to patch a large application by just releasing updates for one or two assemblies.
I guess it is a way of making it clearer that the enum values must stay unchanged. With an enum another programmer will just drop in a new value without thinking, but a list of consts makes you stop and think "why is it like this? How do I add a new value safely?". But I'd achieve this by putting explicit values on the enums and adding a clear comment, rather than resorting to consts.
Why should you leave the implementation alone?
The code may well have been written by an idiot who has no good reason for what he did. But changing his code and showing him he's an idiot isn't a smart or helpful move.
There may be a good reason it's like that, and you will break something if you change it (e.g. it may need to be a class due to being accessed through reflection, being exposed through external interfaces, or to stop people easily serializing the values because they'll be broken by the obfuscation system you're using). No end of unnecessary bugs are introduced into systems by people who don't fully understand how something works, especially if they don't know how to test their changes to ensure they haven't broken anything.
The class may be autogenerated by an external tool, so it is the tool you need to fix, not the source code.
There may be a plan to do something more with that class in future (?!)
Even if it's safe to change, you will have to re-test everything that is affected by the change. If the code works as it stands, is the gain worth the pain? When working on legacy systems we will often see existing code of poor quality or just done a way we don't personally like, and we have to accept that it is not cost effective to "fix" it, no matter how much it niggles. Of course, you may also find yourself biting back an "I told you so!" when the const-based implementation fails due to lacking type-safety. But aside from type-safety, the implementation is ultimately no less efficient or effective than an enum.
If it ain't broke, don't fix it.
I don't know the design of the system you're working on, but I suspect that the fields are integers that just happen to have a number of predefined values. That's to say they could, in some future state, contain more than those predefined values. While an enum allows for that scenario (via casting), it implies that only the values the enumeration contains are valid.
Overall, the change is a semantic one but it is unnecessary. Unnecessary changes like this are often a source of bugs, additional test overhead and other headaches with only mild benefits. I say add a comment expressing that this could be an enum and leave it as it is.
Yes, it does help with readability, and no I cannot think of any reason against it.
Using const int is a very common "old school" of programming practice for C++.
The reason I see is that if you want to be loosely coupled with another system that uses the same constants, you avoid being tightly coupled and share the same enum type.
Like in RPC calls or something...
I know there are ways, but is there actually a good way?
At the moment I have a decent Attribute based framework which is working really well with the exception of the verbosity of:
public Variable<int> Value { get { return Get.Int(MethodBase.CurrentMethod()); } }
Picture that, * a few hundred (with setters often too). Is there anyway to get the same result but more concise?
I've considered:
public Variable<int> Value { get { return Get.Int("Value"); } }
and tried:
public Variable<int> Value { get { return Get.Int(() => Value); } }
But as there's many, many of these variables (there is method in this madness, I promise) I'm concerned about obscure bugs arising from the second Value (or string) not matching the first.
So my question is, can anyone think of a neater way to write the above? All I need is the current property name.
My favourite "solution" so far has been:
protected Func<MethodBase> Self = MethodBase.GetCurrentMethod;
public Variable<int> Value { get { return Get.Int(Self()); } }
Which is short, sweet, and pretty to look at.
But alas the JIT kills rules that out as an option. Is there perhaps a way I can rewrite GetCurrentMethod in C#, under a different name? It's a pity StackCrawlMark (which I believe is required) is internal to System.
Alternatively, are there any tools out there that are compatible with ReSharper but perhaps let me view the code through goggles, reducing the verbose MethodBase.GetCurrentMethod to something shorter and sweeter, whilst still compiling exactly the same? (I'd really rather not have a pre-compile fiddling step, but am open to suggestions - one that reduced it all to the property name would be nice).
In short, no. There are various attempts at this, including stack inspection (GetCurrentMethod) and lambda expressions, but ultimately they are all a bit inefficient.
Unless you need need obfuscation, I would just use a string - Get.Int("Value") - this is very unlikely to be a genuine maintenance problem.
The stack inspection approach suffers from potential brittleness if it inlines; if you need obfuscation, I would probably go with Expression. Or just mark the method as "don't obfuscate this name".
Another approach would be to have an abstract base type, and use meta-programming to create the concrete type with the right data/code at runtime, based on inspecting your attributes.
In C# you can refer to values in a class using the 'this' keyword.
class MyClass
{
private string foo;
public string MyMethod()
{
return this.foo;
}
}
While I presume the answer will likley be user preference, is it best practice to use the this keyword within a class for local values?
In the spirit of DRY, I would say this is not a particularly useful practice in general. Almost any use of this can be shortened to an equivalent expression by just removing the this.
One exception is if you have a local parameter which happens to have the same name as another class member; in that case you must distinguish between the two with this. But this is a situation you can easily avoid, by simply renaming the parameter.
I use the this keyword almost only when some member is hiding another, and when I need to pass the current class instance to a method for example:
class Employee
{
private string name;
private string address;
// Pass the current object instance to another class:
public decimal Salary
{
get { return SalaryInfo.CalculateSalary(this); }
}
public Employee(string name, string address)
{
// Inside this constructor, the name and address private fields
// are hidden by the paramters...
this.name = name;
this.address = address;
}
}
I would say it depends on personal preference for your own coding and on the team/company coding standards for your code at work. Personally, I try to keep both personal and "professional" coding standards the same--it reduces confusion, etc.
I prefer to use "this" on all class-level functions and variables. By using "this" you can immediately tell if the item is a class member or not. Also,I prefer to use "base" on members belonging to any base classes. It's not necessary, but it helps readability, esp if someone unfamiliar with your code is reading it.
I prefer this syntax. As the classes get larger and the functions get more complex, it is convenient to be able to read a variable name and know whether or not its an instance var without having to reference another part of the code.
Edit: I realize that if one is having trouble keeping track of variables, then it is probably time to refactor. This is fine in the abstract. So then to clarify: in the case where classes and their relationships aren't simple (and surely they exist) or in code where people have not refactored or followed good guidelines for keeping parameter names different from instance vars, I'll say (imho!) that using 'this' isn't a bad idea for clear code.
You're right - it's very much a preference thing. Of course, many companies enforce a set of coding style guidelines that either require this before any instance member, or require that it not appear. (Does anyone know what the Microsoft FxCop rules for the .NET framework are?)
Personally, I prefer to have this appear before any property, method or field that belongs to an instance. It makes it easier for me to distinguish where it belongs:
A member of an instance of the class (prefixed with this)
A static class member (which I prefix with the name of the class)
A local scope variable (no prefix)
It's more important to me to be able to read my code less ambiguously, than it is to save the 5 characters of this.. For instance, I immediately know that I need to dispose() all the local-scope items that were opened in this scope, and I won't confuse them with the instance-members that shouldn't be disposed. Heck, just for extra laziness points, I use this. as a quick way to access the intellisense list of member of the instance members.
In JavaScript, yes! In languages where it's not necessary, no. Some people do it to make the "memberness" visible to someone reading the code - but your IDE should be able to take care of that by highlighting it.
When VS 2010 comes out, my plan for world peace is to write an extension for the WPF code editor that displays this. in front of every reference to a member variable than doesn't already have that prefix. Then those who need that reminder will no longer need to type it, and those who don't like it can simply not install my extension and can freely delete any unnecessary this. prefixes they see.
I never use it. Mostly, it doesn't matter if a variable is a member or not. Keep your methods small enough that it's no problem to remember which variables are locals, and you won't mave so much trouble remembering which are members.
I use "_" as a prefix for member variables, as it is easy to ignore. But this means there will never be a collision with a local or parameter, so this. is not necessary.
My attitude may be "colored" by the fact that I use ReSharper, whose "color identifiers" mode makes it easier for me to see what's what.
I think that you should always include it if you are specifically referring to the class variable.
The reason for this is if you later on add in a local variable of the same name, you will need to rename all the class variables with this. so why not save your future self some time and hassle?
Recently I asked a question about how to clean up what I considered ugly code. One recommendation was to create an Extension Method that would perform the desired function and return back what I wanted. My first thought was 'Great! How cool are Extensions...' but after a little more thinking I am starting to have second thoughts about using Extensions...
My main concern is that it seems like Extensions are a custom 'shortcut' that can make it hard for other developers to follow. I understand using an Extension can help make the code syntax easier to read, but what about following the voice behind the curtain?
Take for example my previous questions code snippet:
if (entry.Properties["something"].Value != null)
attribs.something = entry.Properties["something"].Value.ToString();
Now replace it with an Extension:
public static class ObjectExtensions
{
public static string NullSafeToString(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
}
and call using the syntax:
attribs.something = entry.Properties["something"].Value.NullSafeToString();
Definetely a handy way to go, but is it really worth the overhead of another class object? And what happens if someone wants to reuse my code snippet but doesn't understand Extension? I could have just as easily used the syntax with the same result:
attribs.something = (entry.Properties["something"].Value ?? string.Empty).ToString()
So I did a little digging and found a couple of articles that talked about the pros/cons of using Extensions. For those inclined have a look at the following links:
MSDN: Extension Methods
Extension Methods Best Practice
Extension Methods
I can't really decide which is the better way to go. Custom Extensions that do what I want them to do or more displayed code to accomplish the same task? I would be really interested in learning what 'real' developers think about this topic...
Personally I think the "problems" of extension method readability are vastly overstated. If you concentrate on making your code easy to read in terms of what it's doing, that's more important most of the time than how it's doing it. If the developer wants to trace through and find out what's actually happening behind the scenes, they can always click through to the implementation.
My main problem with extension methods is their discovery method - i.e. via a specified namespace instead of a specified class. That's a different matter though :)
I'm not suggesting that you put in extension methods arbitrarily, but I would seriously consider how often you need to know how every expression in a method works vs skimming through it to see what it does in broader terms.
EDIT: Your use of terminology may be misleading you slightly. There's no such thing as an "extension object" - there are only "extension methods" and they have to exist in static types. So you may need to introduce a new type but you're not creating any more objects.
[OP] Definetely a handy way to go, but is it really worth the overhead of another class object?
No extra class object is created in this scenario. Under the hood, extension methods are called no differently than a static method. There is an extra metadata entry for the extension method container but that is pretty minimal.
[OP] And what happens if someone wants to reuse my code snippet but doesn't understand Extension Objects?
Then it would be a good time to educate them :). Yes, there is the risk that a new developer may not be comfortable with extension methods to start. But this is hardly an isolated feature. It's being used more and more in all of the code samples I'm seeing internally and on the web. It's something that is definitely worth while for a developer to learn. I don't think it fits into the category of "to esoteric to expect people to know"
The only serious weirdness to deal with in Extension methods are:
They do not have to cause a null reference exception if the left hand side (the object on which it appears you are invoking a method) is null.
can sometimes be useful, but is contrary to expectations as such should be used with extreme caution.
They are not accessible through reflection on the classes/interfaces to which they apply.
generally not a problem, but worth keeping in mind.
Name collisions with other extension methods involve a lengthy resolution rule sequence
if you care the sequence is to prefer:
Extension methods defined inside the current module.
Extension methods defined inside data types in the current namespace or any one of its parents, with child namespaces having higher precedence than parent namespaces.
Extension methods defined inside any type imports in the current file.
Extension methods defined inside any namespace imports in the current file.
Extension methods defined inside any project-level type imports.
Extension methods defined inside any project-level namespace imports.
[OP] And what happens if someone wants to reuse my code snippet but doesn't understand Extension Objects?
The extension methods will not show in the intellisense for the object if the assembly that implements them is not references in the project. Your code snippet will also not compile. That could potentially create a bit of a confusion to the other developer.
If the extension method assembly is referenced, it will show in the intellisense, but it will be not mentioned in the documentation for the object. This could potentially cause a bit of confusion as well.
However, as #JaredPar mentioned, the extension methods as a technique are used more and more and I would expect most of the C# programmers to know about them. Thus, I wound't be too worried about any potential confusion.
C# Extensions is an additional "tool" provided by .Net in order to help you write your code a little bit nicer. Another advantage of them is, that they handle null. Although they seem very usable, I try to use them only in certain cases that will really tidy up my code, because they are not standard coding methods and they stand a little bit seperate from other classes as they have to be in static classes and are static themselves.
Let's say their implementation is a little bit untidy, but their use is made tidier.
It is also important to mention that they only exist in C# and VB.Net (Java doesn't have Extensions). Another important fact is that Extensions have no priority over standard methods, meaning that if a method is implemented in a class with the same name as an extension method on the same class, then the first method is the one that will be called and not the extension method.
Below there are three cases where I often use them, why I use them and alternative solutions that would solve the same problem:
1. To implement specific methods for generic classes:
I have a generic type, let's say a collection List<T>. I want to do a method that applies only to a specific kind of list. Let's say a method that creates a union from a list of strings using a seperator
("A", "B", "C", " sep " --> "A sep B sep C"):
public static string union(this List<string> stringList, String seperator)
{
String unionString = "";
foreach (string stringItem in stringList) {
unionString += seperator + stringItem; }
if (unionString != "") {
unionString = unionString.Substring(seperator.Length); }
return unionString;
}
In case I didn't want to use an extension, I would have to create a new class "StringCollection : List<string>" and implement my method there. This is mainly not a problem and it is actually better in most cases, but not in all cases. If for example you are receiving all your data in lists of strings in many cases, you don't have to convert those lists in StringCollections each time you want to use union, but use an extension instead.
2. To implement methods that need to handle null:
I need a method to convert an object to a string without throwing an exception in case the object is null
public static String toStringNullAllowed(this Object inputObject)
{
if (inputObject == null) { return null; }
return inputObject.ToString();
}
In case I didn't want to use an extension, I would have to create a class (probably static), for example StringConverter, which will do the same job, with more words than a simple myObject.toStringNullAllowed();
3. To extend value types or sealed classes:
Value types such as int, float, string, etc as well as sealed classes (classes that cannot be inherited) cannot be extended through inheritance. Below you can see an example of extending integers to be able to be converted to x-digit Strings (for example integer 34, digits 5 --> "00034"):
public static String toXDigit(this int inputInteger, int x)
{
String xDigitNumber = inputInteger.ToString();
while (xDigitNumber.Length < x) { xDigitNumber = "0" + xDigitNumber; }
return xDigitNumber;
}
Again an alternative solution would be a static class (like a toolbox), let's say "Math".
In that case you would write: Math.toXDigit(a, x);
While with the extension method: a.toXDigit(x);
The extension method looks better and is more understandable, like speaking English
To conclude, I guess the disadvantage of extensions is that their implementation is seperated from standard classes and looks a little bit odd or difficult to programmers that are not used to them, while their advantage is that they offer a more understandable, tidier and encapsulated use of the language.