What complex refactoring features do you wish there were? - c#

Tools like CodeRush and Resharper offer lots of simple refactorings, such as 'Rename Variable'. But if you could have any refactoring feature at all (no matter how complex), what would it be?
(I know, everyone wants a 'make program perfect' refactoring, but let's be realistic here.)

I wouldn't particularly like a specific feature. I'd prefer improvements on the existing built in functions. I.e. I'd like to declare how my code is refactored, i.e. naming conventions and variable positioning. As an example, I'd like my get/set properties to be as follows:
public string Foo
{
get
{
return foo;
}
set
{
_foo = value;
}
}
private string _foo;
But visual studios does it in some crazy way I cant stand and that doesn't meet our coding standards.
It'd be good if every existing refactoring method didn't feel as though it'd been written by a different person with their own ideas.

Move this method to library XYZ

Add the reference and using needed to make (this class reference/method call) work

Related

How to avoid property recursion

This hit me recently on a project I was working on. Most people are familiar with property recursion:
public int Test
{
get { return this.test; }
set { this.Test = value; }
}
private int test;
You accidentally put an upper-case T in this setter, and you've opened yourself up to a StackoverflowException. What's worse is if you've not defined it, often visual studio will auto-correct the casing for you to the invalid state.
I did something similar however in a constructor recently:
public TestClass(int test)
{
this.Test = Test;
}
Unfortunately here you don't get a StackOverflowException, now you've got a programming error. In my case this value was passed to a WebService that instead used a default value (which wasn't 0) which caused me to miss the fact I had incorrectly assigned it. Integration tests all passed because this service didn't say
"Hey you forgot this really important field!"
What steps can I take to avoid this sort of behaviour? I've always been advised against defining variables like the following, and I don't like them personally, but I can't think of any other options:
private int _test;
private int mTest;
EDIT
Reasons that the underscore or m prefix are undesirable normally that I can think of are:
Readability
Slightly more difficult to scroll through members if you're inheriting from 3rd party classes as you get a mix of styles.
Best way is to use "Auto implemented properties" here.
public int Test { get; set; }
If not possible to use "Auto implemented properties" for some reason use _ prefix(I don't prefer though).
If you also don't prefer to use some prefixes, then you have other option. You don't have to write the property code by hand. Let the IDE do it for you; that way you can avoid careless mistakes. (I don't know how I missed this in original answer)
Just type
private int test;
Select the field, Right click Refactor->Encapsulate Field. IDE will generate property snippet for you as below.
public int Test
{
get { return test; }
set { test = value; }
}
You don't need to bother clicking the context menu. If you prefer keyboard, shortcut is Ctrl + R + E.
Or get a Resharper, It will point your silly mistake immediately.
Integration tests all passed
Then they weren't exhaustive enough tests. If there's an error that wasn't discovered by the tests, then you've got another test to write.
That's really the only automated solution here. The compiler isn't going to complain, because the code is structurally and syntactically correct. It's just not logically correct at runtime.
You can define naming standards, even use tools like StyleCop to attempt to enforce those standards. That would probably allow you to cover a lot, though it's not an ironclad solution and errors can still get through. Personally I agree with you that decorating variable names is unsightly in the code. Perhaps in some cases it's a valid tradeoff?
Ultimately, automated tests are your defense against these kinds of errors. At its simplest, if an error gets through your tests and into production then the response should be:
Write a test to reproduce the error.
Fix the error.
Use the test to validate the fix.
Granted, that only covers that one case, not every property definition in your code. But if this is happening a lot then you may have a personnel problem and not a technical problem. Somebody on the team is, well, sloppy. The solution to that problem may not be a technical one.
Use code snippets.
For every property backed by a private field, use a custom code snippet you have created, instead of writing it up from scratch or letting IntelliSense do the job (poorly).
After all, this problem is about conventions and discipline, rather than language design. The case sensitive nature of C# and the subperfect code completion in Visual Studio are the reason we make these mistakes, not our lack of knowledge and design.
You best bet here is to eliminate the chance of accidents and having a predefined way of writing these repetitive things correctly is the best way to go. It also is much more automated compared to remembering conventions and enforcing them by hand.
There is a default code snippet in Visual Studio for this. Type propfull and hit Tab, then specify the instance variable name and the property name and you're good to go.
In some cases you cannot get around setters and getters. But maybe you don't need the setters and getters if you follow the Tell, Don't Ask principle? It basically says to prefer having the object that has the data do the work, not some other object query a lot from the data object, make decisions, and then write data back to the data object. See http://martinfowler.com/bliki/TellDontAsk.html
Could you not just write a test to cover this?
int constructorValue = 4;
TestClass test = new TestClass(constructorValue);
Assert.Equals(test.Test, constructorValue);
You may not want to write tests immediately to cover yourself from future wobbles, but you've found a bug, why not protect yourself from it again?
For the record, if I need a private field to store the value for a pulic getter/setter, I always underscore it. There's just something an underscore that screams privacy!
public string Test
{
get { return _test; }
set { _test = value; }
}
private string _test;

Is there a way to protect Unit test names that follows MethodName_Condition_ExpectedBehaviour pattern against refactoring?

I follow the naming convention of
MethodName_Condition_ExpectedBehaviour
when it comes to naming my unit-tests that test specific methods.
for example:
[TestMethod]
public void GetCity_TakesParidId_ReturnsParis(){...}
But when I need to rename the method under test, tools like ReSharper does not offer me to rename those tests.
Is there a way to prevent such cases to appear after renaming? Like changing ReSharper settings or following a better unit-test naming convention etc. ?
A recent pattern is to groups tests into inner classes by the method they test.
For example (omitting test attributes):
public CityGetterTests
{
public class GetCity
{
public void TakesParidId_ReturnsParis()
{
//...
}
// More GetCity tests
}
}
See Structuring Unit Tests from Phil Haack's blog for details.
The neat thing about this layout is that, when the method name changes,
you'll only have to change the name of the inner class instead of all
the individual tests.
I also started with this convertion, however ended up with feeling that is not very good. Now I use BDD styled names like should_return_Paris_for_ParisID.
That makes my tests more readable and alsow allows me to refactor method names without worrying about my tests :)
I think the key here is what you should be testing.
You've mentioned TDD in the tags, so I hope that we're trying to adhere to that here. By that paradigm, the tests you're writing have two purposes:
To support your code once it is written, so you can refactor without fearing that you've broken something
To guide us to a better way of designing components - writing the test first really forces you to think about what is necessary for solving the problem at hand.
I know at first it looks like this question is about the first point, but really I think it's about the second. The problem you're having is that you've got concrete components you're testing instead of a contract.
In code terms, that means that I think we should be testing interfaces instead of class methods, because otherwise we expose our test to a variety of problems associated with testing components instead of contracts - inheritance strategies, object construction, and here, renaming.
It's true that interfaces names will change as well, but they'll be a lot more rigid than method names. What TDD gives us here isn't just a way to support change through a test harness - it provides the insight to realise we might be going about it the wrong way!
Take for example the code block you gave:
[TestMethod]
public void GetCity_TakesParidId_ReturnsParis(){...}
{
// some test logic here
}
And let's say we're testing the method GetCity() on our object, CityObtainer - when did I set this object up? Why have I done so? If I realise GetMatchingCity() is a better name, then you have the problem outlined above!
The solution I'm proposing is that we think about what this method really means earlier in the process, by use of interfaces:
public interface ICityObtainer
{
public City GetMatchingCity();
}
By writing in this "outside-in" style way, we're forced to think about what we want from the object a lot earlier in the process, and it becoming the focus should reduce its volatility. This doesn't eliminate your problem, but it may mitigate it somewhat (and, I think, it's a better approach anyway).
Ideally, we go a step further, and we don't even write any code before starting the test:
[TestMethod]
public void GetCity_TakesParId_ReturnsParis
{
ICityObtainer cityObtainer = new CityObtainer();
var result = cityObtainer.GetCity("paris");
Assert.That(result.Name, Is.EqualTo("paris");
}
This way, I can see what I really want from the component before I even start writing it - if GetCity() isn't really what I want, but rather GetCityByID(), it would become apparent a lot earlier in the process. As I said above, it isn't foolproof, but it might reduce the pain for this particular case a bit.
Once you've gone through that, I feel that if you're changing the name of the method, it's because you're changing the terms of the contract, and that means you should have to go back and reconsider the test (since it's possible you didn't want to change it).
(As a quick addendum, if we're writing a test with TDD in mind, then something is happening inside GetCity() that has a significant amount of logic going on. Thinking about the test as being to a contract helps us to separate the intention from the implementation - the test will stay valid no matter what we change behind the interface!)
I'm late, but maybe that Can be still useful. That's my solution (Assuming you are using XUnit at least).
First create an attribute FactFor that extends the XUnit Fact.
public class FactForAttribute : FactAttribute
{
public FactForAttribute(string methodName = "Constructor", [CallerMemberName] string testMethodName = "")
=> DisplayName = $"{methodName}_{testMethodName}";
}
The trick now is to use the nameof operator to make refactoring possible. For example:
public class A
{
public int Just2() => 2;
}
public class ATests
{
[FactFor(nameof(A.Just2))]
public void Should_Return2()
{
var a = new A();
a.Just2().Should().Be(2);
}
}
That's the result:

C# How to get the number of the method calls?

In Java - basing on the Aspects - we can get the number of the function calls, e.g.:
SomeClass sc = new SomeClass();
sc.m1();
sc.m1();
int no = sc.getNumberOfCalls("m1");
System.out.println(no); //2
How to do it in C# ?
this is another option by using external product..In .NET
The canonical, easiest way would probably be to simply use a profiler application. Personally I have good experiences with jetBrains dotTrace, but there are more out there.
Basically what you do is you let the profiler fire up your app, and it will keep track of all method calls in your code. It will then show you how much time was spent executing those methods, and how many times they are called.
Assuming your reason for wanting to know this is actually performance, I think it's a good idea to look at a profiler. You can try to optimize your code by doing an educated guess to where the bottlenecks are, but if you use a profiler you can actually measure that. And we all know, measure twice, cut once ;-)
or
this is also good option
AQtime does that with no difficulty.
How about simply do this in your class ?
public class SomeClass
{
private int counter = 0;
public void m1()
{
counter++;
}
public int getMethodCalls()
{
return counter;
}
}
This capability is not built into .NET. However, you can use any one of the mock object frameworks to do this. For example, with RhinoMocks you can set the number of expected number of calls to a method and check it.
You can also accomplish this if you create a dynamic, runtime proxy for your objects and have your proxy keep track. That might make the cure worse than the disease though!
-- Michael
I believe theres not suach a built in feature for that, so you may wanna code something this way:
public class SomeClass
{
public Int32 MethodCallCount { get; set; }
public void Method()
{
this.MethodCallCount++;
//Your custom code goes here!
}
}
If you wanna go deeper you may want look for AOP (aspect oriented programming) interceptors! - if so you may start looking for Spring.NET framework!
If you are within a test scenario the most apropriate solution would be using a mock framework for that.
You can also do Aspects in C#.
Spring.Net
EOS

Easiest way to inject code to all methods and properties that don't have a custom attribute

There are a a lot of questions and answers around AOP in .NET here on Stack Overflow, often mentioning PostSharp and other third-party products. So there seems to be quite a range of AOP optons in the .NET and C# world. But each of those has their restrictions, and after downloading the promising PostSharp I found in their documentation that 'methods have to be virtual' in order to be able to inject code (edit: see ChrisWue's answer and my comment - the virtual constraint must have been on one of the contenders, I suppose). I haven't investigated the accuracy of this statement any further, but it's categoricality made me return back to Stack Overflow.
So I'd like to get an answer to this very specific question:
I want to inject simple "if (some-condition) Console.WriteLine" style code to every method and property (static, sealed, internal, virtual, non-virtual, doesn't matter) in my project that does not have a custom annotation, in order to dynamically test my software at run-time. This injected code should not remain in the release build, it is just meant for dynamic testing (thread-related) during development.
What's the easiest way to do this? I stumbled upon Mono.Cecil, which looks ideal, except that you seem to have to write the code that you want to inject in IL. This isn't a huge problem, it's easy to use Mono.Cecil to get an IL version of code written in C#. But nevertheless, if there was something simpler, ideally even built into .NET (I'm still on .NET 3.5), I'd like to know. [Update: If the suggested tool is not part of the .NET Framework, it would be nice if it was open-source, like Mono.Cecil, or freely available]
I was able to solve the problem with Mono.Cecil. I am still amazed how easy to learn, easy to use, and powerful it is. The almost complete lack of documentation did not change that.
These are the 3 sources of documentation I used:
static-method-interception-in-net-with-c-and-monocecil
Migration to 0.9
the source code itself
The first link provides a very gentle introduction, but as it describes an older version of Cecil - and much has changed in the meantime - the second link was very helpful in translating the introduction to Cecil 0.9. After getting started, the (also not documented) source code was invaluable and answered every question I had - expect perhaps those about the .NET platform in general, but there's tons of books and material on that somewhere online I'm sure.
I can now take a DLL or EXE file, modify it, and write it back to disk. The only thing that I haven't done yet is figuring out how to keep debugging information - file name, line number, etc. currently get lost after writing the DLL or EXE file. My background isn't .NET, so I'm guessing here, and my guess would be that I need to look at mono.cecil.pdb to fix that. Somewhere later - it's not that super important for me right now. I'm creating this EXE file, run the application - and it's a complex GUI application, grown over many years with all the baggage you would expect to find in such a piece of, ahem, software - and it checks things and logs errors for me.
Here's the gist of my code:
DefaultAssemblyResolver assemblyResolver = new DefaultAssemblyResolver();
// so it won't complain about not finding assemblies sitting in the same directory as the dll/exe we are going to patch
assemblyResolver.AddSearchDirectory(assemblyDirectory);
var readerParameters = new ReaderParameters { AssemblyResolver = assemblyResolver };
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyFilename, readerParameters);
foreach (var moduleDefinition in assembly.Modules)
{
foreach (var type in ModuleDefinitionRocks.GetAllTypes(moduleDefinition))
{
foreach (var method in type.Methods)
{
if (!HasAttribute("MyCustomAttribute", method.method.CustomAttributes)
{
ILProcessor ilProcessor = method.Body.GetILProcessor();
ilProcessor.InsertBefore(method.Body.Instructions.First(), ilProcessor.Create(OpCodes.Call, threadCheckerMethod));
// ...
private static bool HasAttribute(string attributeName, IEnumerable<CustomAttribute> customAttributes)
{
return GetAttributeByName(attributeName, customAttributes) != null;
}
private static CustomAttribute GetAttributeByName(string attributeName, IEnumerable<CustomAttribute> customAttributes)
{
foreach (var attribute in customAttributes)
if (attribute.AttributeType.FullName == attributeName)
return attribute;
return null;
}
If someone knows an easier way how to get this done, I'm still interested in an answer and I won't mark this as the solution - unless no easier solutions show up.
I'm not sure where you got that methods have to be virtual from. We use Postsharp to time and log calls to WCF service interface implementations utilizing the OnMethodBoundaryAspect to create an attribute we can decorate the classes with. Quick Example:
[Serializable]
public class LogMethodCallAttribute : OnMethodBoundaryAspect
{
public Type FilterAttributeType { get; set; }
public LogMethodCallAttribute(Type filterAttributeType)
{
FilterAttributeType = filterAttributeType;
}
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
if (!Proceed(eventArgs)) return;
Console.WriteLine(GetMethodName(eventArgs));
}
public override void OnException(MethodExecutionEventArgs eventArgs)
{
if (!Proceed(eventArgs)) return;
Console.WriteLine(string.Format("Exception at {0}:\n{1}",
GetMethodName(eventArgs), eventArgs.Exception));
}
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
if (!Proceed(eventArgs)) return;
Console.WriteLine(string.Format("{0} returned {1}",
GetMethodName(eventArgs), eventArgs.ReturnValue));
}
private string GetMethodName(MethodExecutionEventArgs eventArgs)
{
return string.Format("{0}.{1}", eventArgs.Method.DeclaringType, eventArgs.Method.Name);
}
private bool Proceed(MethodExecutionEventArgs eventArgs)
{
return Attribute.GetCustomAttributes(eventArgs.Method, FilterAttributeType).Length == 0;
}
}
And then us it like this:
[LogMethodCallAttribute(typeof(MyCustomAttribute))]
class MyClass
{
public class LogMe()
{
}
[MyCustomAttribute]
public class DoNotLogMe()
{
}
}
Works like a charm without having to make any methods virtual in Postsharp 1.5.6. Maybe they have changed it for 2.x but I certainly don't hope so - it would make it way less useful.
Update: I'm not sure if you can easily convince Postsharp to only inject code into certain methods based on with which attributes they are decorated. If you look at this tutorial it only shows ways of filtering on type and method names. We have solved this by passing the type we want to check on into the attribute and then in OnEntry you can use reflection to look for the attributes and decide whether to log or not. The result of that is cached so you only have to do it on the first call.
I adjusted the code above to demonstrate the idea.

C# Extension Methods - How far is too far?

Rails introduced some core extensions to Ruby like 3.days.from_now which returns, as you'd expect a date three days in the future. With extension methods in C# we can now do something similar:
static class Extensions
{
public static TimeSpan Days(this int i)
{
return new TimeSpan(i, 0, 0, 0, 0);
}
public static DateTime FromNow(this TimeSpan ts)
{
return DateTime.Now.Add(ts);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(
3.Days().FromNow()
);
}
}
Or how about:
static class Extensions
{
public static IEnumerable<int> To(this int from, int to)
{
return Enumerable.Range(from, to - from + 1);
}
}
class Program
{
static void Main(string[] args)
{
foreach (var i in 10.To(20))
{
Console.WriteLine(i);
}
}
}
Is this fundamentally wrong, or are there times when it is a good idea, like in a framework like Rails?
I like extension methods a lot but I do feel that when they are used outside of LINQ that they improve readability at the expense of maintainability.
Take 3.Days().FromNow() as an example. This is wonderfully expressive and anyone could read this code and tell you exactly what it does. That is a truly beautiful thing. As coders it is our joy to write code that is self-describing and expressive so that it requires almost no comments and is a pleasure to read. This code is paramount in that respect.
However, as coders we are also responsible to posterity, and those who come after us will spend most of their time trying to comprehend how this code works. We must be careful not to be so expressive that debugging our code requires leaping around amongst a myriad of extension methods.
Extension methods veil the "how" to better express the "what". I guess that makes them a double edged sword that is best used (like all things) in moderation.
First, my gut feeling: 3.Minutes.from_now looks totally cool, but does not demonstrate why extension methods are good. This also reflects my general view: cool, but I've never really missed them.
Question: Is 3.Minutes a timespan, or an angle?
Namespaces referenced through a using statement "normally" only affect types, now they suddenly decide what 3.Minutes means.
So the best is to "not let them escape".
All public extension methods in a likely-to-be-referenced namespace end up being "kind of global" - with all the potential problems associated with that. Keep them internal to your assembly, or put them into a separate namespace that is added to each file separately.
Personally I like int.To, I am ambivalent about int.Days, and I dislike TimeSpan.FromNow.
I dislike what I see as a bit of a fad for 'fluent' interfaces that let you write pseudo English code but do it by implementing methods with names that can be baffling in isolation.
For example, this doesnt read well to me:
TimeSpan.FromSeconds(4).FromNow()
Clearly, it's a subjective thing.
I agree with siz and lean conservative on this issue. Rails has that sort of stuff baked in, so it's not really that confusing ever. When you write your "days" and "fromnow" methods, there is no guarantee that your code is bug free. Also, you are adding a dependency to your code. If you put your extension methods in their own file, you need that file in every project. In a project, you need to include that project whenever you need it.
All that said, for really simple extension methods (like Jeff's usage of "left" or thatismatt's usage of days.fromnow above) that exist in other frameworks/worlds, I think it's ok. Anyone who is familiar with dates should understand what "3.Days().FromNow()" means.
I'm on the conservative side of the spectrum, at least for the time being, and am against extension methods. It is just syntactic sugar that, to me, is not that important. I think it can also be a nightmare for junior developers if they are new to C#. I'd rather encapsulate the extensions in my own objects or static methods.
If you are going to use them, just please don't overuse them to a point that you are making it convenient for yourself but messing with anyone else who touches your code. :-)
Each language has its own perspective on what a language should be. Rails and Ruby are designed with their own, very distinct opinions. PHP has clearly different opinions, as does C(++/#)...as does Visual Basic (though apparently we don't like their style).
The balance is having many, easily-read, built-in functions vs. the nitty-gritty control over everything. I wouldn't want SO many functions that you have to go to a lookup every time you want to do anything (and there's got to be a performance overhead to a bloated framework), but I personally love Rails, because what it has saves me a lot of time developing.
I guess what I'm saying here is that if you were designing a language, take a stance, go from there, and build in the functions you (or your target developer would) use most often.
My personal preference would be to use them sparingly for now and to wait to see how Microsoft and other big organizations use them. If we start seeing a lot of code, tutorials, and books use code like 3.Days().FromNow() it makes use it a lot. If only a small number of people use it, then you run the risk of having your code be overly difficult to maintain because not enough people are familiar with how extensions work.
On a related note, I wonder how the performance compares between a normal for loop and the foreach one? It would seem like the second method would involve a lot of extra work for the computer, but I'm not familiar enough with the concept to know for sure.

Categories

Resources