Linked In Twitter RSS

Unit testing Facade pattern

31. October 2009  · Comments (6)

The facade pattern is commonly used software engineering design pattern. His purpose is to provide simplified interface to a larger body of code.

It has several good uses:

- Make a software library easier to use and understand, since the facade has convenient methods for common tasks.
- Make code that uses the library more readable, for the same reason.
- Reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system.
- Wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).

Importance of this Design pattern we cannot underestimate.

In unit testing one of good practice is to put our dependencies in constructor of class. Facade pattern class however cannot have dependencies in constructor because it increase complexity of code.

In this blog post I will show you how to unit test facade pattern.

If I have 2 classes : EmailLogger and DatabaseLogger  and these two classes have same porpoise to Log same data.

These two classes have dependencies on another classes.

I want to have one class that I will call Logger with one method called Log that will be Facade for these two classes.

Class EmailLogger looks like this :

public class EmailLogger:ILogger
{
private readonly IEmailProxy _emailProxy;
public EmailLogger(IEmailProxy emailProxy)
{
_emailProxy = emailProxy;
}
public void Log(string message)
{
if(_emailProxy!=null)
{
_emailProxy.SendEmail(message);
}
else
{
throw new ArgumentNullException("_emailProxy");
}
}
}

 

This class have dependency on another class called EmailProxy and accepts interface IEmailProxy in constructor.

Class DatabaseLogger looks similar to EmailLogger :

 

public class DatabaseLogger:ILogger
{
private readonly IDatabaseMechanism _databaseMechanism;
public DatabaseLogger(IDatabaseMechanism databaseMechanism)
{
_databaseMechanism = databaseMechanism;
}
public void Log(string message)
{
if(_databaseMechanism!=null)
{
_databaseMechanism.SendLogToDatabase(message);
}
else
{
throw new ArgumentNullException("_databaseMechanism");
}
}
}

 

This class have dependency on class called DatabaseMechanism and accepts another interface IDatabaseMechanism in constructor.

And finally we have class called Logger that will be Facade for these two classes .

In this example I will use singleton implementation Unity container and Rhino Mocks.

 

public class Logger:ILogger
{
private readonly ILogger _emailLogger;
private readonly ILogger _databaseLogger;
public Logger()
{
IContainer container = new UnityContainer();
_emailLogger = container.Resolve<ILogger>("EmailLogger");
_databaseLogger = container.Resolve<ILogger>("DatabaseLogger");
}
public void Log(string message)
{
if(_emailLogger!=null)
{
_emailLogger.Log(message);
}
else
{
throw new ArgumentNullException("_emailLogger");
}
if (_databaseLogger != null)
{
_databaseLogger.Log(message);
}
else
{
throw new ArgumentNullException("_databaseLogger");
}
}
}

 

And of course we need to have some registration in container in some BootStraper class :

 

public static class BootStraper
{
public static void SetUp()
{
IContainer container = UnityContainer.Instance();
container.RegisterType<IEmailProxy,EmailProxy>();
container.RegisterType<IDatabaseMechanism,DatabaseMechanism>();
container.RegisterType<ILogger,EmailLogger>("EmailLogger");
container.RegisterType<ILogger,DatabaseLogger>("DatabaseLogger");
}
}

 

Consuming this class is simple :

 

public class Consume
{
public void ConsumeLogger()
{
Bootstraper.SetUp();
ILogger logger=new Logger();
logger.Log("Some message");
}
}

 

Code is simple and understandable and we don’t need to use any container to call this class . If someone reference your dll it can use your code without any container registration or resolve . You just call  method in that class and he not see container calls and deeper logic inside this Facade class.

And finally test is very simple too :

 

[TestClass]
public class LoggerTests
{
private readonly ILogger _emailLogger;
private readonly ILogger _databaseLogger;
private readonly IContainer _container;
public LoggerTests()
{
_container = UnityContainer.Instance();
_emailLogger = MockRepository.GenerateMock<ILogger>();
_databaseLogger = MockRepository.GenerateMock<ILogger>();
_container.RegisterInstance<ILogger>("EmailLogger", _emailLogger);
_container.RegisterInstance<ILogger>("DatabaseLogger", _databaseLogger);
}
[TestMethod]
public void Log_AcceptCorrectArgs_CallsEmailLoggerLog()
{
//arrange
ILogger logger = new Logger();
//act
logger.Log("Something");
ILogger emailLogger = _container.Resolve<ILogger>("EmailLogger");
//assert
emailLogger.AssertWasCalled(x => x.Log("Something"));
}
}

 

We register instance of mock objects EmailLogger and DataBaseLogger in Container and resolve later in test to ensure that correct method of mock object is called.

I hope this will help you in some of your projects.

Single responsibility principle? Does it mean I can't have more than one method in my class?

16. April 2009  · Comments (6)

Today I have take a look on Single responsibility principle.

It states that every object should have a single responsibility.

It looks very logic and nice but does it mean that I can have only one method per class? Does it mean that every interface that I create need to have only one method for implement?

I am not quite sure that I understand this principle.What do you think?

MVVM pattern in Silverlight using SLEextensions

15. February 2009  · Comments (6)

In this  article I will explain how to implement MVVM pattern in Silverlight.

I was very overjoyed when I was reading my friends article on Codeproject about MVVM pattern in WPF .

You can check this article by Miroslav Popovic on http://www.codeproject.com/KB/WPF/FirefoxLikeSearchWithMVVM.aspx

I have decided to try implement same pattern in Silverlight .After reading and researching about MVVM pattern and his implementation in Silverlight I have found that most used method for implementing something close to MVVM in Silverlight is done by using SLEextension libraries.

SLEextension libraries you can found on Codeplex at this adress : http://www.codeplex.com/SLExtensions

When we talk about MVVM pattern and his implementation we must mention concept of attached behaviors and what is main purpose of MVVM pattern.

The Attached Behavior pattern encapsulates "behavior" (usually user interactivity) into a class outside the visual heirarchy and allows it to be applied to a visual element by setting an attached property and hooking various events on the visual element.(definition by John Gossman)

Main concept of MVVM pattern is to shrink or completly remove logic from the presentation.More about these patterns you can read from links below.

There are many ways to implement attached behavior in Silverlight.You can use SilverlightFX libraries from Nikhil Kothari or something else but most easiest way to do this is to use SLEextensions library.

I will show you now how to implement this on small exemple project.I have created form with button, textbox and  datagrid control.Main purspose of this form is when you enter searh text and press search button grid is populated with filtered data.

Picture1

First we need to add reference to SLExtensions.dll.After that we need to create static class Commands where we need to put all our methods.We now create our method GetData.Whery important thing is to create static void Initialize to ensure later that static fields are initialized.

This class looks like this :

public static class Commands

    {

        static Commands()

        {

            GetData = new Command("GetData");

        }

 

        public static Command GetData

        {

            get;

            private set;

        }

        /// <summary>

        /// Ensure static fields are initialized

        /// </summary>

        public static void Initialize()

        {

        }

    }

After that we need to create base class for all ViewModels.It looks like this :

public abstract class ViewModel : INotifyPropertyChanged

    {

        public event PropertyChangedEventHandler PropertyChanged;

 

        protected virtual void OnPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        }

    }

and PersonViewModel class that has some important things.

In constructor PersonViewModel class we set what method will be responsible when GetData method executes.In setter or public property List we must set OnPropertyChanged method to occcur.

public class PersonViewModel:ViewModel

    {

        private List<Person> list;

        public string City { get; set; }

        public List<Person> List

        {

            get { return list; }

            set

            {

                list = value;

                OnPropertyChanged("List");

            }

        }

 

        public PersonViewModel(string CityP)

        {     

           City = CityP;

           Commands.GetData.Executed+=new System.EventHandler<ExecutedEventArgs>(GetData_Executed);

        }

 

        void GetData_Executed(object sender, ExecutedEventArgs e)

        {

            List = Model.Person.GetPeople();

            var query = from c in List

                        where c.City.ToLower().StartsWith(City.ToLower())

                        select c;

            List=query.ToList();

        }

 

    }

In xaml file we need to add reference to

xmlns:Input="clr-namespace:SLExtensions.Input;assembly=SLExtensions"

and set what method will be attached to button control.

Input:CommandService.Command="GetData"  
Input:CommandService.CommandParameter="{Binding}"

After that only two things more we must do.First we need to ensure that before proccesing xaml file static commands are created,and we need to on button click event pass PersonViewModel to Datacontext element to populate dataGrid control.

        public Page()

        {

            // Ensure static commands are created before xaml is processed

            Commands.Initialize();

            InitializeComponent();         

        }

 

        private void btnOK_Click(object sender, RoutedEventArgs e)

        {

            DataContext = new PersonViewModel(txtSearch.Text);

        }

I hope this will be good starting point for you to try to implement this pattern in your own projects. I think that reasons for implementing this pattern are obvious (testibility, separation from presentation layer…) but debbuging  is very big problem for everybody try to use this pattern in real Silverlight application.

Demo project: SilverlightMVVM.rar

 

Source :

Attached behavior pattern :

http://blogs.msdn.com/johngossman/archive/2008/05/07/the-attached-behavior-pattern.aspx

http://www.nikhilk.net/Silverlight-Behaviors.aspx

http://blogs.southworks.net/jdominguez/2008/08/icommand-for-silverlight-with-attached-behaviors/

MVVM pattern :

http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx

http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx

http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx

http://tozon.info/blog/post/2009/01/20/Silverlight-TreeView-MVVM-and-editing-1.aspx

http://mark-dot-net.blogspot.com/2008/11/model-view-view-model-mvvm-in.html