Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 89,661 hits
  • Meta

Archive for June, 2009

Getting involved in Alt.net

Posted by coreycoogan on June 28, 2009


Alt.Net is a term coined by David Laribee in this blog post in 2007.  It’s defined as this on the Alt.net website:

We are a self-organizing, ad-hoc community of developers bound by a desire to improve ourselves, challenge assumptions, and help each other pursue excellence in the practice of software development.

Since then, the Alt.Net movement has gained a lot of interest and momentum.  Some of the root philosophies have changed and it has evolved to be a far more encompassing community that touches on all things related to .Net development.  Spend some time on the Alt.net Yahoo Group and you’ll see what I mean.  I’m not saying that this is a bad thing because I think it’s great to as many developers eyes open to what is else is available besides Datasets, SqlDataSource and Entity Framework.

There’s plenty of ways to get involved in the Alt.Net community that require little to no effort.

  1. Start your own Alt.Net user group.  All you need is a group of interested people and a place to meet.  I did this recently by starting the Northeast Wisconsin (NEW) Alt.Net group.  I created a Yahoo! Group for communication and we meet once a month.  We’ve had only 2 meetings, but the attendance has been good and I think everyone has walked away feeling like they’ve learned something.
  2. Subscribe to the Alt.net Yahoo group.  There’s some good topics discussed and it’s a great place to get advice.
  3. Virtual Alt.Net (VAN): Virtual Alt.net is a way for you to participate with the global community and many of its thought leaders from anywhere in the world.  As a side note, VAN just got recognized by INETA, which will provide some added benefits.
    1. Subscribe to the Virtual Alt.net Google group.  This is the best way to keep abreast of upcoming virtual events and presentations.
    2. Checkout the Virtual Alt.Net website, run by Zachariah Young.
    3. Attend the Wednesday weekly meeting. (see the calendar)
    4. Attend the Thursday brown bag lunch (see the calendar). You’ll always learn something new, but should be prepared to be bring something, anything, to share with the rest of the group.
    5. Attend the live presentations, announced on the VAN Google group.
    6. View past presentations from such heroes as Greg Young, Jeremy D. Miller, Oren Eini (Ayende), Udi Duhan, and more.

It’s a great big world out there and you may not even know what you don’t know until you start opening your eyes to what other people are doing.  If you do nothing else, keep up with the VAN and be open to some positive influence.

Posted in Alt.Net | Tagged: , , | 1 Comment »

Open/Closed Principle and Over Engineering

Posted by coreycoogan on June 18, 2009


There was a post on the Alt.net group today about how a Factory could violate OCP (Open/Closed Principle) if new methods were added. I’ve had discussions on this issue in the past and figured it deserved a post.

The Open/Closed principle is a software design principle that says:

software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

I first learned of this principle from one of Robert C. Martin’s books, as it makes up the O in the SOLID principles. I respect SOLID and found that if you do nothing but adhere to these principles, you’ll generally design better software. It’s necessary, however, to use good judgment when applying these guidelines.

In general, OCP is the only SOLID principle that I take issue with, specifically the literal interpretation of “closed for modification”.  It seems that many developers take this to the extreme and spend unnecessary effort to avoid having to ever modify a class or method after it has been written.  The poster in the Alt.net thread was worried that adding an IF block to a method would violate OCP and was asking advice for how to avoid it.

My interpretation of OCP is that the interfaces or API’s should be closed for modification so that any future changes won’t break client or other calling code.  That means keeping your method signatures the same and not changing properties and access modifiers.  Software projects are typically time and resource sensitive and many design decisions must be weighed against the ROI they achieve.  Introducing a more complex design so that a few lines of code don’t have to be added later seems ridiculous to me.

Here’s an example where OCP doesn’t provide the necessary value to make it worth the effort.

Let’s say you have an Order entity and that entity has a Validator class.  The Validator class validates that the Order has all the required values in the right format.  This is how most of us handle validation, using some IValidator<TEntity> type of pattern.  Now let’s say that this Order class goes to production and functions properly for several months.  Now the business comes back and says that Credit Card Security Code is required for PCP compliance.  If we follow OCP in a literal sense, we can’t just add that validation rule to the Validator class.

If a person is designing with OCP in mind, they may use the Specification pattern to handle validation, which would allow us to add validation rules any time without modifying any existing classes.  That is certainly a viable option, but is not as simple and easy to understand as a single Validator class and would certainly be less effort to implement.  I would also argue that the quality of my software with a Validator class is no less than an application using Specifications for validation rules.  If my Validator is using the Notification Pattern to return validation status and error messages to various layers, adding this additional validation rule will require no modification by the rest of the application, which is what OCP means to me.

Conclusion

The SOLID principles and OCP are guidelines to help us deliver more extensible and maintainable software.  However, being a rigid and literal follower of OCP and the “closed for modification” philosophy can lead to over engineering.  Adding complexity for the sake of never touching a class or method again after it’s been written may have its place in some software projects, but chances are in most cases your quality won’t suffer by adding an IF block.

Posted in Architecture and Design, Design Patterns, SOLID | Tagged: , , | Leave a Comment »

Visitor Pattern: A Real World Example

Posted by coreycoogan on June 16, 2009


Vistor

Vistor

The Visitor pattern is a powerful design pattern that I see a lot less then its popular brethren such as Factory, Facade, Command and Singleton. I believe this is because the pattern is often a bit more difficult for developers to understand and much of the articles and examples out there lack a real world example.

The Gang of Four defines the Visitor as:

Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

The very nature of the Visitor makes it an ideal pattern to plug into public API’s, thus allowing its clients to perform operations on a class using a “visiting” class without having to modify the source. Once familiar with this pattern, you will see the opportunity to apply it whenever you are dealing with composites or collections of interfaces/base classes.

A Real World Example

I have been working on a project that uses a third-party application database. The database is very large and provides a set of base tables that are completely generic. These tables look much like what you find in SharePoint, with column names like CHAR_01, CHAR_02, DATE_01, DATE_02. The application adds meaning to these generic tables by creating Views with meaningful column names in the database to sit on top of them. For example, the EntryView will essentially map a field called BeginDate to the base table’s DATE_01 field.

A code generator has been written to interact with this database from .Net applications. The generator creates of class for each base table as well as a class for each view, which decorates the base table.

Here’s what that table/view structure looks coming out of the generator:

    public class BaseTableRecord
    {
        public int Int01 { get; set; }
        public string Char01 { get; set; }
        public bool Char02 { get; set; }
        public bool Bool01 { get; set; }
    }

    public abstract class PartyBaseView
    {
        public PartyBaseView (BaseTableRecord record)
        {
            BaseRecord = record;
        }

        public BaseTableRecord BaseRecord { get; private set; }
    }

    public class PartyEntryView : PartyBaseView
    {
        public PartyEntryView (BaseTableRecord record)
            : base(record)
        { }

        public int NumberInParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string PartyName
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }
    }

    public class PartyExitView : PartyBaseView
    {
        public PartyExitView (BaseTableRecord record)
            : base(record)
        { }

        public int ExitingParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string Payor
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }
    }

To remain generic, the primary type that is deal with is a collection of PartyViewBase types. Now there are all sorts of actions we will want to perform on these different views. Because any single Use Case could deal with a collection of PartyViewBase types, consisting of one or more instances of multiples PartyViewBase implementations, we need a way to interact with each inside an iteration without casting. A perfect example Use Case would be the need to map each view to an XML file. Let’s see how Visitor pattern (which will ultimately have to be added to the code generator) will work for me.

First I’m going to define the IPartyViewVisitor interface for my Visitor:

    public interface IPartyViewVisitor
    {
        void Visit(PartyEntryView view);
        void Visit(PartyExitView view);
    }

Now I’m going to add a method to my PartyBaseView to allow the methods on my visitor to be invoked. Here’s what that abstract method looks like:

public abstract void Accept(IPartyViewVisitor vistor);

Here’s what the classes look like now that they’ve fully implemented the pattern:

    public abstract class PartyViewBase
    {
        public PartyViewBase(BaseTableRecord record)
        {
            BaseRecord = record;
        }

        public BaseTableRecord BaseRecord { get; private set; }

        public abstract void Accept(IPartyViewVisitor vistor);
    }

    public class PartyEntryView : PartyViewBase
    {
        public PartyEntryView(BaseTableRecord record)
            : base(record)
        { }

        public override void Accept(IPartyViewVisitor vistor)
        {
            vistor.Visit(this);
        }

        public int NumberInParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string PartyName
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }

    }

    public class PartyExitView : PartyViewBase
    {
        public PartyExitView(BaseTableRecord record)
            : base(record)
        { }

        public override void Accept(IPartyViewVisitor vistor)
        {
            vistor.Visit(this);
        }

        public int ExitingParty
        {
            get { return BaseRecord.Int01; }
            set { BaseRecord.Int01 = value; }
        }

        public string Payor
        {
            get { return BaseRecord.Char01; }
            set { BaseRecord.Char01 = value; }
        }
    }

Next, I need to write an IPartyViewVisitor implementation to handle mapping my Views to XML files.

    public class PartyViewMapperVisitor : IPartyViewVisitor
    {
        //would take some infrastructure class in the constructor

        #region IPartyViewVisitor Members

        public void Visit(PartyEntryView view)
        {
            //do mapping here
            Console.WriteLine("Mapping PartyEntryView");
        }

        public void Visit(PartyExitView view)
        {
            //do maping here
            Console.WriteLine("Mapping PartyExitView");
        }

        #endregion
    }

Now I’ll put it all together and get a list of PartyViewBase instances, loop through them, and let my Visitor implementation do the work.

    //instantiate my repository, service or whatever
    PartyRepository repo = new PartyRepository();

    //get my list of PartyViewBase instances
    IList parties = repo.GetAllParties();

    //instantiate my mapping visitor
    PartyViewMapperVisitor visitor = new PartyViewMapperVisitor();

    //loop through my PartyViewBase instances
    foreach (var viewBase in parties)
    {
         //perform my mapping
         viewBase.Accept(visitor);
    }

Conclusion

The Visitor pattern allows you to define an operation on a class without changing that class. Because a Visitor is defined as an interface, visitor implementations can be written for multiple needs and the target class never gets touched, adhering to OCP. Whenever you are dealing with composites, think about using the Visitor pattern to make your life easier. It’s also great to stub the Visitor into public API’s to grant your clients, and yourself, future access without modification.

Posted in Architecture and Design, Design Patterns | Tagged: , , | 5 Comments »

Asp.Net MVC HTML Helper Alternative

Posted by coreycoogan on June 11, 2009


I’m still learning ASP.NET MVC and gearing up for 2 projects.  At first glance of a typical View, I had a classic ASP flashback.  Now that I understand how it really works, I see that the only commonality is the use of the ASP delimiter tags (<%%>).

I’m not real crazy with the default ASP.NET MVC view engine and have examined some alternatives, such as MVC Contrib and Spark.  A new strategy has emerged however, developed by Eric Hexter.  Eric is dubbing his project Opinionated Input Builders.  It’s very early stage, but it’s definitely interesting and worth checking out.

Posted in ASP.NET MVC | Tagged: , , | 1 Comment »

What kind of developer are you?

Posted by coreycoogan on June 10, 2009


I’m sharing this because I thought it was interesting, especially in regard to team dynamics.  The idea is Productivity Personas, which I found on J.D. Meier’s blog.  It’s definitely worth a read.

Of the different personas, I would say I fall into these, not necessarily at the same time:

- Starter
- Thinker
- Doer
- Can Do
- Simplifier
- Tinkerer

Have a read and see what you are.

Posted in Developer Life | Leave a Comment »

Partial Methods on Partial Classes

Posted by coreycoogan on June 9, 2009


Here’s something I learned recently while reading Professional ASP.NET 1.0 – not only are there partial classes, but also partial methods.

I can’t believe this feature has been around as long as partial classes and I haven’t heard about it until now [UPDATE 7/10/2009: Thanks to Scott Mitchell's Comment, where he pointed out that this actually came with the 3.5 Framework].  I must have read 25 blog posts and articles when partial classes were being introduced talking about how cool they were and none of them ever mentioned the awesomeness of partial methods.

Until now, when I wanted to define a method on one side of a generated class and let it be implemented on another, I would create a base class and add a virtual method to be overridden, such as the example below.  Partial methods are private, so this approach still has merit when true inheritance is required.

Old Way

//My generated class
public partial class DataMapper : DataMapperBase
{
     public void Map()
     {
          //foreach loop or something

         //now do custom mapping
         MapCustom();
     }
}

//my custom partial class
public partial class DataMapper
{
     protected override void MapCustom()
     {
         //do custom mapping
     }
}

//generated base class
public abstract class DataMapperBase
{
     protected virtual void MapCustom(){}
}

As I said, this works, but it’s ugly. Now here’s what it looks like with partial methods:

With Partial Methods

//My generated class
public partial class DataMapper
{
     public void Map()
     {
          //foreach loop or something

         //now do custom mapping
         MapCustom();
     }

     //define the partial method
     partial void MapCustom();
}

//my custom partial class
public partial class DataMapper
{
     //implement the partial method
     partial void MapCustom()
     {
         //do custom mapping
     }
}

How do partial methods work you ask? If a partial method gets implemented by any of the other partials, it’s compiled and all is good. If it is not implemented, the compiler removes the method definition, as well as all calls to it, as though it was never there. More details are available on the MSDN site.

There are some limitations, so here’s the rules (from MSDN):

  • Partial method declarations must begin with the contextual keyword partial and the method must return void.
  • Partial methods can have ref but not out parameters.
  • Partial methods are implicitly private, and therefore they cannot be virtual.
  • Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
  • Partial methods can have static and unsafe modifiers.
  • Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.
  • You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.

Posted in C# | Tagged: , | 2 Comments »

Mocking DateTime.Now

Posted by coreycoogan on June 7, 2009


The problem is simple.  You have written some code that does some date calculation, comparison, etc. using DateTime.Now.   Now you want to write a unit test against some scenario to make sure the code acts as expected.  The question is how to do this in a repeatable, automated test environment?  For a single run or two, you may try to simply set your system date to the desired value and run your test, but that has some obvious limitations.

One idea that I really like comes from Ayende in a blog post that’s almost a year old.  His solution is so simple and elegant – create a static method that returns Func<DateTime>, which allows you to specify a default and easily override the value in a test with a new expression.

public static class SystemTime
{
     public static Func Now = () => DateTime.Now;
}

Now rather than use DateTime.Now, use SystemTime.Now. To override the value in a test it’s simple:

SystemTime.Now = () => new DateTime(2000,1,1);

Posted in Architecture and Design, TDD | Tagged: , , | 1 Comment »

Big Design Up Front (BDUF) = Booooo!

Posted by coreycoogan on June 5, 2009


I’m working on a project that is the epitome of BDUF.  After more than a 4 week effort into an end-all be-all requirements document, the technical design phase has started.  This requires the complete application design to be laid out with textual documents, Sequence Diagrams, Excel spreadsheets, class diagrams and countless other artifacts.

This is so ridiculous, as we all know that the second development begins most of those docs are out of date.  I don’t mind doing UML docs, a little at a time, but doing all of them at once really sucks.  I asked if there would be use cases, which I find to be the most useful artifact of all, but it seems they are meshed somewhere in the 70 page design document.

For those companies not quite willing to jump into a pure Agile methodology, may I suggest a hybrid between Agile and Waterfall.

- Define enough requirements to get the project going, i.e. most important features

- Design for those features

- Approve design

- Develop

- Begin requirements on next phase during development

- Review development

- Make changes as necessary

- Start over

This is sort of like a bunch of smaller water falls, but at least there is some time to react to changes from the previous iteration, which could take any amount of time.  It also breaks up the mind numbing Visio UML tasks so more attention can be focused to them.  Whose to say that one week into the project, a better flow or object model won’t be discovered, invalidating all the sequence and class diagrams developed?

UPDATE (6/8/2009): Jeff Palermo wrote on this topic with some insights into how Headspring does Agile.

Posted in Architecture and Design | Tagged: , , | 1 Comment »

MVC Project Architecture

Posted by coreycoogan on June 5, 2009


The MVC project I’ve talked about in my first 2 posts is still moving along.  I’ve continued to learn all I can about the new ASP.NET framework, but have a lot to learn.  It’s very different (read:better) from the MVC I used to do 5 years ago in the JSP days.

As the rest of the team ramps up, I thought it was important to layout the application architecture.  Being a fan and student of Domain Driven Design, I followed many of the patterns discussed by Evans, as well as others. The app requires a WCF service layer, so most the typical layering will reside behind the Service layer.  We’re also using LLBLGen, with Linq, as an ORM.  The client is anti NHibernate, so some other ORM had be chosen and in my opinion LLBLGen is the best database driven ORM around.

The app is an enterprise critical application and I’m trying to architect in a way that will support growth, foster SOLID principals and be easy to maintain.  Here’s the layers we’ll be using, with a description of each.

app.web (mvc)

app.web.controllers – has controllers for MVC.

app.application – DTOs, WCF service gateway, interface for WCF proxies.  Controllers will take WCF service proxy interfaces via DI.

app.service – WCF service that sends/recieves DTO’s defined in app.application.  Maps DTO’s to domain objects and interacts with the next layer to call Application Services.

app.service.application – application layer for the WCF service.  Contains application services that act as a facade to the domain (core) layer.  This is where all infrastructure and domain functions are coordinated.

app.core – where domain objects and repository interfaces live. This is where all business logic is essentially stored.

app.infrastructure – where the repository implementations live, as well as email gateways and other infrastructure stuff.

Posted in Architecture and Design, ASP.NET MVC, Design Patterns, Domain Driven Design | Tagged: , , , | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.