Showing posts with label Patterns Practices. Show all posts
Showing posts with label Patterns Practices. Show all posts

Friday, April 6, 2012

“Long method” is one of the most common code smell!

You wont find a single project where long method code smell is not present. I find often this code smell often in my projects, and developers do not deliberately introduce long methods, it just got introduced along the way when we introduce features.

What happen when you find a long method?

  • You wonder why is this method is so long.
  • You try to understand what the code is doing.
  • You start hate the software because its full of lines after line but no end of the method.
  • You lost the track where you ware before.
  • And so on.

You can list hundreds of line like the above listing about long method, the story will go on and on. here is what “Wikipedia” has to say about the long method,

“Long method: a method, function, or procedure that has grown too large.”

Bellow an example of a long method is given

void SolutionLinkBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
var pageName = e.Url.ToString().Split('/').LastOrDefault();
if (IsLinkToTmeTool(pageName))
{
if (pageName != null)
{
var toolName = Regex.Replace(pageName, TMEToolPrefixPattern, "", RegexOptions.IgnoreCase);
e.Cancel = true;
if (PackageLoader.Instance.IsToolAvaiableForCurrentUser(toolName))
{
ToolManager.Value.ActivateToolCommand.Execute(toolName);
}
else
{
new Lazy<IMessageBoxPresenter>().Value.Show(
StringTable.ToolNotAvailableErrorMessageText, StringTable.ToolNotAvailableErrorMessageTitle, DialogButton.OK);
return;
}
}
}
else
{
var queryString = e.Url.Query;
const string pattern = @"^\?.*POwner=(?<Owner>[^&]+)";
var match = Regex.Match(queryString, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
var ownerPackageId = match.Groups["Owner"].Value;
var allowedPackageIds = PackageLoader.Instance.GetAllowedPackageIds().ToList();
if (allowedPackageIds.Contains(ownerPackageId) == false)
{
e.Cancel = true;
new Lazy<IMessageBoxPresenter>().Value.Show( StringTable.PageNotAvailableErrorMessageText, StringTable.PageNotAvailableErrorMessageTitle, DialogButton.OK);
return;
}
}
}
}



Bellow a edited version of the code is given. where the code is refactored with extract method and looks more understandable, even though you can refactor the code to a much simpler version, but this is given there as an example.


void SolutionLinkBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
var pageName = e.Url.ToString().Split('/').LastOrDefault();
if (IsLinkToTmeTool(pageName))
LoadLinkedTool(e, pageName);
else
HandleOtherLink(e);
}

private static void HandleOtherLink(WebBrowserNavigatingEventArgs e)
{
var queryString = e.Url.Query;
const string pattern = @"^\?.*POwner=(?<Owner>[^&]+)";
var match = Regex.Match(queryString, pattern, RegexOptions.IgnoreCase);
if (match.Success == false)
return;
var ownerPackageId = match.Groups["Owner"].Value;
var allowedPackageIds = PackageLoader.Instance.GetAllowedPackageIds().ToList();
if (allowedPackageIds.Contains(ownerPackageId) == false)
{
e.Cancel = true;
DisplayMessage(StringTable.PageNotAvailableErrorMessageText, StringTable.PageNotAvailableErrorMessageTitle);
}
}

private static void DisplayMessage(string message, string title)
{
var messageBoxPresenter = new Lazy<IMessageBoxPresenter>();
messageBoxPresenter.Value.Show(message,title, DialogButton.OK);
}

private void LoadLinkedTool(WebBrowserNavigatingEventArgs e, string pageName)
{
if (pageName != null)
{
var toolName = Regex.Replace(pageName, TMEToolPrefixPattern, "", RegexOptions.IgnoreCase);
e.Cancel = true;
if (PackageLoader.Instance.IsToolAvaiableForCurrentUser(toolName))
ToolManager.Value.ActivateToolCommand.Execute(toolName);
else
DisplayMessage(StringTable.ToolNotAvailableErrorMessageText,StringTable.ToolNotAvailableErrorMessageTitle);
}
}


There are lot of refactoring tips and techniques to handle long method, and this is just the tip of the iceberg, this is just an example you can do many things and there are huge possibilities. Until next time me Md. Masudur Rahman Signning out.

Friday, March 30, 2012

Comment: Yet another code smell

Today we are going to take a look, and discuss on yet another code smell named “Comment”. Sounds like some thing is been told wrong, yes you guys heard right, comment is one kind of smell. The days of well documented code with comment are gone, now time has changed and new agile wind is flowing, as a result comments are now considered as code smell.

How Comment is smell?

Who would have thought that this day will ever come, I have worked with organizations where the developers is been given extra time to put right comment on code, but its history. How comment is smell? its simple the code is not self explanatory, so the code is smelly.

“The idea is to make each and every piece of code self explanatory.”

If your code need comment, you should take careful consideration to refactor your code so that it need no comment at all.

Some Useful Example

In bellow code what ever comment you are seeing is a comment smell.

/// <summary>
/// this method gets a tag or a country
/// </summary>
/// <param name="countryName"></param>
/// <returns></returns>
public static string GetTag(string countryName)
{
//loop through the dictionary key
foreach (string tag in _dictionary.Keys)
{
//search the key
List<string> patternList = _dictionary[tag];
bool found = false;

//if the tag is found return it
found = IsFound(countryName, null, patternList);

if (found)
{
return tag;
}
}
return string.Empty;
}
/// <summary>
///
/// </summary>
/// <param name="title"></param>
/// <param name="description"></param>
/// <param name="patternList"></param>
/// <returns></returns>
private static bool IsFound(string title, string description,
IEnumerable<string> patternList)
{
//traverse in pattern list
foreach (string pattern in patternList)
{
//get rid of . and /.
string searchPattern = pattern.Replace(".", "/.");
string sourceContent = title;
//use regex to find the tag match
bool found = Regex.IsMatch(sourceContent, searchPattern, RegexOptions.IgnoreCase);

if (!found && !string.IsNullOrWhiteSpace(description))
{
sourceContent = description;
found = Regex.IsMatch(sourceContent, searchPattern);
}
if (found)
{
return true;
}
}

return false;
}



Which comment is Allowed?



  • In a function a algorithm is been implemented, for instance a tax calculation procedure, and the procedure is been implemented following a particular rule in a tax book. If you provide the name and reference of the book its not a comment.
  • Class responsibility declaration, its okay to put few lines of comment above a class, and describe its purpose.

Its all about judgment


In the end a programmers judgment matters, we would know when to comment and where not to comment, with little refactor effort we can avoid comment.

Thursday, March 8, 2012

Duplicated Code: The evil twin sister of you favorite function.

Duplicate code is one of the most common code smell we have in our codebase. Its simply we don’t care that much about reusing, we know how to reuse objects, functions, even solutions or component but we are some what careless about removing duplicate code. You would be surprised to know that what amount of duplicated code exists and what are those? Off course there are some obvious techniques to eliminate those.

Here is what Wikipedia has to say about it",

“Duplicate code is a computer programming term for a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a number of reasons.[1] A minimum requirement is usually applied to the quantity of code that must appear in a sequence for it to be considered duplicate rather than coincidentally similar. Sequences of duplicate code are sometimes known as code clones or just clones.”

There are two type’s of duplicate code
  1. Blatant –same code appears in more than one places (Example: two methods, two related classes, two unrelated classes, etc.)
  2. Subtle-looks like different code but serves the same purpose
The following are some examples of duplicate code.
  • character-for-character identical
  • character-for-character identical with white space characters and comments being ignored
  • token-for-token identical
  • token-for-token identical with occasional variation (i.e., insertion/deletion/modification of tokens)
  • functionally identical
How duplicate code find the way into our code base?

The process is more than simple. you knowingly introduce duplicate code, and the possible candidate is

  • copy and pest code and use.
  • write similar code (subtle duplication).
  • rather than using library re-inventing the wheel.

There could be thousands of example that can be put down here, but would not be appropriate, but we have the idea, lets go and find duplicate code and eliminate them, it’s a game and we have to play it with huge interest.

Summery

The bottom line is that we must eliminate duplicate codes, while doing coding just give a breather to your mind and try to find out if there is already a code there or not that do the same purpose, and could it be refactored in such a way so that it could be used by your case also? Most importantly while working with legacy code we need to be more careful and keep our mind open to refactor a lot to eliminate duplicate codes.

References

http://en.wikipedia.org/wiki/Duplicate_code

Wednesday, March 7, 2012

Technical Debt: Avoid it at any cost, other wise it would take all your properties.

Here is a fact that I learned from a real life problem, on of my relative took a huge loan from a bank, the risk was totally calculated but its like he is been paying the interest and principle forever, and its a never ending story, Same thing happens to software if you do technical dept. Here is what wikipedia has to say about technical dept.

“Technical debt (also known as design debt or code debt) is a neologistic metaphor referring to the eventual consequences of poor software architecture and software development within a codebase. The debt can be thought of as work that needs to be done before a particular job can be considered complete. As a change is started on a codebase, there is often the need to make other coordinated changes at the same time in other parts of the codebase or documentation. The other required, but uncompleted changes, are considered debt that must be paid at some point in the future.”

In short, while doing coding we faced a problem and we do a quick and dirty way to solved it and give a on time delivery. Later you are coming back to the same place again and again to write more dirty code to over come the scenarios its failing.

What a stupid thing to do, if only your higher stakeholders known, that, the two hour job eventually will take huge amount of development time, they would have hired people who would be monitoring so that no technical debt is been introduced in the code base.

if you want to know more about this topic please go to http://en.wikipedia.org/wiki/Technical_debt. There is a significant amount of information is there to help you out.

Suggestions

What to do?

Never ever introduce technical debt.

If a problem takes good amount to time and a significant amount of architectural change talk to your higher authorities, make them understand that this would take time and a quick and dirty solution will lead them more development effort in future.

Take calculated risk

Always follow 80/20 principle if the feature is been used by only 20 % of the users and its unlikely that this would cause any immediate breakdown.  But don’t forget to get back to it quickly and then refactor it, other wise you would soon forget about it.

General Suggestion

  • Refactor as you go deep in to the code.
  • Try to use design pattern
  • Be communicative with the team
  • Always follow good process of development (For Example : Agile: Scrum, Kanban)
  • Most important try to have some test coverage.

In an ideal development world there is no technical debt, but still there is in real world. so we got handle it correctly, until next time happy coding.

Friday, February 17, 2012

“Dead code”, a very common code smell.

Remove dead code from you code files

Today we are going to take a look at a simple code smell named “Dead code”. You would be surprised to know how many dead code exists in your project when you take a close look at the project file. of course you wouldn’t know just by looking at it. some of them are pretty hard to find.

What is dead code?

The code that is no longer needed and no longer used by any function or procedure is a dead code.

The Tool

The easiest way to identify the dead code is to use a tool that will save thousands of milliseconds by providing some indication that the code is no longer used. And I am talking about none other than Resharper, the awesome tool that solve lot of our problem and yet so cheap!. Of course I am talking about only Microsoft Platform, eclipse has its owe set of cool feature that have all the refactor and code notation. But if you are a “IntelliJ IDEA” user, then probably you have all the necessary help you need.

Simple dead code

The bellow screen shot shows some portion of the code file and the red rectangles are dead code. that’s the simple version I would say. If you have Resharper plugin with your VS2010 IDE this tool would grayed out the dead to let user know what are the dead codes.

image

Here is possible things that can be dead code.

  • private variables
  • private methods
  • private properties
  • redundant quantifier
  • redundant directives
  • public methods
  • public properties
  • Even a class
  • Unused method parameter
  • Unused local variable

Remove dead code Techniques

#1 :  Use the full cleanup .

Just right click on your code file and select full cleanup from context menu. This would remove lots of problem from your code.

image

image

Yet you have some dead code after full clean up. you can follow the bar of VS code window and click imageon each item to remove the problems. to remove the dead field or method just put the cursor on the gray text and then hit key ctrl+Enter this will pop up a tool window with some option menu with it. Select Remove unused method to get rid of the method.

image

 

#2 : Find the uses of the method

This is a hard part and can lead to a chain where you would get rid of a couple of methods Tree. How do you quickly identify that the procedure is unused. Its pretty easy to identify the private methods and fields as its been grayed out by the reharper. but what about public method and public properties or fields.

Generally when you get rid of a dead code for instance a private method, any method that is been used in that private method also become dead if the method is not been used some where else, luckily reharper automatically detects it and gray out the methods in turn.

Now lets talk about public methods, first check if the method has a reference or not. To do that simply right click on a method and select “find usages” if it shows that it does not have any uses, you can probably get rid of the public method,field and property.

image

One easy way to use the modifier, change the modifier from public to private. if you don’t see any compile error it means this method would be grayed out. so no uses. But this fails in case of WCF Service interfaces. Since the service is been uses some where else and all methods that we want to expose needs to be public. But that is the whole idea of a WCF service, so we would expose only necessary methods That would be used.

After find Usages if any usages found it would be listed on a tool window. Just click on the item. It would take the user to the method or line of code where its been used. Check again if that method has any Usage. And so on , I think you got the idea what needs to be done here to identify where is the dead code.

image

A common problem of our code is that is the class is been used anywhere? One simple technique is simply exclude the class from the project and then build the project see if it creates any compile error or not. but we can also use find usage technique with the class file also, to find if its been used some where or not.

Always use “Safe Delete”

While removing class or methods from project always use safe delete operation of reharper, this would help us not to create unnecessary problem for our codes. To use safe delete simple right click on the object you want to delete, i.e. parameter, variable , method and class. Then select Safe Delete from context menu, or you can also use Ctrl+R, D to lunch the safe delete window.

image

When the window pop’s up you can also check enable undo if you don’t feel safe. Then click next to get rid of the code. If the code that we ware trying to delete has some reference some where it would not perform the operation rather it would show a error window showing where the usage is.

image

There are many more thing to discuss about dead code. And couldn’t be completed in a single post. I would try to put together different platform in future.

Thursday, February 9, 2012

Common Refactoring Techniques

Here are some examples of code refactoring; some of these may only apply to certain languages or language types. A longer list can be found in Fowler's Refactoring book and on Fowler's Refactoring Website.

  •     Techniques that allow for more abstraction
    • Encapsulate Field – force code to access the field with getter and setter methods
    • Generalize Type – create more general types to allow for more code sharing
    • Replace type-checking code with State/Strategy
    • Replace conditional with polymorphism
  • Techniques for breaking code apart into more logical pieces
    • Extract Method, to turn part of a larger method into a new method. By breaking down code in smaller pieces, it is more easily understandable. This is also applicable to functions.
    • Extract Class moves part of the code from an existing class into a new class.
  • Techniques for improving names and location of code
    • Move Method or Move Field – move to a more appropriate Class or source file
    • Rename Method or Rename Field – changing the name into a new one that better reveals its purpose
    • Pull Up – in OOP, move to a superclass
    • Push Down – in OOP, move to a subclass

Tools that can be used to enhance refactoring technique with visual studio 2005~20xx

Among the above tools Resharper is most popular.

References:

  1. http://en.wikipedia.org/wiki/Code_refactoring
  2. http://msdn.microsoft.com/en-us/library/ms379618%28VS.80%29.aspx

Wednesday, September 14, 2011

Event Aggregator in Prism 4.0 with MEF

Today I am going to share a simple trick about Event Aggregator, I was working in one of my project and I was trying to use event aggregator. I was stopped by a show stopper exception, and couldn’t find out what is going on. here is the expectation that I had.

image

Looks familiar? I bet some of you had encounter it. well the solution is pretty easy while subscribing an event you got to also set your thread option and off course a true value to keep reference alive parameter of the subscribe method.

public InboxViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
var myDemoEvent = _eventAggregator.GetEvent<MyDemoEvent>();
if (myDemoEvent != null)
myDemoEvent.Subscribe(OnEvent,ThreadOption.UIThread,true);
}
private void OnEvent(MyCustomObject obj)
{
//do some thing over here
}



I already assume that you know about how to make a custom event for Event aggregator. If not here is a code sample. The main catch is that it have to be inherited from CompositePresentationEvent<>. The code sample is given bellow.

 public class MyDemoEvent:CompositePresentationEvent<MyCustomObject>
{
//here goes thing about your cutom event
}

public class MyCustomObject
{
//here goes you custom event payload stuff
}



Till next post happy programming.

Sunday, September 11, 2011

Prism 4.0 is a complete application development framework for silverlight and WPF.

Today I am going to talk about Prism 4.0 today. We had a very satisfactory history of developing a large scale smart client application with prism 2.0. Prism 4.0 released on November 2010. And its more evolved and now also support application development with Silver-light.

As dependency container prism 4.0 have both unity and MEF. So user can choose to use anyone of them. Unity is been introduced since the first release of WPF Composite application block aka Prism.

You can download the prism distribution from code plex. http://compositewpf.codeplex.com/.

You can find a complete developer guide here http://msdn.microsoft.com/en-us/library/gg406140.aspx.
Bellow I have put down a screen shot of the distribution.


we have complete set of tutorial and samples in the downloadable distribution to get started with prism.
I myself recommend MEF samples and find it very useful to use.

I am planing to write a series of post for both enterprise library 5.0 and Prism. Till next post, this is Munna Signing out.