RSS

Lazy Strategy Pattern

The following are some code samples that show how to use Lazy to clean up how your objects are initialized when using the Strategy pattern in .NET. The following code is taken from the DimeCast.Net Strategy pattern video. It uses an enum to select the correct logging strategy and logs the given message. The original code from the video before Lazy is applied looks like (by the way, I’m only posting the sections relevant to strategy and lazy):

public class LoggingService : ILoggingService
{
    private readonly Dictionary<LoggingStrategy, Logger> strategies;

    public LoggingService()
    {
        this.strategies = new Dictionary<LoggingStrategy, Logger>();
        this.DefineStrategies();
    }

    private void DefineStrategies()
    {
        this.strategies.Add(LoggingStrategy.Event, new EventLogger());
        this.strategies.Add(LoggingStrategy.Repository, new RepositoryLogger());
        this.strategies.Add(LoggingStrategy.Trace, new TraceLogger());
    }
}

Here is the same code using the Lazy<T> class in the System namespace.

public class LazyLoggingService : ILoggingService
{
    private readonly Dictionary<LoggingStrategy, Lazy<Logger>> strategies;

    public LazyLoggingService()
    {
        this.strategies = new Dictionary<LoggingStrategy, Lazy<Logger>>();
        this.DefineStrategies();
    }

    private void DefineStrategies()
    {
        this.strategies.Add(LoggingStrategy.Event, new Lazy<Logger>(() => new EventLogger()));
        this.strategies.Add(LoggingStrategy.Repository, new Lazy<Logger>(() => new RepositoryLogger()));
        this.strategies.Add(LoggingStrategy.Trace, new Lazy<Logger>(() => new TraceLogger()));
    }
}

And one final time just in case you don’t have access to Lazy<T>. This uses delegates to accomplish the same thing as the Lazy<T> class. I’ll be using the Func<TResult> delegate.

public class DelegateLoggingService : ILoggingService
{
    private readonly Dictionary<LoggingStrategy, Func<Logger>> strategies;

    public DelegateLoggingService()
    {
        this.strategies = new Dictionary<LoggingStrategy, Func<Logger>>();
        this.DefineStrategies();
    }

    private void DefineStrategies()
    {
        this.strategies.Add(LoggingStrategy.Event, () => new EventLogger());
        this.strategies.Add(LoggingStrategy.Repository, () => new RepositoryLogger());
        this.strategies.Add(LoggingStrategy.Trace, () => new TraceLogger());
    }
}

Now that all the code is out of the way, let’s talk a little about why you would want to use this. Let’s look at the original code sample. The DefineStrategies function initializes a Logger object and adds it to the Dictionary. Every single Dictionary.Add call in the original code is initializing an object. That’s additional memory and processing time for every object. By using Lazy(or the delegate method shown above), you postpone the initialization of the object until you actually ask for it.

Lazy initialization may not work well for everything but I’ve found that it makes strategy implementations much more lean and efficient in terms of machine resources.

 
Leave a comment

Posted by on May 2, 2013 in Software Development

 

Tags: , , ,

SQL If Exists Then Drop

This is one topic that I continually find myself refering to my notes and bookmarks on and I’ve finally decided to add this piece of very good reference information to my own blog.

Tables

Option 1:

IF OBJECT_ID('enterTableNameHere', 'U') IS NOT NULL
BEGIN
    DROP TABLE [dbo].[enterTableNameHere]
END
GO

Option 2:

IF EXISTS
(
    SELECT * FROM dbo.sysobjects
    WHERE id = object_id(N'[dbo].[enterTableNameHere]')
         AND OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
    DROP TABLE [dbo].[enterTableNameHere]
END
GO

Views

IF EXISTS
(
    SELECT * FROM INFORMATION_SCHEMA.VIEWS
    WHERE TABLE_SCHEMA = 'enterSchemaNameHere' AND TABLE_NAME = 'enterViewNameHere'
)
BEGIN
    DROP VIEW [dbo].[enterViewNameHere]
END
GO

Stored Procedures

IF EXISTS
(
    SELECT * FROM dbo.sysobjects
    WHERE id = object_id(N'[dbo].[enterStoredProcedureNameHere]')
        AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
BEGIN
    DROP PROCEDURE [dbo].[enterStoredProcedureNameHere]
END
GO

User-Defined Functions

IF EXISTS
(
    SELECT * FROM INFORMATION_SCHEMA.ROUTINES
    WHERE	ROUTINE_NAME = 'enterFunctionNameHere'
    AND ROUTINE_SCHEMA = 'dbo'
    AND ROUTINE_TYPE = 'FUNCTION'
)
BEGIN
    DROP FUNCTION [dbo].[enterFunctionNameHere]
END
GO
 
Leave a comment

Posted by on April 15, 2013 in Database Development

 

Tags: , , ,

Review: Nokia Lumia 920

I’ve had the Nokia Lumia 920 for a few months now and I think I can give a pretty good review. The phone was quite large to me at first but I did have an HTC Aria before this so anything was going to be huge to me. The phone is a bit heavy but the build quality is excellent. The screen looks great in a variety of lighting conditions. I’ve yet to use the “you can use gloves” feature since we never get glove weather but my wife loves that she can use her fingernails.

Side Note: The OtterBox case must be the best built OtterBox case I’ve ever seen. Even my carrier’s sales rep was amazed at how snug the phone sat in the case and how well it was made. I’m extremely glad I bought it considering I’ve dropped my phone multiple times now…

Wireless Charging

Wireless charging is also an interesting addition to the phone. The phone’s battery can easily go at least all day without a charge if you’re not using it much. With wireless charging, it really doesn’t matter how much you use it though. I usually just keep my phone on my desk anyway. Now I just make sure to drop it on the charging plate. As a bonus, the phone will never have the charging port/cable go bad which seems to be a common problem amongst my friends and family.

Camera

I was a bit worried about the camera with some people saying it doesn’t live up to the hype. They were wrong. The camera produces beautiful pictures. I will agree with some reviewers in that the built in software is a bit limited but a quick search on the marketplace for additional Lenses will fix that quickly.

Operating System

Not much to say about the operating system. Windows Phone is easy to use and intuitive. There are some great ease of use features like the ability to text a reply directly in the incoming call screen. There are two features suprisingly missing from the OS though: an incoming call blacklist and automatic silent/vibrate when appointment is marked busy. Add these 2 features Microsoft and you’ve got a perfect OS.

The browser (IE10) has worked amazing although I do wish they’d implement the full version’s InPrivate mode into the phone version. I keep my gaming accounts separate and InPrivate is an easy way to move between accounts.

Applications

Play and iTunes boast about the number of applications that they have but let’s be realistic. How many of those applications are actually be used by consumers. I have not had trouble finding applications for Windows Phone.

With that said, I don’t game much on my phone besides Sudoku and Word Search type applications and I never used Instagram which is the big one I hear people complain about. If I want to share photos with people, I put them on Facebook. And I’m blaming Google for YouTube. There are some great 3rd party YouTube applications (PrimeTube, MetroTube, etc) but Google keeps breaking them. I use Vimeo for my personal and work-related videos anyway since they have a group feature.

Conclusion

I would definitely recommend the Lumia 920 to anyone in the market for a easy to use phone.

 
Leave a comment

Posted by on April 5, 2013 in Personal Computing

 

Tags: , ,

Visual Studio Tips and Tricks: Debugging

Visual Studio Tips and Tricks was a topic in our local user group a while back. I decided why not do a series of videos instead of trying to publish all of the tips in a PowerPoint or some write up. Everything shown here can be done in at least Visual Studio 2010 and Visual Studio 2012.

The debugging video below is part 2 of this video series:

 

Tags: , , , ,

March 2013 Nicholls Presentation

This post will contain the information from my presentation at Nicholls State University on March 26, 2013.

Code Information

Code URL: http://jeremyknight.codeplex.com/
Source Control Tab -> NichollsPresentationMarch2013

Presentation Information

The general Visual Studio Tips and Tricks information can be found in my video linked below. I will be creating a Debugging Tips and Tricks video soon.
http://jeremyknight.wordpress.com/2013/03/18/visual-studio-tips-and-tricks/

Additional Reading Resources

Here is a list of resources for anyone that would like to do additional reading and/or research:

ASP.NET

LINQ

Entity Framework

ASP.NET AJAX Control Toolkit

 
Leave a comment

Posted by on March 26, 2013 in Speaking Engagements

 

Tags: , ,

Visual Studio Tips and Tricks

Visual Studio Tips and Tricks was a topic in our local user group a while back. I decided why not do a video instead of trying to publish all of the tips in a PowerPoint or some write up. Everything shown here can be done in at least Visual Studio 2010 and Visual Studio 2012.

 

 
1 Comment

Posted by on March 18, 2013 in Software Development, Speaking Engagements

 

Tags: , , ,

A Simple CSV Export?

The following programming anecdote was posted by a former colleague on his Facebook page today:

A couple of years ago a fellow developer was asked to take some data and export it to CSV format. He took some time and researched a library. After, the manager/architect/lead developer (all the same person), questioned why he took that time, and why he didn’t just string.Join() them together and move on. He rattled off a few special cases, escaping characters etc. and stood by his decision though the person questioning still thought it a poor one.   About once a month since then I hear a new story about home-grown, handmade CSV functionality breaking because it didn’t account for a case, character or something previously unexpected.

It’s a reminder to me that no matter how simple the task appears to be, a thought should be given to it’s longevity, future usage, and potential expectations long after the initial case for creation has been forgotten. A small investment now can go a long way.

“The only way to go fast is to go well”   For those curious, the chosen library at the time: http://kbcsv.codeplex.com/

Well said.

 
Leave a comment

Posted by on February 13, 2013 in Software Development

 

Tags: , ,

 
Follow

Get every new post delivered to your Inbox.

Join 85 other followers