Archive for the ‘Everyday coding’ Category

Levels of reuse in Software Development

Tuesday, June 1st, 2010

One of the promises of object-orientation is reuse. Developing new software systems is expensive, and maintaining them is even more expensive. Reuse is therefore sensible in both business and technology perspectives.

With assistance of Erich Gamma, I have identified four levels of reuse.

First level of reuse: Copy/paste

Duplicating code or functionality makes it easy to reuse it. It’s a real timesaver at first, but keeping all the duplicates up-to-date and maintaining them is horrifying task. Not to mention the problems when forgetting to update one or more duplicates…

“Copy and paste programming is a pejorative term to describe highly repetitive computer programming code apparently produced by copy and paste operations. It is frequently symptomatic of a lack of programming competence, or an insufficiently expressive development environment, as subroutines or libraries would normally be used instead. In certain contexts it has legitimate value, if used with care.” Wikipedia

Second level of reuse: Class libraries

Reuse at class level or a set of classes in a software library is common and also fairly easy with object-oriented languages.

“Libraries contain code and data that provide services to independent programs. This allows the sharing and changing of code and data in a modular fashion. Some executables are both standalone programs and libraries, but most libraries are not executables …” Wikipedia

Third level of reuse: Design Patterns

Patterns allow you to reuse design ideas and concepts independent of concrete code.

“In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.” Wikipedia

Fourth level of reuse: Frameworks

An object-oriented abstract design to solve a specific problem – often very specialized, like Unit Testing frameworks and Object-Relational Mapping frameworks, but can be large, complex or domain specific.

“A software framework … is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined API, yet they contain some key distinguishing features that separate them from normal libraries.” Wikipedia

It’s all about being pragmatic – not all software will reach fourth level of reuse and will be structured as frameworks – frankly it shouldn’t. That said; copy/past style development is unquestionably a wrong path.

What level is your company at?

Visual Studio 2010 keyboard shortcuts

Sunday, May 2nd, 2010

I am fond of keyboard shortcuts and wish I was a keyboard-shortcut-ninja and didn’t have to rely on the mouse all the time.

Using keyboard shortcuts boosts productivity and ergonomically a better choice, as the risk of getting a tennis elbow/mouse elbow diminish.

Source of keyboard shortcuts for Visual Studio 2010:

Removing SVN folders with PowerShell

Saturday, April 24th, 2010


I need to remove.svn folders from an existing Visual Studio Solution a customer email me, so I could commit it to another SVN repository.

If I had access to the original SVN repository, I could have used the export function, as it does not include the .svn folders – but no, it should not be that easy.

What the heck, I have been putting it off way too long to start working with PowerShell. It should be a familiar environment as it is object-oriented with a C# like syntax with full access to the .Net Framework Base Class Libraries (BCL).

Here it goes – my first PowerShell script…

function RemoveSvnFolders([string]$path)
{
    Write-Host "Removing .svn folders in path $path recursive"

	Get-ChildItem $path -Include ".svn" -Force -Recurse |
		Where {$_.psIsContainer -eq $true} |
		Foreach ($_)
		{
			Remove-Item $_.Fullname -Force -Recurse
		}
}

The Write-Host Cmdlet just writes the content to console window.

If you are like me, a PowerShell novice – start with the Getting Started with Windows PowerShell article and use the free tool PowerGUI from Quest Software. It’s PowerShell IDE with an integrated syntax highlighter editor and debugger.

In line 5 the Get-ChildItem Cmdlet iterates the path recursively and filtering the result to include only “.svn” files and folders. The force parameter allows the cmdlet to get items that cannot otherwise be accessed by the user, such as hidden or system files. Get-ChildItem Cmdlet can also iterate the registry.

Afterwards the result from Get-ChildItem Cmdlet is piped to the Where-Object Cmdlet (Where is an alias for Where-Object). The psIsContainer is a property on a folder. If it is equal to true pass it to the next pipe. I could have written the following instead:

Where {$_.mode -match "d"}

Use the below statement to list all properties for the files and folders in the current folder:

Get-ChildItem | format-list -property *

The foreach statement iterates every item and deletes the folder with the Remove-Item Cmdlet.

Calling the method is as simple as:

RemoveSvnFolders("c:\svn\My Solution")

On TechNet there is a myriad of articles with the root Windows PowerShell Core and more task oriented like A Task-Based Guide to Windows PowerShell Cmdlets and Piping and the Pipeline in Windows PowerShell.

Remove SVN folders PowerShell Script.

Happy PowerShelling… :-)

40+ Essential Front End Web Developer Cheat Sheets

Tuesday, June 23rd, 2009

tripwiremagazine.com has gathered a neat collection of cheat sheets for web developers.

I’m not a front end web developer, so I’m in desperate need of tools and cheat sheets that can help me look good, when venturing into the world of web design :-)

Easy win – index candidates on SQL Server 2005

Monday, December 1st, 2008

Below is my real life story telling how easy it can be to find index candidates if you use your tools.

This weekend we deployed a new version of a medium/large solution to the production environment for one of our customers. Normally this is not a big issue, as we are always prepared to roll back to the previous version – the one currently in production. The deployment and configuration processes are well-prepared and highly automated to minimize faults and late-night-bug-hunting-frenzy.

After the deployment is complete we smoke test the setup to make sure that it is configured correctly and all is sound.

This weekend after the successful deployment the smoke test failed miserably. We received TimeOutExceptions all over. It was coming from the user repository service.

We decided to investigate a little before the decision of aborting the deployment of the new version and therefore rolling back to the previous version.

The steps to resolve the issue is what I want to share with you.

A quick look in the source repository showed that almost no changes to the user repository service – none that could cause TimeOutExceptions.

With the SQL Server Profiler it was easy to spot the cause of the exception.

This simple select statement was isolated and copied into the Management Studio to view the Actual Execution Plan. The execution plan did show much, but by execution the below statement which instructs the SQL Server not to execute the Transact-SQL  statements. Instead, SQL Server returns detailed information about how the statements are going to be executed in the form of a well-defined XML document.

SET SHOWPLAN_XML ON

The SQL Server will include loads in information and one of these are suggested indexes which you will not see with the graphical execution plan in Management Studio. Look for the MissingIndex elements:

<missingindexes>
  <missingindexgroup Impact="96.6222">
    <missingindex Database="[DOIPEI]" Schema="[dbo]" Table="[OrganisationalUnit_Stack]">
      <columngroup Usage="EQUALITY">
        <column Name="[org_pkid]" ColumnId="2" />
      </columngroup>
    </missingindex>
  </missingindexgroup>
</missingindexes>

By creating this single index on [DOIPEI].[dbo]. [OrganisationalUnit_Stack]. [org_pkid] the TimeOutExceptions disappeared, as the query no longer took minutes but milliseconds.

We were able to continue and successfully deploy the new version of the solution with only minimal disruption and a delay of only half an hour. Why the index where missing is still a mystery.

It makes all the difference in the world if you know the capabilities of your tools at hand.

.Net debugger visualizers

Sunday, October 12th, 2008

The .Net framework 2.0 gave some great tools for debugging – they are a great help when writing code.

Some of these features are the DebuggerDisplay and DebuggerStepThrough attributes. I seldom use any of them, as I prefer to just overriding the ToString method instead of using the DebuggerDisplay attribute. This makes it easy to instrument the code too, as I can reuse the ToString method implementation for tracing.

Another feature is the ability to develop custom debugger visualizers. They enable smart developers to build their own. I find some really useful, especially the WCF visualizer. But there a many – check out this list of custom .Net debugger visualizers.

These small enhancements make it so easy to get an overview of the current state, instead of inspecting properties.

Garbage Collection Flavors

Tuesday, April 3rd, 2007

Why should you care about Garbage Collection? Well, it may very well improve performance for your applications.

The .Net framework garbage collector can operate in different modes depending on platform and requirements. There are three modes available for .Net framework version 2.0 and 3.0. Each of these modes is tailored for specific situations.

Concurrent Workstation Garbage Collection

This mode is optimized for interactivity by frequent short garbage collects. Each collect is split up into smaller pieces and are interleaved with the managed applications threads. This improves responsiveness at the cost of CPU cycles. This is ideal for interactive desktop applications where freezing application is an annoyance for the users and ideal CPU time is abundant when waiting for user input. Concurrent workstation mode improves the usability with perceived performance.

Note that interactive GC only applies for Gen2 (full heap) collects because Gen0 and Gen1 collects are in nature very fast.

Non-concurrent Workstation Garbage Collection

Non-concurrent workstation mode works by suspending managed application threads when a GC is initiated. It provides better throughput but might appear as application hiccups where everything freezes for the users.

Server Garbage Collection

In server mode a managed heap and a dedicated garbage collector thread is created for each CPU. This means the each CPU allocates memory in its own heap therefore results in lock-free allocation. When a collect is initiated all the managed application threads are suspended and all the GC threads collect in parallel.
Another thing to note is that the size of the managed heap segments is larger in server mode than workstation mode. A segment is the unit of which the memory is allocated on the managed heap.

It is possible to choose the type of GC for a managed application in the configuration file. Under the <Runtime> element add one of the below three settings and depending on the number of CPU, the garbage collector will run in the configured mode.Garbage Collection type settings

Running a standalone managed application the GC mode is by default concurrent workstation. Managed application hosts like ASP.Net and SQLCLR run with Server GC by default.

If you want to know more about how the GC works, read the blog entries “Using GC Efficiently”
by Maoni.

Favor structured exception handling

Wednesday, February 21st, 2007

I was surprised this last week, when a discussion about error handling, whether or not to use structured exceptions in .Net, surfaced at a customer where I am helping them to complete a project. I will not name the company, but it is a Danish division of a large American IT corporation with around 80.000 employees.

The discussion was between one of their architects, a couple of others and me. The company where accustomed to used return codes and the architect argued in favor of return codes. I didn’t think in this day and age that organizations still use return codes with languages that have build-in support for structured exception handling.

An exception is an event that occurs during the execution of a program, designed to handle the occurrence of some exceptional condition which changes the normal flow of execution. Exceptions travel out of band and propagate through the call stack until an exception handler catches the exception. Structured exceptions use the Try…Catch…Finally syntax.
Below is a make believe example of a simple system calling two methods:

static void Main(string[] args)
{
  Order myOrder = new Order();
  decimal yield;

  try
  {
    yield = CalculateYield(myOrder);
    UpdateStatus(myOrder);
  }
  catch (Exception ex)
  {
  //** Exception handling **//
  }
}

public static decimal CalculateYield(Order order)
{
  // calculate yield
  return decimal.MaxValue;
}

public static void UpdateStatus(Order order)
{
  // update status
}

If an exception is thrown in the method CalculateYield the flow is short-circuited and the method UpdateStatus is never called. With return codes the developer has to manually check if the method failed and manually propagate the return code up the stack.

Return codes imposes on method signature by requiring the return type to be a return code and potentially use a parameter as return type. This clutters the method signature and does not make the method functionality apparent. Notice the confusing method signature of CalculateYield in the following code:

static void Main(string[] args)
{
  Order myOrder = new Order();
  decimal yield = 0;
  int returnCode = 0;

  returnCode = CalculateYield(myOrder, yield);

  if (returnCode < = 0)
  {
    returnCode = UpdateStatus(myOrder);
  }
  else
  {
    //** Error handling **//
  }

  if (returnCode > 0)
  {
    //** Error handling **//
  }
}

public static int CalculateYield(Order order, decimal yield)
{
  // calculate yield
  return -1; // return code
}

public static int UpdateStatus(Order order)
{
  // update status
  return 0; // return code
}

Return codes are inferior to exceptions. Exceptions are instances of a class and can therefore carry detailed information – not like integer return codes! It is non-reputable that return codes are no good.

The return code advocate might bring up an issue like performance due to the fact that throwing an exception results in a stack walk to create the stack trace.

When to throw exceptions?

Do not throw exceptions in the normal flow of execution. If it is expected that an action might fail like a login, use the Tester-Doer Pattern (e.g. Collection.Contains) or Try-Parse Pattern (e.g. Double.TryParse).

When to catch exceptions?

Catch only an exception if detailed information about the exception can be added, the exception is handled or some sort of compensation action is required. If the flow of execution can not continue, rethrow the exception so an exception can be handled further up the stack, e.g. inform the user.

catch (ArgumentException ex)
{
  // some clean up or logging
  throw ex;
}

When rethrowing exceptions, it is important to do it the right way. By using the above pattern regarding throwing and not throwing ex, the stack walk is not performed twice, making the rethrow virtually free.

If you want to know more read the book Framework Design Guidelines. It is recommended and easily read. You can also look at the blog entry Exception Throwing by Krzysztof Cwalina – one of the authors of the Framework Design Guidelines book. There is also a small summery at Design Guidelines for Exceptions on MSDN.

On a side note: the company mentioned was as one of the first I Denmark to adopt the .Net framework – in 2000 where beta 1 was released they build their first project on the .Net framework. Go figure!

Visual Studio 2005 shortcuts features

Thursday, February 1st, 2007

I tent to forget the Visual Studio 2005 shortcuts really fast when I haven’t done any real coding and just Word “coding” for a while. The shortcuts are really important as they enhance my coding experience and boost my productivity (which makes my manager happy; which increase my bonus; which makes me even happier – it’s a full circle :-) ).
There are a bunch of standard Windows keyboard shortcuts which I will not discuss. But do take a look, as I doubt that you know all of them. More or less all can be used in Visual Studio.
These are essential Visual Studio 2005 keyboard shortcuts for C#

Debugging
F5 Start debug.
Ctrl + F5 Start without debug.
Shift + F5 Stop debug.
F9 Toggle breakpoint.
F11 Step into method – Executes code one statement at a time, following execution into
method calls.
F10 Step over method – Executes the next line of code, but does not follow execution through
any method calls.
Shift + F11 Step out of method – Executes the remaining lines of a method in which the current
execution point is located.
IntelliSense
Ctrl + Space List possible methods, classes etc.
Ctrl + Shift + Space Displays the name, number, and type of parameters required for the specified method.
Ctrl + J List members of a method.
Ctrl + K, I Displays the complete declaration for the specified identifier in your code in a Quick
Info tool tip. This includes exceptions!
Refactoring
Ctrl + R, R Rename dialog box, which allows renaming all references for an identifier.
Ctrl + R, O Displays the Reorder Parameters dialog box, which allows changes to the order of the
parameters for methods, indexers, and delegates.
Ctrl + R, V Displays the dialog box, which allows removal of parameters from methods, indexers,
or delegates by changing the declaration at any locations where the member is called.
Editing
Ctrl + M, O Collapses existing regions to provide a high-level view of the types and members in
the source file.
Ctrl + M, L Toggles all previously collapsed outlining regions between collapsed and expanded
states.
Ctrl + M, M Toggles the currently selected collapsed region between the collapsed and expanded
state.
Ctrl + K, C Inserts comments marking at the beginning of the current line or every line of the
current selection. This also works in HTML and XML files.
Ctrl + K, U Removes the comments marking at the beginning of the current line or every line of
the current selection. This also works in HTML and XML files.
Ctrl + K, D Formats the current document according to the indentation and code formatting settings
specified. This also works in HTML and XML files.
Ctrl + K, X Displays the Code Snippet Picker. The selected code snippet will be inserted at the
cursor position.
Ctrl + K, S Displays the Code Snippet Picker. The selected code snippet will be wrapped around
the selected text.
Ctrl + Shift + V Pastes text from the Clipboard ring to the cursor location in the file. Subsequent
use of the shortcut key iterates through the items in the Clipboard ring.

There are loads of other Visual Studio 2005 keyboard shortcuts for C# – you should check out this Microsoft poster or this complete list.
You can setup your own keyboard shortcuts under Tools | Options | Keyboard. The interface for setting up keyboard shortcuts sucks, but it is doable.

Keyboard shortcuts are not the only means of improving your productivity. Visual Studio snippets are a timesaver. They work by entering a snippet shortcut key and the pressing tab twice. Like “class + tab + tab”, then a class stub is created for you.

class Class stub
cw Console.WriteLne
enum Enum stub
exception Exception class stub
prop Property stub with getter and setter
propg Property stub with getter only
#region Code region stub
try Try/Catch block
tryf Try/Finally block

The snippet I love the most is exception – this snippet generates complete exception class in accordance with Microsoft guidelines. I used to hate implementing custom exceptions because it was so cumbersome.

You can see all the default snippets under Tools | Code Snippets Manager or keyboard shortcut Ctrl K, B ;-) . You can also implement your own or do as I do; Google it.

You shouldn’t memorize all shortcuts, but adopt those which make your everyday life easier. You should however, every ones in a while think of expanding your arsenal of shortcut.

Have I missed any really important keyboard shortcuts or snippets? What are your favorite keyboard shortcuts and snippets? Let me know – I am expanding my arsenal :-D