Wednesday, March 3, 2010

Use before Reuse

I have been doing a lot of software design work in past months. As you know design is not easy. It’s almost always about making (hard) decisions. It’s about considering alternatives and weighting options. In that sense, I’ve also tried to learn more and expand my knowledge about software architecture and software design. As the main source of usable knowledge, I find the “Domain-driven design” book. You’ve probably heard of the Repositories, Aggregates, Value object etc. But, what I value the most in this book is the part called “Strategic design”. It’s the part that talks about Bounded Contexts, Context Maps, Core domain etc. Really, this is the most valuable part of the book. Eric Evans, himself, in his What I’ve learned about DDD since the book talk kind of admits that putting that part at the end of the book was a mistake. If you do software architecture and design I strongly advise you to explore that part of the book. However there is one advice-practice, that changed the my thinking from ground up. I have read this article by Kevlin Henney. The title of the article is “Simplicity Before Generality, Use Before Reuse”. The article is about how to value concrete and specific solutions over the more general solutions. Business people mostly have problems that are specific to them and thus need specific solutions. Software people, on the other hand, like to generalize. They (we) like to see abstractions everywhere and try to come up with general solutions that can solve all the problems. Of course, this will not happen. This usually end by making things more complex without any benefit. Go and read this article.

Tuesday, February 16, 2010

How to use Custom RoleProvider in WCF?

First thing is to add reference to the System.Web.dll assembly to your WCF project. Then create a class which inherits from RoleProvider. You’ll also need to add the System.Web.Security namespace. Then you can use the CTRL+dot trick so that VS generates all the methods for you. You’ll end up with something like this:

public class MyRoleProvider : RoleProvider
{
 
    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }
 
    public override string ApplicationName
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
 
    public override void CreateRole(string roleName)
    {
        throw new NotImplementedException();
    }
 
    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        throw new NotImplementedException();
    }
 
    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        throw new NotImplementedException();
    }
 
    public override string[] GetAllRoles()
    {
        throw new NotImplementedException();
    }
 
    public override string[] GetRolesForUser(string username)
    {
        throw new NotImplementedException();
    }
 
    public override string[] GetUsersInRole(string roleName)
    {
        throw new NotImplementedException();
    }
 
    public override bool IsUserInRole(string username, string roleName)
    {
        throw new NotImplementedException();
    }
 
    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }
 
    public override bool RoleExists(string roleName)
    {
        throw new NotImplementedException();
    }
}

Now, you’ll need to provide actual implementation for all of these methods. That’s up to you.

Next, you need to configure your config file. Add following to the system.web section of your configuration file:

<system.web>
    <roleManager enabled ="true">
 
        <providers>
            <add  name="MyRoleProvider" type="ReducingComplexity.MyRoleProvider, ReducingComplexityRoleProvider"/>
        </providers>
    </roleManager>
</system.web>

Now you’ll need to link this role provider to your services services. You will use serviceBehavior for this. For example, if you have service behavior defined like this:

<behaviors>
    <serviceBehaviors>
        <behavior name="MyServis.MyStandardBehavior">
            <serviceAuthorization roleProviderName="MyRoleProvider" principalPermissionMode="UseAspNetRoles"></serviceAuthorization>
        </behavior>
    </serviceBehaviors>
</behaviors>

Using the <serviceAuthorization>, I set roleProviderName with the name of my role provider as defined under <roleManager> node. Also, principalPermissionMode need to be set to UseAspNetRoles. That’s pretty much it. It’s that simple.

Now it’s possible to use both declarative security framework:

[PrincipalPermission(SecurityAction.Demand,Role = "Customer")]
public List<Order> GetOrders(int customerId)
{
}

or for example Thread.CurrentPrincipal.IsInRole() method.

public List<Order> GetOrders(int customerId)
{
    if (Thread.CurrentPrincipal.IsInRole("Customer")) 
    {
        // get customer orders 
    }
    else 
    {
        // permission denied
    }
}

WCF rocks!!!

Still, there is something I really don’t like. It is the fact that RoleProvider is considered to belong to ASP.NET(hence the need to add reference to System.Web.dll assembly). This is kind of unnatural, and I would like to see the role providers moved to some other assembly, for example System.Security.dll.

Monday, February 15, 2010

WCF and AOP with Castle.DynamicProxy

Managing logging and exception handling in WCF applications can be very time-consuming. Cross-cutting concerns can become a great burden and generate a lot of work for us. Today, I played a little bit with AOP and Castle Dynamic Proxy (DP) library. If you’re not familiar with AOP please take a look at this.

Before I even started with DP, I also considered PostSharp, but eventually I decided to go with DP. Reason: I just don’t like things integrated into VS and doing stuff I cannot fully control. It can be that this is not a legitimate reason, but still:).

I started by adding references to Castle.Core.dll and Castle.DynamicProxy2.dll files. Then I defined my Logging Aspect class

public class LoggingAspect : IInterceptor
{
    #region IInterceptor Members

    public void Intercept(IInvocation invocation)
    {
        Debug.WriteLine(string.Format("The user {0} is calling method {1}.", OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name, invocation.Method.Name));
        Debug.WriteLine("Parameters are : ");
        foreach (object argument in invocation.Arguments)
        {
            Debug.WriteLine("Parameter value : " + Convert.ToString(argument));
        }
        invocation.Proceed();
        Debug.WriteLine(string.Format("The calling is complete!"));
    }

    #endregion
}

This code is pretty straightforward. By implementing IInterceptor interface, I print out username of the calling user, the method called, and parameter values. You’ll probably want to write these info into a database or a file in your project. However, this will stands good as an example. Then, to create a proxy for a type:

ProxyGenerator pg = new ProxyGenerator();
var loggingAspect = new LoggingAspect();
var proxy = pg.CreateClassProxy(typeof(MyType), loggingAspect);

That is all I need to do regarding DP itself. Now, I need to integrate this into WCF. Luckily, WCF is very extensible framework. First, I’ll implement IInstanceProvider interface, so that I can control object instances creation. The interface is rather simple, consisting of three methods.

public class MyInstanceProvider : IInstanceProvider
{
    public Type Type { get; private set; }
    public MyInstanceProvider(Type type)
    {
        this.Type = type;
    }

    #region IInstanceProvider Members

    public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
    {
        ProxyGenerator pg = new ProxyGenerator();
        var loggingAspect = new LoggingAspect();
        var proxy = pg.CreateClassProxy(this.Type, loggingAspect);
        return proxy;
    }

    public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
    {
        return GetInstance(instanceContext, null);
    }
    public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
    {
        if (instance is IDisposable)
            ((IDisposable)instance).Dispose();
    }

    #endregion
}

Note that I’m using CreateClassProxy method of ProxyGenerator to create proxies. This requires that methods we want to intercept need to be marked as virtual. Now that I have my IInstanceProvider implemented, I need to hook it up to a service. There are several options for this, but I like using attributes for this. I want to be able to mark my service implementation with some attribute so that all methods on that are intercepted in the same way. To do this I’ll need an attribute that implements IServiceBehavior interface.

public class MyAspectsAttribute : Attribute, IServiceBehavior
{

    #region IServiceBehavior Members

    public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
        System.ServiceModel.ServiceHostBase serviceHostBase)
    {
        foreach (var dispatcher in serviceHostBase.ChannelDispatchers)
        {
            var cd = dispatcher as ChannelDispatcher;

            foreach (var endpoint in cd.Endpoints)
            {
                endpoint.DispatchRuntime.InstanceProvider = new MyInstanceProvider(serviceDescription.ServiceType);
            }
        }
    }

    public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {

    }
    #endregion
}

The most important thing here is the ApplyDispatchBehavior method where I set up the instance provider for each endpoint. Next, the only thing left is to mark my service with MyAspects attribute.

[MyAspects]
public class MyGreatService : IMyGreatService 
{
    public virtual string SayHello()
    {
        return "Hello";
    }
}

This way, SayHello() method (and all others marked as virtual) will be intercepted by my LoggingAspect class thus enabling me to centralize my logging code.

Monday, February 8, 2010

Convention over Configuration – the Microsoft way!

I like the concept of Convention over Configuration. It really makes sense. I only need to change parts of the configuration that are specific for my case. Here’s the Wikipedia definition of the concept:

“Convention over Configuration (also known as Coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility.”

It looks like that at Microsoft, they also liked the Convention over Configuration concept. Take for example the resource files in Visual Studio. Every form has it’s its’s resource file named in format [FormName].resx. This is great, but how do I change the .resx file for a form? I only want to change .resx file name, not the form name. I’m missing the Rename command on the context menu:

.resx file rename

No rename here. OK, let’s try by clicking Properties on the Form1.resx file, and changing the name there.

.resx file rename

The filename field is read-only. So there is no way to change the file whatsoever. It seems that Microsoft didn’t quite get the bolded and colored part of the Convention over Configuration definition:

“Convention over Configuration (also known as Coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility.”

I don’t have flexibility to change the name of the .resx file for a form.

Why am I telling all of this?

If you have ever written something like this:

public class MyForm<T>: Form 
{
     ...
}

and tried to use resources on your Form, you’ll get whole kind of interesting problems. But there is not much you can do about it. Thanks for reading!

Sunday, February 7, 2010

I’m having some hard time with Mono.Cecil

Mono.Cecil is great library, no doubt about that. But there are some things that are bugging me.

No documentation

This one is serious. A framework without documentation is very hard to use. Usually time is being wasted just to figure out how to do some of the very simple things.

API is hard to use

Generally, the API is OK, but it requires a lot of writing. Also, it’s easy to get lost in all of the MemberReferences, MethodReferences, MethodDefinitions, FieldReferences, FieldDefinitions, TypeReferences stuff. Writing IL is not easy at all. Especially when things get a bit complicated. Wouldn’t it be nice if Mono.Cecil had a interpreter/compiler in it. So, we could write C# code that would be translated to IL. Add to that a nice fluent interface:

  AssemblyDefinition assembly = AssemblyFactory.GetAssembly("SomeAssembly.dll");

            assembly.WithType("MyClass")
                    .WithMethod("SomeMethod")
                    .AppendCode(@"
                                    int x = 5; 
                                    Console.WriteLine(x); 
                                ");

I guess that I’m asking for too much with the interpreter/complier stuff, but a Mono.Cecil fluent interface would be very convenient.

Testability – unit testing 

How do you test code that works with Mono.Cecil? Here is my Mono.Cecil development cycle:

  1. Write code that uses Mono.Cecil
  2. Write the dummy assembly to the disk
  3. Open the assembly in the Reflector to see if everything is fine.

As you can see there is no test automation here whatsoever. The whole process is manual and very time consuming.

As I said, Mono.Cecil is great but more documentation and an Fluent Interface would make it much more better. If you have any advices on how to overcome these difficulties please let me know.

Saturday, February 6, 2010

Exploring the MVP Pattern

Windows Forms are still number one choice when it comes to development for Windows platform. Windows Forms are easy and proven. In most cases you use things out-of-the-box. If you need something special, you have the ability to make custom controls work the way you want. For most enterprise applications I would dare to call Windows Forms near to perfect. So what is this post about then? Imagine that you’re building a typical enterprise application with layered architecture. You’ve organized your layers perfectly, looking like this:

Perfect layered architecture

Next imagine that you’re done with developing your data and business layers. You’re happy since you have a nice, clean and loosely coupled design so far. Everything seems perfect as it can be. The next step is to work on your presentation layer. You are all excided! Of course, you choose to use Windows Forms for that. Shortly, after starting the development of presentation layer, you start to feel weird. Your feeling of nice, clean codebase starts to disappear. You start to see your BLL classes mixed in various event handlers. A lot of (object sender, EventArgs e) stuff makes you feel sad. You see code like txtName.Text and listViewOrders.Items all over the place. Little by little, it gets harder to gain control of the complexity.

Reason behind this post

First off, if you already have experience in using MVP pattern in Windows Forms, then it may be possible that you will not benefit that much from reading this post.

There are a lot of sources about implementation of the MVP pattern in Windows Forms applications. However, while exploring the pattern on my own, I didn’t find a lot of applications with full source code provided. Also, example applications were very simple, far from what can be seen in real-world applications. This made my understanding of MVP pattern harder. In that sense, I have set following goals for this post:

  • Build an working application by using MVP pattern.
  • Provide full source for it.
  • The application needs to be more complex than a simple “Hello World” example
  • Explain benefits of using MVP in Windows Forms applications 

The problem

My application consists of a single form. I’ll call the form Money Transfer Form. The form is used to initiate money transfer from one account to another. Each account has an ID and the name of the account owner. An account can be either of type Personal or Company. The actual transfer can be either Standard, International, Extended (no idea what that means). When transferring money, one needs to provide amount which needs to be of specific currency. Here are the other requirements/rules:

  • When transfer type is Standard the amount that can be transferred is limited to 500
  • When transfer type is International the amount cannot be lower then 200, and the currency needs to be in dollars. However, if dollar exchange rate at the moment of transfer is below 1.3, then the minimum amount that’s allowed needs to be 700. User of application needs to be notified when this happens. Also, in such case, another currency can be used for transfer.
  • When transfer type is Extended and both accounts are Company, an additional description of the transfer needs to be specified. Normally, users cannot enter any kind of description unless these conditions are not satisfied. The description cannot exceed 20 characters. If it does, the user will be asked a if he wants to reset the description (clear it). Also, as long as description is larger then 20 characters, this will be indicated with different color in UI. 
  • When user enters account number, the name of the account owner and account type has to be displayed on the form.
  • Before actual money transfer is initiated, application needs to ask the user to confirm such action. Also, when transfer has been done, the user needs to be informed.

Note that these rules really don’t make any sense, but can provide us with the complexity that often is found in real-world applications.

Domain design

Here is my domain model:

Domain Model 

The core domain model is very simple. To most interesting part is MoneyTransfer class. 

Validation

Since I have a lot of business rules, I have to think about validation. There has been a lot of discussions about validation in domain model. There are generally 2 different approaches

1. Let the entity validate itself by using some kind of IsValid() method.
2. Use external services to perform validation on entities.

The first method is fine, but lacks some flexibility. The main argument against it is that the same entity can be valid in one context and not valid in some other context. Personally, I prefer to keep my validation away from entities. Validation services can also be reused. This way, in one context a one set of rules can be used, while in another context a different set of rules can be used. There are different approaches to implementing the validation services, for example introducing IValidator<T> interface, but I will not use that approach just to keep the things simpler. Here is my rule interface:

    public class ValidationResult
    {
        public string Message { get; set; }
        public bool IsValid { get; set; }
    }
    public interface IMoneyTransferRule
    {
        ValidationResult Validate(MoneyTransfer moneyTransfer);
    }

The interface is very simple since we only have Validate method on it. Every rule must implement this interface. I’ll show some rules implementing IMoneyTransferRule interface:

“When transfer type is Standard the amount that can be transferred is limited to 500”

public class StandardLimitRule : IMoneyTransferRule
{
    #region IMoneyTransferRule Members

    public ValidationResult Validate(MoneyTransfer moneyTransfer)
    {
        if (moneyTransfer.Type == TransferType.Standard)
        {
            if (moneyTransfer.Amount > 500)
                return new ValidationResult()
                           {
                               IsValid = false,
                               Message = "When transfer type is 'Standard', amount is limited to 500."
                           };
        }
        return new ValidationResult {IsValid = true};
    }

    #endregion
}

“When transfer type is Extended and both accounts are Company, an additional description of the transfer needs to be specified. Normally, users cannot enter any kind of description unless these conditions are not satisfied. The description cannot exceed 20 characters.”

public class ExtendedTransferRule : IMoneyTransferRule
{
    #region IMoneyTransferRule Members

    public ValidationResult Validate(MoneyTransfer moneyTransfer)
    {
        if (moneyTransfer.Type == TransferType.Extended)
        {
            if (moneyTransfer.From.Type == AccountType.Company && moneyTransfer.To.Type == AccountType.Company)
            {
                if (string.IsNullOrEmpty(moneyTransfer.Description) || moneyTransfer.Description.Length > 20)
                {
                    return new ValidationResult
                               {
                                   IsValid = false,
                                   Message = "Extended Company-To-Company transfers need to have description. The description needs to be below 20 characters."
                               };
                }
            }
        }
        return new ValidationResult { IsValid = true };
    }

    #endregion
}

This was my validation strategy. Now, I’ll go to repositories.

Repositories

There are two repositories in my application: ICurrencyRepository and IAccountRepository. I’ll provide two in-memory implementations of both.

AccountRepository

 public class AccountRepository : IAccountRepository
    {
        public List<Account> _accounts = new List<Account>(); 
        public AccountRepository()
        {
            _accounts.Add(new Account { ID = "1", Name = "Account 1", Type = AccountType.Personal  });
            _accounts.Add(new Account { ID = "2", Name = "Account 2", Type = AccountType.Company });
            _accounts.Add(new Account { ID = "3", Name = "Account 3", Type = AccountType.Personal });
            _accounts.Add(new Account { ID = "4", Name = "Account 4", Type = AccountType.Company });
            _accounts.Add(new Account { ID = "5", Name = "Account 5", Type = AccountType.Personal });
            _accounts.Add(new Account { ID = "6", Name = "Account 6", Type = AccountType.Company  });
            _accounts.Add(new Account { ID = "7", Name = "Account 7", Type = AccountType.Company  });
            _accounts.Add(new Account { ID = "8", Name = "Account 8", Type = AccountType.Company  });
            _accounts.Add(new Account { ID = "9", Name = "Account 9", Type = AccountType.Personal });
            _accounts.Add(new Account { ID = "10", Name = "Account 10", Type = AccountType.Personal });
        }
        #region IAccountRepository Members

        public Account Load(string ID)
        {
            return _accounts.Where(m => m.ID == ID).FirstOrDefault();
        }
        public void Withdraw(string ID, double amount)
        {
            // we don't actually do anything here
        }
        public void Deposit (string id, double amount)
        {
            // we don't actually do anything here
        }
        #endregion
    }

CurrencyRepository

  public class CurrencyRepository : ICurrencyRepository
    {
        private List<Currency> _currencies = new List<Currency>(); 
        public CurrencyRepository()
        {
            _currencies.Add(new Currency { ID = "1", Name = "USD", Country = "US", ExchangeRate = 1.6 });
            _currencies.Add(new Currency { ID = "2", Name = "GBP", Country = "United Kingdom", ExchangeRate = 1.0 });
            _currencies.Add(new Currency { ID = "3", Name = "EUR", Country = "EU", ExchangeRate = 1.95 });
        }

        public Currency Load(string id)
        {
            return _currencies.Where(c => c.ID == id).FirstOrDefault(); 
        }

        public List<Currency> GetAll()
        {
            return _currencies.ToList(); 
        }
    }

Another thing worth mentioning is TransferFailedException class:

public class TransferFailedException : Exception 
{
    public List<ValidationResult> FailedValidations { get; set; } 
    public TransferFailedException(ValidationResult[] failedValidations)
    {
        this.FailedValidations = new List<ValidationResult>(); 
        this.FailedValidations.AddRange(failedValidations); 
    }
}

MVP Pattern

MVP stands for Model-View-Presenter. The relationships between M and V and P are:

Model-View-Presenter

Controller is mediating between Model and View. Unlike in MVC here we don’t have direct connection between the Model and the View. The Presenter is responsible for updating both the Model and the View. This variant of MVP is called Passive View, since View acting is kind of dumb. The whole process goes like this:

  1. Events are received on View, the View passes them to the Presenter.
  2. Presenter decides how and if the Model needs to be updated.
  3. Presenter initiates any needed changes on the View.

In this approach View is very simplified and worries only about the very presentation. There are no decisions being made in the View. The Presenter actually controls the logic flow. This is how Passive View variant of MVP works. There are also two other variants of MVP: Presentation Model and Supervising Controller. I will not talk about them now. This picture of Passive View may be more expressive:

Model-View-Presenter

That was theory. Here’s the practice:

Here it is how my form looks like:

Example MVP Application

First, I’ll abstract my frmMoneyTransfer with an interface:

public interface IMoneyTransferView
{
    string Account1ID { get; set; }
    string Account1Name { get; set; }
    string Account1Type { get; set; }
    string Account2ID { get; set; }
    string Account2Name { get; set; }
    string Account2Type { get; set; }
    string Description { get; set; }
    Currency Currency { get; }
    double Amount { get; set; }
    TransferType Type { get; set; }

    bool AskIfSure();
    void ShowMessage(string message);
    void DisplayDescriptionField();
    void HideDescriptionField();
    void PopulateCurrencyList(List<Currency> currencyList);
    bool AskQuestion(string message);
    void ExpandCurrencyBox();
    void SetDescriptionDifferentColor();
    void SetDescriptionNormalColor();
}

The frmMoneyTransfer implements IMoneyTransferView interface.

public partial class frmMoneyTransfer : Form , IMoneyTransferView
{
    ...
}

I’ll also need my MoneyTransferPresenter class

public class MoneyTransferPresenter
{
    ...
}

Connecting View and Presenter

The connection between View and Presenter is simple one, they hold references to each other. Here is the Presenter constructor:

public class MoneyTransferPresenter
{
    ...
    private IMoneyTransferView View { get; set; }
    public MoneyTransferPresenter(IMoneyTransferView view)
    {
        ...
        this.View = view;
        ...

    }
}

The View implementation also holds reference to Presenter

public partial class frmMoneyTransferFrom : Form , IMoneyTransferView
{    ...    
    MoneyTransferPresenter Presenter { get; set; }     
    public frmMoneyTransferFrom()    
    {        
        InitializeComponent();        
        this.Presenter = new MoneyTransferPresenter(this);     
    }    
    ...
}

Connection between Model and Presenter

This one is even simpler. Presenter holds reference to Model. The Model does not even need to know about that.

public class MoneyTransferPresenter
{
    ...
    private MoneyTransfer MoneyTransfer { get; set; }

    public MoneyTransferPresenter(IMoneyTransferView view)
    {
        ...
        this.MoneyTransfer = new MoneyTransfer();
        ...
    }
}

I have said earlier that:

“Events are received on View, the View passes them to Presenter.”

Here’s how it looks in practice when user presses Process Transfer button.

private void btnProcessTransfer_Click(object sender, EventArgs e)
{
    Presenter.ProcessTransfer();
}

The view only called Presenter.ProcessTransfer() method. Here’s another example:

private void txtAmount_TextChanged(object sender, EventArgs e)
{
    Presenter.AmountChanged(); 
}

I also said this:

Presenter decides how and if the Model needs to be updated.”

public class MoneyTransferPresenter
{
    ...
    public void AmountChanged()
    {
        this.MoneyTransfer.Amount = View.Amount;
    }
    ...
}

Then again, I’ve said this as well:

Presenter initiates any needed changes on the View

Below, you can see how Presenter tells the View what to do and updates it appropriately:

public void DescriptionChanged()
{
    if (View.Description.Length > 20)
    {
        bool answer =
            View.AskQuestion(
                "Warning : Your description is larger then 20 characters. Your transfer may fail. Do you want to clear it?");
        if (answer == true)
        {
            View.Description = string.Empty;
        }
        else
        {
            View.SetDescriptionDifferentColor();
        }
    }
    else
    {
        View.SetDescriptionNormalColor();
    }
    MoneyTransfer.Description = View.Description;
}

What is the benefit of using MVP?

  • We’ve managed to control the complexity by separating concerns.
  • Code in frmMoneyTransfer form is simplified and easy to understand.
  • Code in Presenter is clean and simple because it accesses the View using well defined interface – IMoneyTransferView
  • We have better structure of the code which improves understandability, maintainability, readability.
  • We have got a more testable code.

Note on source code provided

I did not use any IoC container just to keep the code simpler and more focused on MVP pattern. That’s why I have things like new MoneyTransferPresenter() and new AccountRepository() all over the place.

I also strongly suggest you to go through the source code and examine the various parts of the application.

Conclusion

My conclusion is that, in absolutely all, but the most simplest situations, should MVP pattern be used when building presentation layers in Windows Forms. The pattern is easy to learn and the benefit of using it is great.

Thursday, February 4, 2010

A good reading list

Today, I found an interesting blog post that kind of represents a reading guide to becoming a better developer. I found it on The Inquisitive Coder blog, which I highly recommend. You can look at the original post here. The author separates reading list in three sections: Introduction, Design & Architecture, Team Environment. The author also thinks that it’s best to read the books exactly in given order. Anyway, here is the list:

Introduction

  1. Refactoring (Martin Fowler)
  2. Implementation Patterns (Kent Beck)
  3. Code Complete: 2nd Edition (Steve McConnell)
  4. Working Effectively With Legacy Code (Michael Feathers)
  5. Clean Code (Robert C. Martin)

Design & Architecture

  1. Design Patterns (Gang Of Four)
  2. Patterns Of Enterprise Application Architecture (Martin Fowler)
  3. Domain-Driven Design (Eric Evans)
  4. Enterprise Integration Patterns (Gregor Hohpe, Bobby Woolf)
  5. Release It! Design and deploy production-ready software (Michael T. Nygard)
  6. 97 Things Every Software Architect Should Know (edited by Richard Monson-Haefel)

Team Environment

  1. Extreme Programming Explained, Second Edition (Kent Beck)
  2. The Art Of Agile Development (James Shore & Shane Warden)
  3. The Mythical Man-Month, 20th Anniversary Edition (Frederick P. Brooks)

I already own following books from this list:

Even though I’m not absolutely sure that this is the best order to read these books, I have decided to start reading Test-Driven Development (Kent Beck) first. It shouldn’t take long since it has around 240 pages. Currently, I’m at chapter 3, and I have to say I like the style of the book. It’s easy to follow and the author, Kent Beck, knows how to make a point. I also plan to introduce a new practice of reading one book each month. Two if time permits. This way, it will take me a year to read the all the books from the list. I’m pretty sure it will be worth the effort.

Tuesday, February 2, 2010

Digging deeper into Messaging

Recently, I got interested into messaging. Messaging is simply one of the ways of building enterprise applications. When you live in .NET world, you can use one of the following frameworks to ease your way of building a messaging application:

I decided to go with NServiceBus and write an simple application just to get more sense about the overall approach. I liked what I saw. Messaging gives a whole new meaning to building robust, fault-tolerant, fast performing, loosely coupled enterprise applications. The framework itself is designed in a such way so that actual development is simplified to it’s maximum. My next step was to download NServiceBus source code to take a peek of how the things were done internally. This helped me to grasp core concepts better and faster. Since I liked the whole idea, I decided to take things even further and read the Enterprise Integration Pattern book which stands for one of the best on the subject. I would also like to look more into the NServiceBus source code. However, reading the book has a higher priority for now. If you’re new to messaging, I strongly recommend checking out following links:

Anyway, I’ll keep you posted on my progress and thoughts on this interesting subject.

Sunday, January 31, 2010

Thoughts on OO design

OO design is a creative activity. To be successful at it, you’ll need a mixture of both talent and learned skills. There is no such thing as correct design. There is only good, bad and somewhere-in-between design. OO program is simply a collection of objects that send messages to each other. But how do you design these objects? What objects to create? Which objects should interact? In my work, I usually begin OO design by identifying abstractions. I look at the problem from higher level. I try to identify abstractions that model true nature of the problem. An common mistake is to completely model real-world entities. In software development we have possibility of using abstractions to make our job/life easier. You should use this to your advantage. I assign each object a single responsibility. Note that assigning responsibilities is not easy at all. If you are good at assigning responsibilities then chances are, that you’re are good at OO designs too.

Understanding responsibilities is key to good object-oriented design”—Martin Fowler

Once you’re done with the design, how do you know if it’s good or bad? There are two metrics/principles that you can evaluate your designs against. These are coupling and cohesion. These principles are very powerful in assisting you to make your OO designs good. Funnily, the principles don’t even come from OO, but from Structured design. Coupling is simply a degree to which each object is dependent on each one of the other objects (Wikipedia definition). Coupling quantifies the dependencies among objects. It can be loose or tight. Loose coupling is desired, since it’s more change-friendly. Fewer dependencies make introducing changes easier. Cohesion tells us how focused a class is in fulfilling its responsibility. Does a class have well defined responsibility? Are all parts of class (methods etc) focused on fulfilling that, and only that responsibility? High-cohesion is desired, since it promotes robustness, reusability, and understandability.

To sum up, here are the key concepts I use in my day-to-day OO design:

  • Abstractions
  • Responsibilities
  • Loose-coupling
  • High-cohesion

Following books helped me to gain more understanding of OO design:

Final advice: The best way to become better at OO design is to do it a lot. A huge amount of it.   

Saturday, January 30, 2010

DRY – The first step

It has been said that a thousand miles journey starts with a single step. So in case journey = becoming a better developer, then first step = DRY. DRY stands for Don’t Repeat Yourself. I see way too much copy-paste development around. This needs to stop. If you constantly copy-paste code around, you’re limiting yourself of becoming a better developer. Code duplication is evil, and it’s simply against common sense. So why do we do it? We do it probably because it’s easier, it doesn’t require us to think. When we stop thinking, our journey of becoming a better developer ends. Anyway, does anybody know how do you disable CTRL+C in VS :)?