Sep 18 2014

Tackling the Arrow head Anti-Pattern

Category: .Net | C# | Design Principles ashish sheth @ 00:13

Frequently you will see following type of code in your code base.

if(result != 1)
{
    if(someOtherResult == 101)
    {
        if(anotherValue == 500)
        {
            // do something
        }
    }
    else
    {
        // do some other thing
    }
}

return;

Here the code forms a shape of an arrow-head, as below:

if
    if
        if
            if
                do something
            end
        end
    end
end

If you see, the main logic is deep down into the nested condition, it increases the cyclomatic complexity of the code.

A better version of the same code could be as below:

if(result == 1)
{
    return;
}

if(someOtherResult == 101 && anotherValue == 500)
{
    // do something
    return;
}

// do some other thing

return;

The above code does a number of things to flatten the code and make it better:

  1. Validations are performed first and it returns at the first opportunity.
  2. Multiple nested conditions are combine into one (with “&&”(logical And) operator. If there are multiple expressions forming one such condition, they can be moved to a separate method returning boolean. That method can then be use in the if condition as below:
if(IsValidResult(someOtherResult, anotherResult)
{
    // do something
    return;
}

bool IsValidResult(int someOtherResult, int anotherResult)
{
    if(someOtherResult == 101 && anotherValue == 500)
    {
        return true;
    }
    return false;
}

Tags: , ,

Sep 16 2014

Podcast that I listen

Category: .Net | Learning | miscellaneous ashish sheth @ 00:45

In the big sea of web, you will find many people telling you the podcast that every developers should listen. Here is my list, and yes, I too think these are the podcast every developer(.Net developer) should listen.

  1. .Net Rocks: This is more than a decade old talk show focusing on Microsoft .Net Technologies. Earlier it used to be a weekly show, but now it has three show a week. Apart from covering anything and everything related to .Net, it also covers mobile app development on Android and iOS.
  2. Hanselminutes: This is the show by Scott Hanselman, which focuses on technology including Microsoft .Net Technology.
  3. HerdingCode: This is a show where discussion goes into nitty-gritty of development tasks. As with the above two, not just the .Net technology, but other aspects of Software development practises are also discussed.
  4. Software Engineering Radio: This is a monthly podcast targeted towards not just .Net developers, but to all software developers in general. So it covers topics which include Software Engineering practises, architecture, design patterns, etc. It also has a rather academic feel and many a times the guests include leading researchers in the field of Computer Science.
  5. MS Dev show: This is relatively a new podcast for Microsoft developers focussing fully to Microsoft technology including topics such as Azure/Cloud, Windows, Windows Phone, .Net etc.
  6. IEEE Software’s On Computing: In this podcast Grady Booch reads from his column “On Computing” in the IEEE Software magazine. In this, he talks software’s impact on humanity.
  7. IEEE Software’s Tools of the Trade: This is again the podcast of an on going column in IEEE Software with the same name. In every episode, it covers software tools to be used within a certain aspect of Software Development, such as documentation, debugging, testing, etc.

Let me know what you listen to.

Tags:

Oct 17 2013

Domain Specific Languages - MindMap

Category: ashish sheth @ 06:07

Here is the MindMap that I prepared for Domain Specific Languages after listening to the podcast on the same topic by Martin Fowler on SE Radio.

 

Download Larger size here: Domain Specific Languages.png (164.27 kb)

Tags: ,

Jun 26 2013

History of Computing

Category: miscellaneous ashish sheth @ 23:34

An interesting infographic on history of computing.

Tags:

Jun 17 2011

.Net Guidance Map

Category: .Net | .Net Framework | asp.net ashish sheth @ 18:05

 

I thought these would be very helpful to those who are learning .Net.  J. D. Meier has put up Development Guidance Map for various .Net technologies. This material includes links to technical articles, videos, how-tos, blogs, tutorials, trainings, code samples on various .Net technologies and about everything you might need to know about .net.

Happy Learning.

 

Tags: ,

Sep 16 2010

Use Properties to Encapsulate the Hidden Fields or ViewState in Asp.Net

Category: .Net | asp.net | C# | VS2008 ashish sheth @ 05:16

In asp.net you might be using lot of hidden variables and ViewState to maintain state between page postbacks. This can make your code look cluttered. You can use properties to encapsulate the hidden fields or ViewState.

If you are writing lot of code like this:

if(myHidden.Value == string.Empty)
{
	myHidden.Value = "someValue"; 	
}

someVariable = myHidden.Value

You can use properties to encapsulate the access to myHidden field. For example:

public string MyHiddenFieldValue
{
	get
	{
		if(myHidden.Value == string.Empty)
		{
			myHidden.Value = "someValue"; 	
		}
		return myHidden.Value
	}
	set
	{
		myHidden.Value = value;
	}
}

Then you can access the myHidden field just by the property

someVariable = MyHiddenFieldValue;

Similarly if you are storing some custom values in the ViewState of the page the you can create property for the ViewState also.

public string MyCustomViewState
{
	get
	{
		if(ViewState["MyViewState"] == null)
		{
			ViewState["MyViewState"] = "someValue"; 	
		}
		return ViewState["MyViewState"].ToString();
	}
	set
	{
		ViewState["MyViewState"] = value;
	}
}

Tags: , , ,

Aug 24 2010

VisualStudio ReflectedSchemas folder in ApplicationData

Category: .Net | asp.net | VS2008 ashish sheth @ 23:23

Just now I found out that C:\Documents and Settings\[Username]\Application Data\Microsoft\VisualStudio\9.0\ReflectedSchemas

folder takes lots of space. VS 2008 stores schema files which are dynamically generated when you compile a webcontrol.

To release the space on your drive you can delete the files safely and VisualStudio will re-generate these files whenever needed.

 

For more information see below:

http://blogs.msdn.com/b/mikhailarkhipov/archive/2004/05/14/131949.aspx

http://stackoverflow.com/questions/878345/reflectedschemas-folder-in-the-users-appdata-folder-visual-studio

http://forums.asp.net/t/1264942.aspx

http://www.ureader.com/msg/15364998.aspx

Tags: , ,

Apr 24 2010

Violating Single Resposibility Principle using VisualStudio Region

Single Responsibility Principle (SRP)says that "THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE.". Although this article mentions only about class, I think the SRP also applies to methods within the class: there should never be more than one reason for a method to change.
Visual Studio provides a good way to mark off section of file in the form of "region"so they can be collapsible and the code can be organized. Many people use region in a big method to organize the code. For example:

public void CreeateOrder(/*some parameters*/)
{
	#region Validate the parameters
	//code goes here
	#endregion

	#region create the order
	//insert the order data in the database
	#endregion

	#region create the order item
	//insert the item data in the database
	#endregion
}

Note that not all people use regions like this. Many people use comments instead of regions in this kind of methods.
As you can see this is a clear violation of the single responsibility principle. The method does more than one thing: it validates the order data, create a top level order and create order items. This can certainly be put into separate method.

private bool ValidateOrderData(/*some parameters*/)
{
	#region Validate the parameters
	//code goes here
	#endregion
}

private bool InsertOrder(/*order related parameter*/)
{
	#region create the order
	//insert the order data in the database
	#endregion
}

private bool InsertOrderItem(/*order item related parameter*/)
{
	#region create the order item
	//insert the item data in the database
	#endregion
}

public  void CreateOrder(/*Some parameter*/)
{
	If(ValidateOrder(/*parameter list*/))
	{
		if(InsertOrder(/*order parameter*/))
		{
			InsertOrderItem(/*order item parameter*/);
		}	
	}
}

As you can see, wherever you are using "region" in your method to demarcate the code, you can very well put that code in a separate method.

Tags: , , , ,

Feb 10 2010

Find-n-Replace using Regular Expression in Visual Studio 2008

Category: .Net | VS2008 ashish sheth @ 04:22

Here is a tip how you can convert a multiline text to single line(ie., how to remove newline characters) using regular expression.

Select "Use Regular Expression" in the find-n-replace dialog box. Enter "\n" in the "Find What:" field. Don't provide anything in the "Replace With:" and click the Replace or Replace All button. And voila.. All your contents are in a single lines now.

Here are more resources I found on the net on Find-n-Replace using regular expression:

http://www.aaronlerch.com/blog/2007/03/28/visual-studio-find-and-replace-regular-expressions/
http://msmvps.com/blogs/paulomorgado/pages/visual-studio-find-and-replace-regular-expression-patterns.aspx
http://www.codinghorror.com/blog/archives/000633.html
http://weblogs.asp.net/joelvarty/archive/2008/03/25/find-replace-in-visual-studio-with-regular-expressions-and-variables.aspx
http://developers.de/blogs/scott_munro/archive/2006/07/14/_2700_Find-and-Replace_2700_-with-regular-expressions-in-Visual-Studio.aspx
http://blogs.msdn.com/vseditor/archive/2004/06/18/159515.aspx
http://msdn.microsoft.com/en-us/library/2k3te2cs%28VS.80%29.aspx

Tags: ,

Dec 7 2009

Invoke Google from withing VS 2008

Category: .Net | .Net Framework | C# | CodeProject | VS2008 ashish sheth @ 11:25

As programmers we need to search for many tasks that we want to accomplish. And the F1 key in visual studio does not help because it always launches the local MSDN search, even if MSDN is not installed on the local computer.

Brian Schmitt has provided the code to write a macro to search variouse sites. Here I am describing steps to how you can configure your Visual studio 2008 to invoke google search from within the IDE based on his post.

  • In the VS 2008 IDE, click Alt + F8 to launch the Macro explorer.  It should show you a tree like below at the right hand side of the IDE.

 

 

  • Right Click on theMyMacros project and create a new module named Search. (Alternately, you can goto Tools menu-> Macros -> New Macro command). This will launch the macro editor.
  • Copy and paste the below code in the macro editor. (Code taken from Brian Schmitt's article on Better Visual Studio F1)

 

Imports EnvDTE
Imports System.Web

Public Module Search

#Region "Search Internet Sites"
  Public Const GOOGLE_FORMAT As String = "www.google.com/search?q={0}"
  Public Const STACKOVERFLOW_FORMAT As String = "http://www.stackoverflow.com/search?q={0}"
  Public Const SEARCHDOTNET_FORMAT As String = "http://searchdotnet.com/results.aspx?cx=002213837942349435108:jki1okx03jq&q={0}&sa=Search&cof=FORID:9#1144"
  Public Const MSDN_FORMAT As String = "http://social.msdn.microsoft.com/Search/en-US/?query={0}&ac=8"
   
  Public Sub SearchStackOverflowForSelectedText()
      SearchWebPage(STACKOVERFLOW_FORMAT)
  End Sub
  Public Sub SearchGoogleForSelectedText()
      SearchWebPage(GOOGLE_FORMAT)
  End Sub
  Public Sub SearchSearchDotNetForSelectedText()
      SearchWebPage(SEARCHDOTNET_FORMAT)
  End Sub
      Public Sub SearchMSDNForSelectedText()
      SearchWebPage(MSDN_FORMAT)
  End Sub
  Private Sub SearchWebPage(ByVal SearchURLFormat As String)
      Dim sel As EnvDTE.TextSelection = DTE.ActiveWindow.Selection
      Dim srchTxt As String = sel.Text.Trim
      If srchTxt.Length > 0 Then
          DTE.ItemOperations.Navigate(String.Format(SearchURLFormat, HttpUtility.UrlEncode(srchTxt)))
      End If
  End Sub
#End Region

End Module

 

  • Now the macro is ready (there are four macros created one each for google, stackoverflow, searchdotnet and MSDN). Now we will assign short cut for all the four macros.
  • Go to Tools -> Options -> keyboard. In the “Show command containing” type macro. Or simply scroll through the list box to find the macro we just created.

 

 

  • In the “Press shortcut key” type in the short cut you want (for e.g. Alt + F1, Alt + Shift + F1). Note that if you press just F1, it will replace the existing binding for the F1 key to the MSDN help.
  • In the similar way type in the short cut for other macros.

Tags: ,