Thursday, December 24, 2009

Smart copy-paste

Infamous "Copy-Paste" method produced more lines of code than any company or person in whole world. Despite an enormous number of errors it produced this method was (is and probably will be)the most popular way to create code.

You may either deny this or live with this knowledge. If you accept possibility that your code may be replicated you could prepare and make your code more flexible and less error prone for future reuse.

.NET reflection provides you features to make it easier.

For instance, if you need to add tracing for different methods you could ether

a) add different lines with traces like below
public override void Validate()
{
System.Diagnostics.Trace.WriteLine("Validate");
base.Validate();
}

protected override void OnLoadComplete(EventArgs e)
{
System.Diagnostics.Trace.WriteLine("OnLoadComplete");
base.OnLoadComplete(e);
}

b) or just put a line below to each method:
System.Diagnostics.Trace.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);

P.S. Be aware that the reflection has its own cost, taking time for finding methods dynamically

No comments: