Decaying Code

Where code comes to die

About the author

Maxime Rouiller is a passionate .NET technology specialist, working for 7 years in large software development, advocating Agile and TDD. Aware of the latest technological trends, he intervenes as a specialist in the .NET Montréal usergroup and acts regularly as a speaker for Web Form programmers on the MVC platform.

View Maxime Rouiller's profile on LinkedIn

Month List

Back to basics: Why should I use interfaces?

So I had this interesting discussion with a colleague about having a clean architecture for a small software he is doing. Since it's his first step among SOLID, I wanted to take it easy see how things were laid out. Since the program was mostly already written, I immediately noticed the lack of pattern and the direct data access in the event of his WinForm application. The conversation went a bit like this:

Me: What is this code with data access on the "OnClick" of your button? Him: Well it's the information I need to execute this command. Me: Do you know the Model-View-Presenter pattern? Because right now, you are mixing "Presentation", "Data Access" and "Business Logic" Him: I've used it before but it's been a while. How do you implement it?

So after showing him the pattern and explaining the basic implementation (because there is a lot of different way to implement this pattern), he asked me the following question:

"Of course, you don't need to use interface everywhere, right?"

But then I went on to explain testability and such but there is something different I wanted to bring to this small discussion and that I wanted to share a bit. When my class have dependencies injected through the constructor, I have 2 choices. Either I depend upon the implementation or the abstraction (interface/abstract). What's the difference and why is it so important?

MyClass depending upon the abstraction of "MyClassDataAccess"

When your class depend upon the abstraction, it can take any class that implement that abstraction (be it abstract class or interface). The implementation can easily be replaced by something else and that is essential in unit testing your logic.

MyClass depending upon the implementation of "MyClassDataAccess"

When your class depend upon the implementation directly, the only that can be sent to this class is this specific implementation. Anything else must derive from this class. This implementation couple the Caller and the Callee really tightly.

Why is it important ?

When you have a class that access services, slow resource (database, disk, etc.) or even a class that you haven't coded yet... an interface should be used. Of course it's not a law. You apply interface/abstract class when you need to decouple an implementation of a system from another system. That allows me to send mocked object and test my requirements/logic. This also bring another advantage that might not be evident at first. Customer changing his mind. When the customer change his mind and do not want to store information in an XML but instead want a database. Or when a customer say to not implement "this part of the system" because it will be available through a service. Etc Etc... Using interfaces and abstract class is the oil that makes the engine of your software turn smoothly and allow you to replace parts by better/different parts without hell breaking loose because of tightly coupled implementation.


Categories: architecture | design | mvp | pattern
Permalink | Comments (0) | Post RSSRSS comment feed

Simple explication of the MVC Pattern

Since the last time I wrote a blog post was more than a few months ago, I would like to start by saying that I'm still alive and well. I had changes in my career and my personal life that required some attention and now I'm back on track.

So for those that know me, I was participating to the TechDays 2009 in Montreal and presenting the "Introduction to ASP.NET MVC" session. I will also be presenting the same session in Ottawa (in fact this blog post is written on the way to Ottawa with Eric as my designated driver).

So what is exactly ASP.NET MVC? It's simply the Microsoft's implementation of the MVC pattern that was first described in 1979 by Trygve Reenskaug (see Model-View-Controller for the full history).

So in more details, the MVC is the acronym of Model, View and Controller. We will see each component and the advantages of having them separated properly.

Model

The model is exactly what you would expect. It's your business logic, your data access layer and whatever else is part of your application logic. This I don't really have to explain. It's where your business logic will sit and therefore should be the most tested part of your application.

The model is not aware of the view or of the controller.

View

The view is where sit your presentation layer for your application. In a web framework, this is mostly ASPX pages with logic that is limited to showing the model. This layer is normally really thin and only focused on displaying the model. The logics are mostly limited to encoding, localization, looping (for grids) and such.

The view is not aware of which controller invokes it. The view is only aware of the model to display.

Controller

The controller is the coordinator. It will retrieve data from the model and hand it over to the view to display. The controller can also be associated to other cross-cutting concerns such as logging, authorization and performance monitoring (performance counter, timing each operations, etc.).

Advantages

Now, why should you have to care about all that? First, there is a clear cutting separation between WHAT is displayed to the user and HOW you get the information to display. In the example of a web site, it become clearly possible to display different views based on the browser, the device, the capabilities of the device (javascript, css, etc...) and any other information available to you at the moment.

Among the other advantages, it's the ability to test your controller separated from your view. If your model is properly done too (coding against abstraction and not implementations), you will be able to test your controller separated from your model and your view.

Disadvantages

Mostly a web pattern than a WinForm pattern. There is currently no serious implementation of the MVC pattern for anything else other than web frameworks. The MVC pattern is hence found in ASP.NET MVC, FubuMVC and other MVC Framework. Thus it limits your choices to the web.

If you take a specific platform like ASP.NET MVC, other disadvantages (that could be seen as advantages) slips in. Mostly, you lose any drag and drop support for server controls. Any grids are now required to be hand-rolled and built manually instead the more usual abstraction offered by the original framework.

Conclusions

Since we mostly require to have a more fine grained control over our view, the abstraction offered by the core .NET Framework are normally not extensible/customizable enough for most web designers. Some abstraction might even become unsupported in the future and thus bringing us to a more precise control of our views. The pattern also allow us greater testability than what is normally offered by default in WebForms (Page Controller with Templating Views).

My recommendation will effectively be a "it depend". If an application is already built with WebForms and doesn't have any friction, there is no point in redoing the application completely in MVC. However, for any new greenfield project, I would recommend at least taking a look at ASP.NET MVC.


Categories: architecture | asp.net | mvc | pattern
Permalink | Comments (0) | Post RSSRSS comment feed

Improving code quality - 2 ways to go

I've been thinking about this for at least a week or two. In fact, it's been since I started (and finished) reading the book "Clean Code" by Robert C. Martin. There is probably only two way to go.

Fix the bad code

This method is called refactoring and "cleaning" the code. This of course, you can't truly know what code is bad without having a Static Analyser tool or programmers working on the code. The tool will allow you to spot piece of code that could bring bugs and/or be hard to work with. The problem, refactoring code or cleaning up code is really expensive on a business perspective. The trick is to fix it as you interact with the code. It is probably impossible to request time from your company to fix code that could cause bugs. If you ask your company to fix the code, you will probably receive this answer: "Why did you write it badly in the first place?". Which brings us to the other way to improve the code quality.

Don't write it

If you don't write the bad code in the first place, you won't have to fix it! That sounds simple to an experienced programmer that improved his craft with years but rookies will definitely leave bad code behind. Eventually, you will have to encounter this bad code. So how do you avoid the big refactoring of mistakes (not just rookies)? I believe that training might be a way to go. When I only had 1 year of experience in software development, I was writing WAY too many bad code. I still do. Not that I don't see it go through. Sometimes, things must be rushed, I don't understand fully the problem and some small abstraction mistakes gets in. I write way less bad code then when I started. However, this bad code is not just magically disappearing. It's stays there.

What about training?

I think that training and/or mentoring might be the way to go. Mentoring might be hard to sell but training is definitely not that hard to sell. Most employees got an amount of money related to their name within a company that represent training expenses that can be spent on them. What I particularly recommend is some courses in Object-Oriented design or Advanced Object-Oriented Design. Hell, you might even consider an xDD course (and by xDD... I mean TDD, BDD, DDD, RDD, etc.). Any of those courses will improve your skill and bring you closer to identifying clean code from bad code. Other training that will form you specific framework (like ASP.NET MVC or Entity Framework) will only show you how to get things done with those framework. The latter can be learned on your own or through a good  book.

So? What do you all thinks? Do you rather have a framework course or a "Clean Code" course?


Permalink | Comments (0) | Post RSSRSS comment feed

My baby steps to PostSharp 1.0

So... you downloaded PostSharp 1.0 and you installed it and are wondering... "What's next?".

Well my friends, let me walk you through the first steps of PostSharp. What could we do that would be simple enough? Hummm... what about writing to a debug window? That sounds simple enough! Let's start. So I created a new Console Application project and I added the reference to PostSharp.Laos and PostSharp.Public. As a requirement, the class must be tagged with "Serializable" attribute and implement OnMethodBoundaryAspect (not in all case but let's start small here).

Next, I have a few methods I can override. The two that we are interested in right now is "OnEnter" and "OnExit". Inside of it, we'll say which method we are entering and which one we are exiting. Here are my Guinea pig classes:

public class FooBar
        {
        [DebugTracer]
        public void DoFoo()
        {
        Debug.WriteLine("Doing Foo");
        }

        [DebugTracer]
        public void DoBar()
        {
        Debug.WriteLine("Doing Bar");
        }
        }

        [Serializable]
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
        public class DebugTracer : OnMethodBoundaryAspect
        {
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
        Debug.WriteLine(string.Format("Entering {0}", eventArgs.Method.Name));
        }

        public override void OnExit(MethodExecutionEventArgs eventArgs)
        {
        Debug.WriteLine(string.Format("Exiting {0}", eventArgs.Method.Name));
        }
        }

See how simple this is? But... does it work? Let's see the trace of calling each methods:

Entering DoFoo
Doing Foo
Exiting DoFoo
Entering DoBar
Doing Bar
Exiting DoBar

Isn't that wonderful? Compile execute and enjoy. But... what about the community you say? Of course if the tool is not open source there is probably nothing built around it, right? Wrong!

Here is a few resources for PostSharp that include pre-made attributes that are ready to be used:

That was everything I could find. Do you know any others?


Permalink | Comments (0) | Post RSSRSS comment feed

PostSharp - The best way to do AOP in .NET

Who knows about Aspect-Oriented Programming (AOP)? Common! Don't be shy! Ok, now lower your hands. My prediction is that a lot of you didn't raise their hands. So let's resume what AOP is:

Aspect-oriented programming is a programming paradigm that increases modularity by enabling improved separation of concerns. This entails breaking down a program into distinct parts (so called concerns, cohesive areas of functionality). [...]

So what does it mean truly? Well, it's a way to declare part of your software (methods, classes, assembly) to have a "concern" applied to them. What is a concern? Logging is one. Exception handling is another one. But... let's go wild... what about caching, impersonation, validation (null check, bound check), are all concerns. Do you mix them with your code? Right now... you are forced to do it.

The state of current AOP

Alright for those who raised their hands earlier, what are you using for your AOP concerns? If you are using patterns and practices Policy Injection module, well, you are probably not happy. First, all your objects need to be constructed by an object builder and need to inherit from MarshalByRefObject or implement an interface.

This is not the best way but it's been done in the "proper" way without hack.

What is PostSharp bringing?

PostSharp might be a "hack" if think so. Of course, it does require you to have it installed on your machine while compiling for it to work. But... what does PostSharp does exactly? It does what every AOP should do. Inject the code before and after the matching method at compile time. Not just PostSharp methods but any methods that is inherited from the base class PostSharp is ofering you. Imagine what you could do if you could tell the compiler to inject ANY code before/after your method on ANY code you compile. Think of the possibilities. I'll give you 2 minutes for all this information to sink in... (waiting)... got it? Start to see the possibility? All you need to do is put attributes on your methods/attributes like this:

[NotNullOrEmpty]
        public string Name { get; set; }

        [Minimum(0)]
        public int Age { get; set; }

Now look at that code and ask yourself what it do exactly. Shouldn't be hard. The properties won't allow any number under "0" to be inserted inside "Age" and "Name" will not allow any null or empty string. If there is any code that try to do that, it will throw a ValidationException.

Wanna try it?

Go download PostSharp immediatly and it's little friend ValidationAspects on Codeplex. After you have tried, try to build your own and start cleaning your code to achieve better readability.

And yes... both are Open-Source and can be used at no fee anywhere in your company.

Suggestion to CLR Team

Now, PostSharp force us to have it installed with the MSI for it to work because it needs to install a Post-Compile code injector (like some obfuscation tools). What would be really nice, is to be able to do the same thing built-in with the compiler. The compiler is already checking for some attribute already... I would love to have this "internal working" exposed to the public so that we can build better tools and, more importantly, better code.

UPDATE: I want to mention that PostSharp is NOT open-source. However is free unless you need to package it with your tool.


Permalink | Comments (0) | Post RSSRSS comment feed

RefCardz - Little known reference at the tip of your finger

DISCLAIMER: I am not an employee of DZone Inc. and I am not paid for talking about the RefCardz. RefCardz are available for Free (as in free beer) online on their website. RefCardz in printed format can be obtained at different events or by contacting DZone directly.

Maven Refcardz just got released today. Everybody that use Maven might be hyped over that but... did you know the other Refcardz?

My favourite is the "Design Patterns" Refcardz. There is easy diagram to understand the organization of your classes as well as 2 interesting sections. "Use When" contains indication on when to use this particular pattern and "Example" contains a small problem that would require this pattern. As an example, let's take the Adapter Pattern.

image

The "use when" in this section mention that an adapter should be used when:

  • you need to adapt a class to your interface
  • complex conditions with behaviour and states are present
  • transitions between states need to be explicit

I didn't use the Adapter pattern a lot so I just knew about the first two. Still thinking about the third one.

Those RefCardz are offered for free in PDF format on DZone or you might find them in glossy hard paper when going to conference/code camp/etc. Most of the developers I know have DZone on their RSS reader but have never taken the time to look at the RefCardz that are available.

The RefCardz can be found on here.

Here is a few of my favourites:


Permalink | Comments (0) | Post RSSRSS comment feed

Report a Bug - The feature all products should have

I was writing acceptance test for project today and I needed to include a file inside my Excel 2007 sheet. After fiddling around a little, I found "Insert Object". This allowed me to insert a file and have it available to anyone opening the Excel 2007 document. When I dragged and dropped the file to my desktop, the file was truncated! I couldn't believe it! I found a bug in Excel 2007! Being a developer, I wanted to properly report that bug.

So I started with a small Google search for "report Microsoft bug" which lead me to this, this and that.

Let me bring you the title of the last article : "Mission: Impossible. Submitting a Bug Report to Microsoft".

This had me afraid. The article is dated 2002 and the other ones are 2006. We are in 2009 at the time of writing this article. So I searched more and more. I literally found nothing.

How can an application ship without having an easy way to report a bug? Apple does it. Ubuntu does it. OpenOffice does it. Firefox does it. Google Chrome does it. Why can't I report a bug for Internet Explorer, Office or Vista (soon Windows 7)?

It goes without mention that if you are building a product, there should be an easy way to report a bug. Be it by a small contact form, an official bug reporting software, etc. But please don't charge your user 35$ to fill out bug report.

Microsoft has recently (in the last few years) opened up and launched Connect to help user report bug inside the .NET Framework. They should extend it to all their product line. It seems that developer working on the .NET framework are reachable and have blogs everywhere and that the Excel team is just higher up in the sky and untouchable by customer feedback.

So? Does your application have a way to easily report bug? Because if the process to report a bug is long and tedious, you will have a "bug-less" product with marginal amount of users that tolerates the bug or that are hard-core enough to take the time to report it.


Categories: architecture | opinion | rant
Permalink | Comments (2) | Post RSSRSS comment feed

5 reasons why you should use ASP.NET MVC

I'll be fair with you readers. I've only toyed with the ASP.NET MVC framework. It looks great as of now but it's the first full blown MVC framework that we have that is backed by Microsoft. However, there is a lot of opposition nowadays that tend to be formulated like this:

Why should I use ASP.NET MVC? WebForms works well.

Other problems come from the lack of server controls. When a developer look at that and he then wonder why he should have to write HTML and Javascript when before he could have retrieved all that beautiful information with a simple postback.

So without ranting any further, here is 5 reasons why you should use ASP.NET MVC.

1. Testability

When the MVC model is properly applied, it allow for a better separation of your business logic and your presentation code. If the view is not included inside your model, you can easily test without requiring a web server. By default, when starting a new MVC project, Visual Studio offer to create a new Unit Test project based on Microsoft's Unit Test framework. Other Unit tests framework can also be configured to be used by default instead of Microsoft's solution.

The way the code is also made, the controller is the one handling the calls from the route. They can be instantiated outside of a web request which makes them easy to test too.

2. Perfect control of the URLs

ASP.NET MVC use URL Routing to better control the request and forward them to your controllers. Instead of 1 to 1 mapping, they allow pattern matching. The default being "{controller}/{action}/{id}" with the default being "Home/Index". This technically allow you to set the URLs exactly how you want. You don't have to create folder for every level deep it goes. The URL routing allows you to make clean URL that will be easy to remember.

Would you rather try to remember http://localhost/Sales/DisplayProduct.aspx?ProductID=23213 or http://localhost/Product/Detail/23213 ? Even better, if you are an e-Commerce site and want some fast link.... you can directly bind those URL to http://localhost/23213 to make it more easy to remember. Doing that in WebForm while keeping all this unit testable would just be too time consuming now is it?

3. Better Mobility Support

In WebForm, you would have to detect on each page that the browser is a mobile and adapt your rendering for the mobile on each and every form. You could also redirect the user to different page when it's a mobile. What is excellent with MVC is that it's not the view that is receiving the request. It's the controller. The controller can then dynamically decide which view to render while keeping the same URL. So to see a product view, you don't even need to send different URL to different provider. You just detect which device you are handling and redirect it to the proper view. As you support more and more mobile device, you can keep on adding view that are more specific to each device. Want to support this new HTC? Create a view, detect the browser and ensure the right view is displayed. Want to support some iPhone goodness with some device specific HTML? Create the necessary view, reuse the browser detection and display the view.

You can keep on doing that ad infinitum and as much as you want depending on your audience. Having Mobile support now is more convenient than it has ever been.

4. View Engines

Now if you only built ASP.NET WebForms, this term might be weird for you. Let's just say that you have been using the same view engine all this time without wondering if you could choose. The WebForm view engine is... well... what you have been using all this time. This includes server tags (<% %>), binding tags (<%# %>) as well as control tag (<asp:TextBox ... />).

The Spark Engine is a good example. MvcContrib also offer 4 different view engine (Brail, NHaml, NVelocity, XSLT). Each of those engine are created to fix some specific problems. Different view engines can be used on different view. One page could be handled with WebForm view engine, one with Spark Engine, one with XSLT, etc. Different view, different problem different solution.

You might not have to use those, but the simple fact that they are available will make your life easier if they are needed.

5. Built-in and shipped jQuery support

Let's keep the best for the end. jQuery is shipped with any new project instance of ASP.NET MVC. Since Microsoft announced support for jQuery, it's been the big buzz in the javascript world. Since ASP.NET MVC don't rely on Postback, a strong javascript framework is needed to provide for all the UI the previous server control were offering. jQuery easily offer you AJAX, DOM manipulation, event binding and  this across browser.

Of course, jQuery is not an advance to MVC itself. But it is a serious offering from ASP.NET MVC. No more download or "I'll write my own" stuff. I don't know for all of you but if I have to do javascript, I normally do a document.getElementById. This will work in most browsers but as soon as you start going funky, some browser will misbehave. jQuery simply allow you to write $("#myControlId") or many more shortcuts to simply do what you need across browsers. Just by having jQuery available stops me from writing incompatible code.

Conclusions

Lots of point goes toward MVC. Way more could be added. You certainly don't want to miss Kazi Manzur Rashid's blog about ASP.NET MVC Best Practices (part 1, part 2). Scott Hanselman, Phil Haack also have great posts about ASP.NET MVC.

Don't be fooled. Web Forms are not necessarly evil. They just aren't leading you to a pit of success.


Categories: architecture | asp.net | c# | mvc | unit test
Permalink | Comments (11) | Post RSSRSS comment feed

Anti-Pattern: The Gas Factory or Unnecessary complexity

Just as in any system, when you start coding some structure, you always try to make it as generic as possible to make it easy to later reuse those parts.Just like petrolum complex, things starts getting complex There is normal complexity when you build your code and as you go, complexity adds up. However, one of the main problem of this anti-pattern is when it's done consciously.

Let's give a quick example here. You start building collections and one of your collection need a special feature. The problem is when you extract this functionality and try to make it as generic as possible so that anyone could reuse your class. That is the problem of the unnecessary complexity. You see, as you are making stuff generic for a single class, you are adding structures inside your code. Some of those structure might be proof tested for this specific class but might fail on other classes. There is also the problem that maybe no other class will ever require this functionality.

How do I solve this anti-pattern?

By following YAGNI and Lean Software Development, you delay code and unnecessary complexity until you actually require the complexity. If  you have 2 classes that require the same functionality, it is now time to extract this functionality inside a different class and make those 2 classes inherit from it (or any other patterns that are required).

And here, I'm not just talking about inheritance. I'm also talking about unnecessary design patterns. If you built a pipeline component to calculate discount but you only have one discount at the moment, it might be actually relevant to implement it anyway since you are sure you might require it later. However, the client is the one that is supposed to drive the requirements and if you don't require the pipeline immediately... well... don't built it!

It doesn't mean to leave your code in a fixed state. It just means to keep your code clean to ease the implementation of the pipeline.

The best line of codes are those we don't need to write.


Permalink | Comments (0) | Post RSSRSS comment feed

Software development is not an art. It's a craft.

When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong.
R. Buckminster Fuller - US architect & engineer

Forget about the "creation" part of the job. As you are developing your first application, you are not creating something. You are building something. Mind you, it's not like building a bridge as in engineering or a plane.

The main difference between the art and the craft is the people inside the profession. Art is completely subjective. Anyone can be improvised artist and some may succeed. The difference between artist and programmers is artist that don't sell get another job. Self-improvised programmers that fails simply find another company to hire him.

I'm not complaining about self thought programmers. What I'm worried about is the quality of the code we find in today's software. Who saw some serious bad code here? Raise your hand! You're not alone. Those code were probably made by people who don't care about software or by people who never had the chance to have proper training. That's where it's important to realize that our profession is way more of a craft than an art.

Art is based on inspiration. Craft is based upon sets of rules and experience that will bring you quality every time you follow them. Artistic software development doesn't care about the rules. Let's pick a simple metaphor. Japanese sword maker. There is a reason why there work is recognized and of such quality. Their craft had hundreds of year to accumulate rules on how to properly melt the metal, forge the blade, etc.. The master know a good sword on sight and knows that there is very few way to reach quality. Young apprentice will train for years under their master to gain the knowledge they acquired and be able to reproduce success.

It will be harsh but there is only 2 ways to change the behaviour of those that don't care about the code.

  1. Train them (mentorship, classes, etc.)
  2. Get rid of them

If you want to train a programmer, he have to attend conferences, user group and spend some time off work to learn about good practices, design pattern and software principles. Company like Object Mentor do offer training to raise the quality of existing programmer.

Our industry might not be as old as Japanese sword maker but we must start to get rules/principles as much as possible and encourage "artistic sword maker" to follow rules and principles. Otherwise, the only thing you will get is a cheap rip-off that will break on the first hit. We've all seen software that breaks on the first hit and we need to improve the average level of our profession.

UPDATE: Added a quotation that I think represent a part of what we are doing. Solving problems and then making it nice. But foremost, solving problems.


Categories: alt.net | architecture | opinion
Permalink | Comments (0) | Post RSSRSS comment feed