Reducing Complexity

Wednesday, March 3, 2010

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

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:

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")]

publicList<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

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

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:

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.

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.

Monday, February 8, 2010

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:

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

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:

publicclass 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

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:

Saturday, February 6, 2010

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:

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:

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:

“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.”

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

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:

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

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

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:

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

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:

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

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:

Sunday, January 31, 2010

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:

Saturday, January 30, 2010

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 :)?