Posts
58
Comments
103
Trackbacks
10
Monday, October 22, 2007
Moving Day

I've recently moved.  Come check out my new diggs at Los Techies.

If you are interested by what you read, add my feed to your reader.

posted @ Monday, October 22, 2007 7:31 PM | Feedback (0)
Sunday, October 21, 2007
Every Class Should Be a WCF Service

Actually, no.  Just kidding. ;-)

BUT, that's the view held by a very smart architect from a different school of thought.  We can break down his thoughts a bit further though.  You see, he thinks every class is/should be a component.  So what he's really trying to say is that every component should be a wcf service.  Why?  Because the component services provided by WCF can interop with other languages (if necessary).  This comes via the WS-Death Star.

But don't take my word for it, watch Ron Jacobs interview Juval Lowey.  And close your ears when you hear the comment about TDD.  Don't flip the bozo bit.  He's a really sharp guy.

And remember, if anyone outside Microsoft would be capable of making such a claim about WCF, it would be the RD of Silicon Valley, who was one of the few outside Microsoft to help design WCF.

It may seem like overkill now, but maybe not when processors start shipping with 32 cores on them.

posted @ Sunday, October 21, 2007 9:05 PM | Feedback (1)
DomainService.Equals(typeof(Component))

I just wanted to point this out for anyone else who hasn't already noticed.  Domain Services are usually components in disguise (ie..same thing, different terminology).

While a lot of emphasis is put on statelessness for components, there is actually a finer grained definition.

A class is a component if its clients can be instance agnostic.

Whether it's an IEmailSender or an interface for a remote service, your application typically does not care which instance of the proxy or helper class it gets.  In terms of state, it's less about not having state and more about not having internal state.

For example, Data Access Components are allowed to have external state.  Their state is stored in the form of the database.  The fact that they appear to have state (the data in the database) does not breach the component definition.  The reason is that since the state is centralized and external, the clients are instance agnostic.  This falls within the guidelines of component-orientation.

Much like the guys building component architectures, we too use classes whose clients are instance agnostic.  Service Layer classes are components.  Domain Service classes are also components.  There are no rules as to how a component is built out internally (procedurally, functionally, object-oriented), etc.  Those are just the implementation details.  I use an implementation of the Notification Pattern for Dto validation.  It too is a component.

Anything you are injecting today is very likely a component.  You can inject state into classes using tools like Windsor, but it's not easy (and involves injecting a properties hashtable--no thanks).

Oh, and those "configuration" variables don't count as state either (ie..SmtpServer).  Those are perfectly valid in both paradigms.

Domain model applications are really component sandwiches, where the OOP/Domain Model is the meat.

What about NHibernate?  The SessionFactory is a component--although you only ever want one instance per application.  This is perfectly valid as well.

Sessions are a little bit trickier.  Each Session has a unique state.  This can still be accounted for if the session state were externalized to the session class.  COM+ did the equivalent thing with transactions.  In that case, components were used inside a "transaction stream".  The statefulness (ie..the current transaction) become a part of the Context (the environment).  The clients were instance agnostic, but the behavior of the instance changed slighly based on the particular context of execution.  The same technique could be used of NHibernate sessions if the state was externalized (ie..into the Request Cache in ASP.NET).  Then the clients could be instance agnostic and the Session would become a component.  The same can be said of a Session's database connection and transaction.  Another alternative (which I've seen several people do) would be to encapsulate the Session as state of a larger component (say..a Repository class).  The Repository becomes a component.  The Session becomes a part of the execution context (the environment).  This would allow multiple clients to use the same Repository instance, with the behavior varying slighly based on context.

posted @ Sunday, October 21, 2007 3:43 PM | Feedback (0)
The Insanity and the Irony

Here are a couple interesting questions to ask youself.

  • Could Windsor be extended to inject a Java dependency into my class?  This would involve adding some distributed computing code to Windsor.  The code would have to be very standards-compliant for the interop scenario.
  • Could a WCF Service host inject class dependencies into my service layer classes?
  • Could WCF or Windsor be extended to provide event-based mediation between two decoupled classes?

You see, not many people have noticed, but there is a common thread of thought amoung these very different technologies.  One groups works over there and uses one set of terminology.  Another group works elsewhere using a different set of terminology.

I would like to fundamentally challenge each and every person who reads this post on their view of WCF, COM+, and Windsor.

Context-Based Class Services

You see, each of the three technologies rely on the same underlying ideas--even if they have different names.  They all manage the environment in which a class instance runs.

WCF manipulates the environment (think behaviors and binding) to enable distributed computing.  It does this to handle interop scenarios (ie..with Java).  It does this to handle various activation scenarios (singleton anyone?).  It handles transactions.  It also handles a whole host of other things.  Some would argue that WCF works quite well even for services on a single server (they do have an named pipes transport after all).

Windsor manipulates the environment (think Castle.DynamicProxy) to provide a very similar set of context-based services.  It handles lifestyles (singleton anyone?).  It can handle transactions (with a little extra help).  And it handles a whole host of other things (not to mention IoC).

COM+ also manipulates the environment (using Contexts) to provide a nearly identical stack of services as WCF and Windsor.  Transactions?  Yep.  Activation/Lifestyles? Yep.

Yes, windsor is much more light weight.  That's beside the point.  These three things are all built on the exact same patterns.

They all value configuration over code (which is slightly different than the ruby value statement).

If you are using Windsor today, is there a reason why WCF couldn't replace Windsor in your codebase (if someone were to create both local and remote IoC behaviors)?  Remote dependency injection, now there's a concept.  What if your Windsor configuration was replaced by a centralized repository (ie..a service which might live on another machine) that was used to resolve dependencies?  What if Windsor understood UDDI for configuration?

If you are using WCF today, is there a reason that Windsor couldn't replace WCF if there was a remoting-type stack built into Windsor?  What if Windsor could interop with Spring.NET?  It parallels the Java/.NET Interop of WCF.

Ironically enough, even COM+ had publish/subscribe.  Neither Windsor nor WCF offer any type of publish/subscribe facilities/bindings.

At some point, these things need to converge.  They all do the same thing.  WCF was an evolution of COM+, but we still see sets of features that are missing.

The truth is, they all provide Component Services.

What if Microsoft built local and remote IoC into WCF?  What if that also included basic Pub/Sub?

posted @ Sunday, October 21, 2007 1:20 AM | Feedback (4)
Thursday, October 18, 2007
Putting It All Together: Objects, Components, and Services

I'm just going to throw this out there for now.  Feedback is greatly welcomed (both positive and negative).


 Update:  I think I need to clarify the relationship between Capabilities and Processes.

posted @ Thursday, October 18, 2007 11:21 PM | Feedback (4)
Wednesday, October 17, 2007
Screencast: Test-Driven Domain Model

I put together a TDD screencast this week after having the same conversation more than once.  It boils down to the topic of whether people can actually write their unit tests before writing their code.  With this screencast, I wanted to illustrate that it's not only possible, but that it's also highly productive (once you get the tooling right).

This is not an introduction to TDD, nor an introduction to domain modeling, DDD, or any other high level concept.

If you want more information on the techniques used in this screencast, I will direct you to the following resources:

  • The Domain Model Pattern
    • Very Brief Writeup on Martin Fowler's Blinki (I recommend you add his feed to your RSS reader)
    • A longer description can be found in his book, Patterns of Enterprise Application Architecture, along with complementary and alternative architecture patterns.  PoEAA is the authoritative book on a multitude of architecture patterns as found in the wild.
    • A highly recommended methodology on building domain model applications can be found in Eric Evans book, Domain Driven Design (also lovingly refered to as DDD).  I highly recommend it as well.
  • Test Driven Development
  • Object-Oriented Programming
    • This is the foundation for everything else.  If you can't name at least three principles of object-orientation (and I'm not talking about "polymorphism", "encapsultation", etc), then I recommend brushing up on them.
    • Robert Martin does a good job laying them out in Agile Principles, Patterns, and Practices in C#
    • For advanced learning, people tend to go with one of the Head First books or Craig Larman's book.  I've mostly seen people practicing Responsibility-Driven Design (within the context of TDD/DDD) in the wild.

You can download both the screencast (Windows Media - 50 MB) and sourcecode here.

The tools used in this screencast include ReSharper, MbUnit, and Test Driven.NET.

I'll try and get another screencast up soon which shows building domain services, the service layer, and data access (ie.. putting the domain model to work).

Please feel free to email me if you have questions/flames/comments on this in the mean time.  My email address is evan@thisdomain.com.

kick it on DotNetKicks.com
posted @ Wednesday, October 17, 2007 6:47 PM | Feedback (13)
Pragmatic Dogma

While reading Greg Young's post on the topic of the ubiquitous language and behavior driven development, something stuck out at me.  I am quoting Greg who is quoting Eric Evans:

Alas, I too have had stakeholders such as what Scott describes. In fact thinking back many of them were in the sorts of domains that I would not recommend DDD and recently Eric Evans has also had had this discussion.

I became more and more aware that one of the basic mistakes that model enthusiasts made from the start was the idea that we should just model everything, that the whole system should modeled and object oriented and so on. what I have started to realize is that that dilutes the effort to the point where we don't really ever get the bang for the modeling buck and that in fact most systems are probably 90% CRUD (create, read, update, delete) and that there are simpler solutions to that problem.

I'll leave you with this thought:

Pragmatism without context is really dogma in disguise.  We learned this long ago when defining software patterns.  There is a higher level of understanding which exists of nearly everything.  You will know you've reached that level of understanding after you have fully understood the item, and then understood it's limitations.  Until you can grasp the limitations, be wary of the dogma effect.

That being said, I do think the domain model pattern is grossly underused in the enterprise application space.

posted @ Wednesday, October 17, 2007 6:17 PM | Feedback (2)
Wednesday, October 10, 2007
Operator Overloads and Value Objects

In many cases, we tend to overlook important abstractions in our object models.  Emails and Phone Numbers are two common ones.  A lot of times these are immutable value objects, to borrow from DDD.  A lot of these guys are perfect for operator overloading.  Here's a simple example:

 

    public class Email : IEquatable<Email>
    {
        public Email(string address)
        {
            if (string.IsNullOrEmpty(address) || ! Validate(address))
            {
                throw new InvalidEmailException(address);                
            }
            _address = address;
        }

        private bool Validate(string address)
        {
            //insert simple regex here
            return true;
        }

        private readonly string _address;

        public string Address
        {
            get { return _address; }
        }

        public static implicit operator Email(string address)
        {
            return new Email(address);
        }

        public static implicit operator string(Email email)
        {
            return email.Address;
        }

        public bool Equals(Email email)
        {
            if (email == null) return false;
            return Equals(_address, email._address);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            return Equals(obj as Email);
        }

        public override int GetHashCode()
        {
            return _address.GetHashCode();
        }
    }


There's a bit of noise there, but here's what it gives us:

            Email me = "myfirstname@evanhoff.com";
            string address = me;


How about a little design by contract goodness:

 

    public class EmailSender
    {
        public void Send(Email to, Email from, string subject, string body)
        {
            //implementation
        }
    }

With usage:

            EmailSender sender = new EmailSender();
            sender.Send("myfirstname@evanhoff.com", "johndoe@hotmail.com", "test subject", "test body");


You'll notice that the compiler will automagically use the implicit string conversion.  In addition, we have DbC enforced as part of the conversion process.  You'll also notice I overrode Equals and GetHashCode for value-based comparison semantics (ok, ok, so ReSharper overrode them for me..lol).

This works great for a lot of other "missing abstractions" also.

 

    public class Phone : IEquatable<Phone>
    {
        private readonly string _number;

        public Phone(string number)
        {
            if (string.IsNullOrEmpty(number) || ! Validate(number))
            {
                throw new InvalidPhoneException(number);
            }
            _number = number;
        }

        private bool Validate(string number)
        {
            //insert validation here
            return true;
        }

        public string Number
        {
            get { return _number; }
        }

        public static implicit operator Phone(string number)
        {
            return new Phone(number);
        }

        public static implicit operator string(Phone phone)
        {
            return phone.Number;
        }

        public bool Equals(Phone phone)
        {
            if (phone == null) return false;
            return Equals(_number, phone._number);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            return Equals(obj as Phone);
        }

        public override int GetHashCode()
        {
            return _number.GetHashCode();
        }
    }

    public class InvalidPhoneException : Exception
    {
        private readonly string _number;

        public InvalidPhoneException(string number)
        {
            _number = number;
        }

        public string Number
        {
            get { return _number; }
        }

        public override string Message
        {
            get { return string.Format("Invalid Phone Number: {0}", _number); }
        }
    }
Note: All of the above is "blog code".  It doesn't have unit tests, so I'm not going to say it's bug free.
posted @ Wednesday, October 10, 2007 11:40 PM | Feedback (4)
Simple Object-Orientation and Component-Orientation Side by Side

Object-Orientation:

 


Component-Orientation:


 

Looking at the example above, I notice there's a fairly large discrepancy in lines of code.  That was mostly a consequence of the trivial example I am using.  Don't read into that.

There's more coming on this stuff, but this is enough for today.  Next, we can look at the two forms of inheritance.

posted @ Wednesday, October 10, 2007 11:12 PM | Feedback (1)
Component Orientation

Yes, people, fasten your seatbelts.  Time for a quick introduction to an often misunderstood topic.  The term "component" is about as overloaded as the terms "service" and "object".  Please read this with your "curiosity" hat on.  I'm only attempting to inform here.

Pick a random developer off the street, and they will probably even give the same definition for each.  They are all about creating abstractions on a problem domain.  They all claim to promote reuse.  They all promote encapsulation.  And, they are all generally misunderstood and misapplied in the .NET community.

So what's the difference?  The difference between an object and a service is probably the easiest to see, but what about that component?  Let's focus on the object and the component for now.

Principles of Object-Orientation:

  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Single Choice Principle
  • Stable Abstractions Principle

Packaging Principles:

  • Acyclic Dependencies Principle
  • Release Reuse Equivalency Principle
  • Common Closure Principle
  • Common Reuse Principle
  • Acyclic Dependencies Principle
  • Stable Dependencies Principle
  • Stable Abstractions Principle

If these look foreign to you, I'd recommend you skip the rest of this article and grab a good book on OOP.  It'll change your professional life forever, I promise.  I often recommend Bob Martin's book.  He also has some great PDF articles available on the web (under Design Principles).

I'm largely going to skip over the OO stuff and assume you have a good handle on that programming paradigm.

I'll skip the fluff and go straight for the meat on components.

Defining a software component:

A software component is a unit of composition with contractually specified interfaces and explicit context dependencies only.  A software component can be deployed independently and is subject to composition by third parties.

--From the 1996 European Conference on OO Programming

Characteristics of a software component [Szy]:

  • is a unit of independent deployment
  • is a unit of third party composition
  • has no externally visible state

Characteristics of an object [Szy]:

  • is a unit of instantiation, each instantiation has a unique identity
  • may have state, and its state may be externally visible
  • encapsulates state and behavior

Principles of Component-Orientation [Low]:

  • Separation of Interface and Implementation
  • Binary Compatibility
  • Language Independence
  • Location Transparency
  • Concurrency Management
  • Version Control
  • Component-based Security

Tomorrow we will take a deeper look at what this means in terms of c# code and our development environment.

[Szy] : Component Software by Clemens Szyperski
[Low] : Programming .NET Components by Juval Lowy

posted @ Wednesday, October 10, 2007 12:54 AM | Feedback (3)