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.
Related
I've always been explicit with my code when using instance members, prefixing them with this. and with static members, prefixing them with the type name.
Roslyn seems not to like this, and politely suggests that you can omit this. and Type. from your code where appropriate...
...so where I would do this... (no pun intended)
public void DoSomethingCool()
{
this.CallAwesomeMethod();
CoolCucumber.DoSomethingLessAewsome();
}
...roslyn suggests I do this...
public void DoSomethingCool()
{
CallAwesomeMethod();
DoSomethingLessAwesome();
}
...however when it comes to using extension methods, it appears that I cannot omit the use of this. for example...
public int GetTotal()
{
// This doesn't work
return Sum(o => o.Value);
// This does
return this.Sum(o => o.Value);
}
Questions:
Why does Roslyn not seem to like explicit use of this. and Type. ?
Why do I need to explicitly use this. for extension methods?
Whilst not strictly part of this question, how do I resolve the discrepancy between Roslyn NOT wanting me to use this. and Type. and StyleCop's analyzers insisting that I use them?
You are correct on this behavior. It has struck me too when using Visual Studio 2015 and I wondered the same as you did. Here are my thoughts on this:
Why does Roslyn not seem to like explicit use of this. and Type.?
It is overhead, and it seems it wants to minimize the code needed. I prefer being explicit in my code though. It is much easier to understand the scope of a variable without having knowing the rest of the code. (Maybe it is also a marketing strategy to let us know about the code analyzers... Or am I thinking too much)
Why do I need to explicitly use this. for extension methods?
I guess this is the rule to supply the first parameter of the extension method, the this. Without providing this it doesn't know the context to call the method on. Actually, the extension method this.Sum(x => x) is actually rewritten as Enumerable.Sum(this, x => x). See the 'need' for this? I guess omitting this is technically possible, but I prefer to be explicit in this case too and I am glad the compiler does too.
this. is a syntax that is provided in C# to resolve ambiguity. For example:
class Square
{
private int size;
public Square(int size)
{
size = size; // How do we differentiate member and parameter?
}
}
So using this. to be explicit is rather an oxymoron, because it is solving a problem caused by a lack of explicitness.
The 'best practice' I would recommend is to write code that is not ambiguous in the first place, thus eliminating the need to use this.. Ambiguity is not only disliked by the compiler but it can be extremely confusing for other programmers trying to read your code.
To achieve disambiguation we need to use different names for things like member variables and parameters. The most common approach (apart from this.) is to use naming prefixes to identify members. Many programmers dislike prefixes but this is usually because they have never seen/used a well designed prefix system - I've described my approach here, and once you get used to it, it is a very powerful way of communicating useful information to yourself and your teammates, and eliminating several common types of bugs caused by ambiguity and mixups.
I am sick to death of writing INPC setters like this:
public string Label
{
get {return _label;}
set
{
if (_label == value) return;
_label = value;
NotifyPropertyChanged(() => Label);
}
}
I'd like to refactor the setting of the field the same way I did INPC; I'd like to pass in the Expression<Func<T>> (and probably the backing field) into something like this:
public string Label
{
get {return _label;}
set
{
SetProperty(() => Label, ref _label, value);
}
}
... and here's the implementation I've come up with in the base class:
public virtual void SetProperty<T>(Expression<Func<T>> expression, ref T field, T value)
{
if (Equals(field, value)) return;
field = value;
NotifyPropertyChanged(expression);
}
... and it seems to work - it compiles, at least <grin />. My question is: am I missing something here? is passing by ref going to accomplish what I'm trying to do?
Yes, it will. You're still going to be a little sick of writing private backing fields and repetitive parts though:
private int _foo;
public int Foo { get{return _foo;}, set { SetProperty("Foo", ref _foo, value); } }
you can't easily escape from that.
INPC works based solely on three things:
needs a NAME of the property
needs to raise the event
and optionally needs to actually store the value, somehow, somewhere
The value-storage is actually not so important. It's important so that the property itself actually behaves, but it's not important for INPC itself. INPC is only about name+eventraising.
Your approach is OK, I'm often tempted to do the same. Writing INPCs implementation is .. soo boring. Technically, what you "invented" (sorry, you're not the first one, I saw at least a dozen similar implementations:) ) isn't really not much of a difference, you just extracted some common code to a method. Not rocket science, but still few lines saved. There is a small "expense" of not being able to tighty control when/how the event is raised. But not much of a pain though, as you can always write manual event-rising and custom conditions when needed.
However, there are some things worth noting:
if (Equals(field, value)) is a good start, but with custom objects it will may require you to override Equals and GetHashCode in many data classes, and it's not always a good idea, especially in WPF and bindings. When passing a Equals/HashCode-overriding dataobject to WPF you must take care and be prepared to see that sometimes the WPF will get confused and sometimes may not update bindings properly (i.e. it may fail to notice that an object was replaced with a new one and leave some bindings bounds to old instance). It's good to make an overload to SetProperty that will taking a IEqualityComparer<T> instead; cosmetics though
in old .Net versions, it was possible to automatically get the NAME from the callstack, but it was very expensive. That's for example why many frameworks (like i.e. XPO) deliberately ceased to do it at some point and required you to provide the name manually. However, since .Net 4.5, the "caller information" is much cheaper. See: this article on [CallerMemberName] and friends and you will be able to remove the "string propertyName". It will cost a bit, but it may be handy for you.
speaking of frameworks, please see Caliburn Micro and it's PropertyChangedBase class. You may find it very useful (Caliburn is available on nuget) or, at least, see the implementation. It uses above-mentioned caller information as default, and also has some nice features like boolean flag to temporarily disabling notifications (IsNotifying). Very useful in some cases.
There is also commercial PostSharp utility, that is able to .. automatically generate all INPC implementations. You attach the PostSharp util as a postbuild step, and it reads attributes from your properties, and if it finds out that some property is marked as to-be-a-INPC, then it rewrites IL of your assembly and adds the INPC implementation to it. What's the gain? [INPC] public int Foo {get;set;} and done. However, please note, PostSharp is commercial utility. You may be able to do such thing yourself if you find an IL weaver, probably based on Cecil from Mono. Or maybe you will find a free util for that too. I don't remember much more, sorry.
EDIT:
Now you mentioned it - you quoted SetProperty(()=> Label, somePocoClass.Label, value) which uses a expressions to find the name of property in a compile-safe way (no strings! refactor/rename works). If you decide to stick to ref, then with some extra work, you can get the ()=>Label expression, analyze it and extract the name, then transform&rewrite that into val => _label = val delegate, and cache that delegate per-field, and then use that cached delegate instead using ref parameter, resulting in: set{ SetProperty(()=>Label, value); }
That's almost as "cool" as it could ever get wit current C# specs. But: Such SetProperty gets really complex, transforming expressions isn't light but can be made almost one-time cost, but delegate cache is not "for free" and you have to cache them, because calculating transformed delegates onthefly is way too heavy. I've tried that, I've seen others trying that, and from my observations, most of people quits. And many coworkers see it as magic and won't try to touch that if something works not right. Cool, fun, but you shouldn't need C# gurus for debugging/patching simple feature like INPC.
EDIT2:
Even simpler way - get some T4 templates to generate the code for you. This is also very popular way to handle that. Or rather, was, like 3-4 years ago. I know some people around who really love T4. Somehow, I not. I felt like writing PHP or first versions of ASP-not-Net.. but don't care about my opinion here - see them and try them for yourself. Many people like it.
By the way, sorry for being chaotic - I've just remembered some bits about IL weaving:
for starters, see this article, very informative, covers all the basics plus more - dynamic proxies, il weaving by Cecil, (...)
the "free PostSharp-like ILweaver" - it's called Fody, on GitHub. See for example this article on INPC auto-implementation via Fody
If you are using .NET 4.5 You can use the CallerMemberName attribute to get the caller, you then don't need to pass in a expression.
Here is the base method I use for INPC
public virtual bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
{
if (Equals(field, value))
return false;
field = value;
OnNotifyPropertyChanged(propertyName);
return true;
}
This is used like
public string Label
{
get {return _label;}
set
{
bool changed = SetProperty(ref _label, value);
if(changed)
{
//Some other code you want to run only on change.
}
}
}
One very nice feature of this pattern is it is compatible with ReSharper's NotifyPropertyChangedInvocator attribute so you can have automatic rt.Click -> "To property with change notification".
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
Are enum types faster/more efficient than string types when used as dictionary keys?
IDictionary<string,object> or IDictionary<enum,object>
As a matter of fact, which data type is most suitable as a dictionary key and why?
Consider the following: NOTE: Only 5 properties for simplicity
struct MyKeys
{
public string Incomplete = "IN";
public string Submitted = "SU";
public string Processing="PR";
public string Completed = "CO";
public string Closed = "CL";
}
and
enum MyKeys
{
Incomplete,
Submitted,
Processing,
Completed,
Closed
}
Which of the above will be better if used as keys in a dictionary!
Certainly the enum version is better (when both are applicable and make sense, of course). Not just for performance (it can be better or worse, see Rashack's very good comment) as it's checked compile time and results in cleaner code.
You can circumvent the comparer issue by using Dictionary<int, object> and casting enum keys to ints or specifying a custom comparer.
I think you should start by focusing on correctness. This is far more important than the minimal difference between the minor performance differences that may occur within your program. In this case I would focus on the proper representation of your types (enum appears to be best). Then later on profile your application and if there is a issue, then and only then should you fix it.
Making code faster later in the process is typically a straight forward process. Take the link that skolima provided. If you had chosen enum, it would have been a roughly 10 minute fix to remove a potential performance problem in your application. I want to stress the word potential here. This was definitely a problem for NHibernate but as to whether or not it would be a problem for your program would be solely determined by the uses.
On the other hand, making code more correct later in the process tends to be more difficult. In a large enough problem you'll find that people start taking dependencies on the side effects of the previous bad behavior. This can make correcting code without breaking other components challenging.
Use enum to get cleaner and nicer code, but remember to provide a custom comparer if you are concerned with performance: http://ayende.com/Blog/archive/2009/02/21/dictionaryltenumtgt-puzzler.aspx .
I would guess that the enum version is faster. Under the hood the dictionary references everything by hashcode. My guess is that it is slower to generate the hashcode for a string. However, this is probably negligibly slower, and is most certainly faster than anything like a string compare. I agree with the other posters who said that an enum is cleaner.
Imagine someone coding the following:
string s = "SomeString";
s.ToUpper();
We all know that in the example above, the call to the “ToUpper()” method is meaningless because the returned string is not handled at all. But yet, many people make that mistake and spend time trying to troubleshoot what the problem is by asking themselves “Why aren’t the characters on my ‘s’ variable capitalized”????
So wouldn’t it be great if there was an attribute that could be applied to the “ToUpper()” method that would yield a compiler error if the return object is not handled? Something like the following:
[MustHandleReturnValueAttribute]
public string ToUpper()
{
…
}
If order for this code to compile correctly the user would have to handle the return value like this:
string s = "SomeString";
string uppers = s.ToUpper();
I think this would make it crystal clear that you must handle the return value otherwise there is no point on calling that function.
In the case of the string example this may not be a big deal but I can think of other more valid reasons why this would come in handy.
What do you guys think?
Thanks.
Does one call a method for its side-effects, for its return value, or for both? "Pure" functions (which have no effects and only serve to compute a return value) would be good to annotate as such, both to eliminate the type of error you describe, as well as to enable some potential optimizations/analyses. Maybe in another 5 years we'll see this happen.
(Note that the F# compiler will warn any time you implicitly ignore a return value. The 'ignore' function can be used when you want to explicitly ignore it.)
If you have Resharper it will highlight things like this for you. Cant recommend resharper highly enough, it has lots of useful IDE additions especially around refactoring.
http://www.jetbrains.com/resharper/
I am not sure that I like this. I have called many a method that returns a value that I choose not to capture. Adding some type of default (the compiler generates a warning when a return value is not handled) just seems wrong to me.
I do agree that something along the suggested lines might help out new programmers but adding an attribute at this point in the game will only affect a very small number of methods relative the the large existing body. That same junior programmer will never get their head around the issue when most of their unhandled return values are not flagged by the compiler.
Might have been nice way back when but the horses are out of the barn.
I'd actually prefer a way to flag a struct or class as [Immutable], and have this handled automatically (with a warning) for methods called without using their return values on immutable objects. This could also protect the object by the compiler from changes after creation.
If the object is truly an immutable object, there really would be no way to handle it. It also could potentially be used by compilers to catch other common mistakes.
Tagging the method itself seems less useful to me, though. I agree with most of the other comments regarding that. If the object is mutable, calling a method could have other side-effects, so the above code could be perfectly valid.
I'm having flashbacks to putting (void) casts on all printf() calls because I couldn't get Lint to shut up about the return value being ignored.
That said, it seems like this functionality should be in some code checker tool rather than the compiler itself.
At least a compiler-warning would be helpful. Perhaps they add something similar for C# 4.0 (Design-By-Contract).
This doesn't warrant for a warning or pragma. There are too many places where it is intended to discard the result, and I'd be quite annoyed getting a warning/error from the compiler just because the method was decorated with some dodge attribute.
This kind of 'warning' should be annotated in the IDE's Editor, like a small icon on the gutter "Warning: Discarding return value" or similar.