| |
Archive for the ‘Testing’ Category
Tuesday, September 30th, 2008
“We need to rewrite the system.”
Thus begins the story of yet another developer trying to convince their manager to adopt test-driven development (or any other methodology or technology). There’s a good chance this developer’s been reading all sorts of stuff on blogs (like those linked here) that have convinced him that salvation lies that way.
Don’t get me wrong.
There’s a good chance the developer’s right.
It’s just that that’s besides the point.
Developers and Managers
There’s a difference between how developers view a practice and how a manager (defined for the purposes of this post as someone in charge of delivering something) view that same practice. From a developer perspective, Ian’s point about unit testing is spot on:
“The problem is that the most important step is not doing it right, but doing it at all.”
Yet, as Ian himself points out in the title, this is a learning issue. If you want to learn to swim, there’s no replacement for jumping in the pool.
The manager’s perspective is a bit different.
Yes, we want our developers to improve their skill set. Yes, we understand that unit testing will ultimately improve quality. Yes, we know developers need to practice these skills as a part of their job. But, and it’s a big ole’ but, when it comes time to sink or swim, and we’ve got a deadline, those desires need to be balanced with delivering. Accounts of unit testing adoption efforts resulting in more (test) code to support with little apparent improvement in quality in the short term, well, they scare us. Arnon’s post gives more links supporting that feeling.
What’s a Unit Test anyway?
Is it any class that happens to have a TestFixture attribute on it?
If we are to “decouple” unit testing from good design, as Roy has described, that’s a not-improbable outcome. If the design of the system is such as there aren’t any real “units”, what exactly are we testing? Regardless of static or dynamic typing, replaceability of code, and other technological things, does the fact that all TestMethods in that TestFixture complete successfully mean anything? In other words, what did the test test?
It is clear that these tests cost something.
It’s more code to write. It’s more code to maintain.
The question is, what value are we getting from these “unit tests that any developer without design skills can write”?
The manager in me doesn’t like this return on investment.
By the way, TDD is as much the evolution of unit testing as the screw driver is the evolution of the hammer. But that’ll have to wait for a different post.
What’s Design Got To Do With It?
If you’re looking for the technical ability to write a test fixture and replace calls to other classes, then design has nothing to it.
If tests are to be valuable - design has everything to do with it.
The difficulty our developer is having unit-testing the system is a symptom of design problems. There’s a good chance that’s why he suggested a rewrite.
By the way, please do a search & replace in your vocabulary on the word “rewrite” with the word “redesign”. The code’s syntax isn’t the problem - it’s not the “m_”, camel case, or anything like that. It’s not that if the code was rewritten under the same design that all problems will go away.
Redesign, or do nothing.
The community’s been discussing the issues of coupling, interfaces, mocking, and tools at length in the context of testability. I won’t reiterate the debate here but I’ll tell you this:
If logic is duplicated, if the code is tightly coupled, if there is no separation of concerns, the unit tests will be useless - even if they “test” the class in isolation.
Cut the coverage crap
Metrics lie.
The fact that there’s a bunch of other code which calls 100% of the system’s code and doesn’t contain false assertions doesn’t mean that the code is high quality or doesn’t contain bugs.
In a well designed system, most “logic” will be contained in two “layers” - the controllers and the domain model. These classes should be independent of any and all technological concerns. You can and should get high unit test coverage on classes in these layers. Shoot for 100%, it’s worth it.
Testing domain models is all about asserting state. While using setters to get the domain objects into a necessary initial state is OK, setters should not be used beyond that. Testing controllers is primarily about interactions - mocks will probably be needed for views and service agents. Commands do not need to be mocked out.
Most other layers have some dependence on technology that makes unit tests relatively less valuable. Coverage on these layers is most meaningless. My guidance is to take the effort that would have been spent on unit testing these other layers and invest it all in automated integration tests. You’re likely to get a much higher return on investment. Much higher.
Much.
Everybody’s Right
Developers aren’t just born knowing good design, testing, or anything else. Universities, colleges, and most vendors do little to change that state of affairs. Books help, a bit, but when learning to swim, you’ve got to get your feet wet, and on the job training is, by and large, all there is. As such, lowering the barrier to entry is important.
Keeping in mind the Dreyfus model of knowledge acquisition, it’s not about “dumbing down” software development, it’s about bringing novices up to speed:
“In the beginning [novices] learn to recognize objective facts and features, relevant to the skill. Characteristic of relevant elements are that they can be recognized context-free, i.e. without reference to the overall situation. The novice acquire basic rules to follow, acting upon those facts and features. The rules are also context-free, i.e. no notice is taken to the surroundings. On account of this the novice feels very little responsibility for the result.” (emphasis mine)
Managers are ultimately responsible for the result.
Managers shouldn’t necessarily sacrifice their projects on this altar of learning. Organizations need to find ways for developers to safely practice these techniques as a part of developing their “human resources”. First of all, this needs to be communicated to everyone - that the organization understands the importance of these techniques, the desires of developers to adopt them, and the projects that need to be delivered.
Some projects may be allocated additional non-functional requirements: the software will be developed test-first, there will be at least 80% unit test coverage, etc. It can make sense to have developers spend some time on these projects after finishing one more delivery focused project and before going onto another one. As more developers become proficient with unit testing and design, the delivery focused projects can start to benefit from these skills.
It’s a gradual process.
The Important Bit
No matter how you go about unit testing, do periodic test reviews.
Just like code reviews.
That’s it.
Related Posts
Business Process Verification
Self documenting and Test-Driven Alien Artifacts
SOA Testing
Posted in Development, Management, Testing, The Team | 8 Comments »
Monday, June 30th, 2008
This topic is getting more play as more people are using WCF and WF in real-world scenarios, so I thought I’d pull the things that I’ve been watching in this space together:
Reliability
Locking in SqlWorkflowPersistenceService (via Ron Jacobs) where, if you want predictable persistence (MS: ‘none of our customers asked for this to be easy’), you need to use a custom activity (which Ron was kind enough to supply).
“Given what I learned today I’d have to say that I’d be very careful about using workflows with an optimistic locking. Detecting these types of situations is not that simple.”
Let’s think about that. If we’re doing pessimistic locking, we get into the problem of, if a host restarts (as the result of a critical windows patch or some other unexpected occurrence), that the workflow won’t be able to be handled by any other host in the meantime (you didn’t care so much about your SLA, did you?).
Luckily, someone’s come up with a hack that works around this robustness problem in Scalable Workflow Persistence and Ownership.
“So this code will attempt to load workflow instances with expired locks every second. Is it a hack? Yes. But without one of two things in the SqlWorkflowPersistenceService its the sort of code you have to write to pick up unlocked workflow instances robustly.”
This will seriously churn the table used to store your workflows, decreasing performance of workflows that haven’t timed out. Oh well.
Testability
Implementing WCF Services without Referencing WCF (via Mark Seemann):
“More than a year ago, I wrote my first post on unit testing WCF services. One of my points back then was that you have to be careful that the service implementation doesn’t use any of the services provided by the WCF runtime environment (if you want to keep the service testable). As soon as you invoke something like OperationContext.Current, your code is not going to work in a unit testing scenario, but only when hosted by WCF.”
After pointing out some of the more basic difficulties in testability a straightforward WCF implementation brings, Mark turns the heat up in his follow-up post, Modifying Behavior of WCF-Free Service Implementations:
“Perhaps you need to control the service’s ConcurrencyMode, or perhaps you need to set UseSynchronizationContext. These options are typically controlled by the ServiceBehaviorAttribute. You may also want to provide an IInstanceProvider via a custom attribute that implements IContractBehavior. However, you can’t set these attributes on the service implementation itself, since it mustn’t have a reference to System.ServiceModel.”
Wow - all the things required to make a WCF service scalable and thread-safe make it difficult to test. In the end, we’re beginning to see how many hoops we have to go through in order to get separation of concerns, but until we can take all this and get it out of our application code, it’s an untenable solution. I hope Mark will continue with this series, if only so I can take the framework that might grow out of it and use it as a generic WCF transport for NServiceBus.
Comparison
After the Neuron-NServiceBus comparison that Sam and I had, we talked some more. After going through some of the rational and thinking, Sam even put nServiceBus into his WCF-Neuron comparison talk. Sam had this to say about nServiceBus:
“The bottom line is: I like what I see. Although it’s a framework, not an ESB product like Neuron, it’s a powerful framework that takes the right approach on SOA and enforces a paradigm of reliable one-way, *non-blocking* calls. That is the point of the talk tonight overall; we need to get away from the stack world of synchronous RPC calls to true asynchronous non-blocking message based SOA systems.”
The main concern I have with a WCF+WF based solution is that developers need to know a lot in order to make it testable, scalable, and robust. In nServiceBus, that’s baked into the design. It would be extremely difficult for a developer writing application logic to interfere with when persistence needs to happen, or the concurrency strategy of long-running workflows. The fact that message handlers in the service layer don’t need concurrency modes, instance providers, or any of that junk make them testable by default.
Posted in NServiceBus, Reliability, Scalability, Testing, WCF, Workflow | No Comments »
Monday, February 4th, 2008
Sagas have always been designed with unit testing in mind. By keeping them disconnected from any communications or persistence technology, it was my belief that it should be fairly easy to use mock objects to test them. I’ve heard back from projects using nServiceBus this way that they were pleased with their ability to test them, and thought all was well.
Not so.
The other day I sat down to implement and test a non-trivial business process, and the testing was far from easy. Now as developers go, I’m not great, or an expert on unit testing or TDD, but I’m above average. It should not have been this hard. And I tried doing it with Rhino.Mocks, TypeMock, and finally Moq. It seemed like I was in a no-mans-land, between trying to do state-based testing, and setting expectations on the messages being sent (as well as correct values in those messages), nothing flowed.
Until I finally stopped trying to figure out how to test, and focused on what needed to be tested. I mean, it’s not like I was trying to build a generic mocking framework like Daniel.
Here’s an example business process, or actually, part of one, and then we’ll see how that can be tested. By the way, there will be a post coming soon which describes how we go about analysing a system, coming up with these message types, and how these sagas come into being, so stay tuned. Either that, or just come to my tutorial at QCon.
On with the process:
1. When we receive a CreateOrderMessage, whose “Completed” flag is true, we’ll send 2 AuthorizationRequestMessages to internal systems (for managers to authorize the order), one OrderStatusUpdatedMessage to the caller with a status “Received”, and a TimeoutMessage to the TimeoutManager requesting to be notified – so that the process doesn’t get stuck if one or both messages don’t get a response.
2. When we receive the first AuthorizationResponseMessage, we notify the initiator of the Order by sending them a OrderStatusUpdatedMessage with a status “Authorized1”.
3. When we get “timed out” from the TimeoutManager, we check if at least one AuthorizationResponseMessage has arrived, and if so, publish an OrderAcceptedMessage, and notify the initator (again via the OrderStatusUpdatedMessage) this time with a status of “Accepted”.
And here’s the test:
public class OrderSagaTests
{
private OrderSaga orderSaga = null;
private string timeoutAddress;
private Saga Saga;
[SetUp]
public void Setup()
{
timeoutAddress = “timeout”;
Saga = Saga.Test(out orderSaga, timeoutAddress);
}
[Test]
public void OrderProcessingShouldCompleteAfterOneAuthorizationAndOneTimeout()
{
Guid externalOrderId = Guid.NewGuid();
Guid customerId = Guid.NewGuid();
string clientAddress = “client”;
CreateOrderMessage createOrderMsg = new CreateOrderMessage();
createOrderMsg.OrderId = externalOrderId;
createOrderMsg.CustomerId = customerId;
createOrderMsg.Products = new List<Guid>(new Guid[] { Guid.NewGuid() });
createOrderMsg.Amounts = new List<float>(new float[] { 10.0F });
createOrderMsg.Completed = true;
TimeoutMessage timeoutMessage = null;
Saga.WhenReceivesMessageFrom(clientAddress)
.ExpectSend<AuthorizeOrderRequestMessage>(
delegate(AuthorizeOrderRequestMessage m)
{
return m.SagaId == orderSaga.Id;
})
.ExpectSend<AuthorizeOrderRequestMessage>(
delegate(AuthorizeOrderRequestMessage m)
{
return m.SagaId == orderSaga.Id;
})
.ExpectSendToDestination<OrderStatusUpdatedMessage>(
delegate(string destination, OrderStatusUpdatedMessage m)
{
return m.OrderId == externalOrderId && destination == clientAddress;
})
.ExpectSendToDestination<TimeoutMessage>(
delegate(string destination, TimeoutMessage m)
{
timeoutMessage = m;
return m.SagaId == orderSaga.Id && destination == timeoutAddress;
})
.When(delegate { orderSaga.Handle(createOrderMsg); });
Assert.IsFalse(orderSaga.Completed);
AuthorizeOrderResponseMessage response = new AuthorizeOrderResponseMessage();
response.ManagerId = Guid.NewGuid();
response.Authorized = true;
response.SagaId = orderSaga.Id;
Saga.ExpectSendToDestination<OrderStatusUpdatedMessage>(
delegate(string destination, OrderStatusUpdatedMessage m)
{
return (destination == clientAddress &&
m.OrderId == externalOrderId &&
m.Status == OrderStatus.Authorized1);
})
.When(delegate { orderSaga.Handle(response); });
Assert.IsFalse(orderSaga.Completed);
Saga.ExpectSendToDestination<OrderStatusUpdatedMessage>(
delegate(string destination, OrderStatusUpdatedMessage m)
{
return (destination == clientAddress &&
m.OrderId == externalOrderId &&
m.Status == OrderStatus.Accepted);
})
.ExpectPublish<OrderAcceptedMessage>(
delegate(OrderAcceptedMessage m)
{
return (m.CustomerId == customerId);
})
.When(delegate { orderSaga.Timeout(timeoutMessage.State); });
Assert.IsTrue(orderSaga.Completed);
}
}
You might notice that this style is a bit similar to the fluent testing found in Rhino Mocks. That’s not coincidence. It actually makes use of Rhino Mocks internally. The thing that I discovered was that in order to test these sagas, you don’t need to actually see a mocking framework. All you should have to do is express how messages get sent, and under what criteria those messages are valid.
If you’re wondering what the OrderSaga looks like, you can find the code right here. It’s not a complete business process implementation, but its enough to understand how one would look like:
using System;
using System.Collections.Generic;
using ExternalOrderMessages;
using NServiceBus.Saga;
using NServiceBus;
using InternalOrderMessages;
namespace ProcessingLogic
{
[Serializable]
public class OrderSaga : ISaga<CreateOrderMessage>,
ISaga<AuthorizeOrderResponseMessage>,
ISaga<CancelOrderMessage>
{
#region config info
[NonSerialized]
private IBus bus;
public IBus Bus
{
set { this.bus = value; }
}
[NonSerialized]
private Reminder reminder;
public Reminder Reminder
{
set { this.reminder = value; }
}
#endregion
private Guid id;
private bool completed;
public string clientAddress;
public Guid externalOrderId;
public int numberOfPendingAuthorizations = 2;
public List<CreateOrderMessage> orderItems = new List<CreateOrderMessage>();
public void Handle(CreateOrderMessage message)
{
this.clientAddress = this.bus.SourceOfMessageBeingHandled;
this.externalOrderId = message.OrderId;
this.orderItems.Add(message);
if (message.Completed)
{
for (int i = 0; i < this.numberOfPendingAuthorizations; i++)
{
AuthorizeOrderRequestMessage req = new AuthorizeOrderRequestMessage();
req.SagaId = this.id;
req.OrderData = orderItems;
this.bus.Send(req);
}
}
this.SendUpdate(OrderStatus.Recieved);
this.reminder.ExpireIn(message.ProvideBy - DateTime.Now, this, null);
}
public void Timeout(object state)
{
if (this.numberOfPendingAuthorizations <= 1)
this.Complete();
}
public Guid Id
{
get { return id; }
set { id = value; }
}
public bool Completed
{
get { return completed; }
}
public void Handle(AuthorizeOrderResponseMessage message)
{
if (message.Authorized)
{
this.numberOfPendingAuthorizations–;
if (this.numberOfPendingAuthorizations == 1)
this.SendUpdate(OrderStatus.Authorized1);
else
{
this.SendUpdate(OrderStatus.Authorized2);
this.Complete();
}
}
else
{
this.SendUpdate(OrderStatus.Rejected);
this.Complete();
}
}
public void Handle(CancelOrderMessage message)
{
}
private void SendUpdate(OrderStatus status)
{
OrderStatusUpdatedMessage update = new OrderStatusUpdatedMessage();
update.OrderId = this.externalOrderId;
update.Status = status;
this.bus.Send(this.clientAddress, update);
}
private void Complete()
{
this.completed = true;
this.SendUpdate(OrderStatus.Accepted);
OrderAcceptedMessage accepted = new OrderAcceptedMessage();
accepted.Products = new List<Guid>(this.orderItems.Count);
accepted.Amounts = new List<float>(this.orderItems.Count);
this.orderItems.ForEach(delegate(CreateOrderMessage m)
{
accepted.Products.AddRange(m.Products);
accepted.Amounts.AddRange(m.Amounts);
accepted.CustomerId = m.CustomerId;
});
this.bus.Publish(accepted);
}
}
}
All this code is online in the subversion repository under /Samples/Saga.
Questions, comments, and general thoughts are always appreciated.
Posted in Autonomous Services, Business Rules, EDA, ESB, NServiceBus, Pub/Sub, SOA, Testing, Workflow | 2 Comments »
Saturday, September 1st, 2007
After reading Derek Hatchard’s post, The Art and War of Estimating and Scheduling Software, I wanted to follow up on my previous post on the topic, Don’t Trust Developers with Project Management. The problem lies with individualistic thinking.
Developers, and managers too for that matter, by and large are concerned with “productivity”. Developers want the latest tools and technologies so that they can churn out more code faster. Managers create schedules trying to get the maximum efficiency out of each one of their developers. They consider resource utilization and other terms that sound manager-ish.
Fact is, on medium to large sized projects, if you look at the studies you’ll find that developer productivity when measured as total lines of (non-blank) code of the system in production divided by the total number of developer days comes in roughly at 6. Maybe 7.
7 lines of code a day.
Let that sink in for a second.
I can hear the managers screaming already. OMFG, what were they doing all day long?! It takes, what, 10 minutes to put out 7 lines of code? An hour even, if it’s complicated recursive code and stuff. And they say they don’t like us micro-managing them?! Now we know why. It’s because they’re goofing off all day long.
Well, managers, that’s not really the way it goes. You see, you have to take into account the time it took to learn the technology, tools, frameworks, etc. Add to that the time of understanding the requirements, which is really sitting through boring meetings that don’t explain much. Finally, our poor developer actually gets to implement the requirement. Maybe run the system a couple of times, trying out the feature they implemented, and checking the code in.
Well, that’s actually the easy part. Now comes the part which kills most of the time. After a bunch of features have been developed by the team, the testers start banging away at it and find a bunch of bugs. Now the developer has to reverse-engineer some bizarre system behavior and figure out which part of the system is to blame. That involves usually some educated guessing (unless they’ve just joined the team and have been put in the bug-fixer role to “learn the system”, in which case it is thoroughly UNeducated guessing). They change some code, run the system, which looks like its been fixed, check the new code in, and close the bug.
But the bugs keep coming. And as the project progresses towards production, more and more of the developers time is spent looking through code and changing existing code, that actually writing new code.
And the larger the system, the more bugs. And I don’t mean that the number of bugs linearly increases with lines of code, or number of features. It’s probably closer to exponential. If it’s a mission critical system, the performance bugs will be taking an order of magnitude more time to fix than other bugs.
So, as you can see, getting a system into production is a team effort. It includes the developers and testers, of course, but also management, and the customer, and how they manage scope. This is kind of a “duh” statement, but we’re getting to the punch-line.
If getting a system into production involves the entire team, isn’t that obviously true for each feature too?
In which case, why are we asking just the developers to estimate the time it takes to get a feature “done”? Why are we trying so hard to measure their productivity?
I know why. It’s so we can get rid of the less productive ones and give bonuses to the more productive ones!
Back to the main issue. I don’t “trust” developer estimates because I need to see the team’s capability to put features in production. The involves all aspects, and often many team members, in some cases multiple developers going through the same code. This involves all overhead and cross team communication, sick days, etc. It’s also why I try to get multiple data points over time to understand the team’s velocity.
While I care about the quality of my developers, and testers, and everybody on my team and would like them to be able to estimate their work as best they can, I’ve got a project to put into production. And the best way I’ll know when it’ll go into production is by having data that’ll enable me to state to my management:
“Our team is finishing 20 feature-units a month, we’ve got 200 feature-units to go, so we’ll be done in around 10 months.”
If I’m busy micro-measuring each developers estimates, I won’t have the time to see the forest. By first taking a harsh look at the reality of what the team can do, I can start looking for ways to make it better. Maybe the bottleneck is between analysts and developers, maybe we’re seeing the same bugs regressing many times, but until we know where we are, we can’t run controlled experiments to see what makes us better.
Focusing on the individual developer, getting them the latest and greatest tools may be great for their morale, but it probably won’t make a bit of difference to their actual productivity.
Next time - what to do when management asks you what it’ll take to be done sooner.
Posted in Agile, Development, Management, Projects, Testing, The Team | 2 Comments »
Monday, August 6th, 2007
What with all the warm and fuzzy feelings around trusting developers (here, here, and here) I just have to tone it down a bit. The title takes it a bit far - but less than you might think. Just today I had a talk with one of the team leads on the project I’m consulting on. It boiled down to this:
Developers don’t know how to estimate.
Or more specifically, the variance in the actual completion time of a feature from the estimate given by a developer increases probably exponentially with time.
For example, if the estimate is a day, you can expect it to be finished in around a day. If the estimate is a week (5 works days), it will probably vary between 4-10 work days. If the estimate is a month, in all actuallity the developer probably doesn’t know enough to say but will answer when pressed.
This is why Ron (the team lead) asked me if I wasn’t worried I was putting myself in a lose-lose situation by changing the project structure. There were two “teams” when I came in - developers and testers. All the team leads had “committed” to “finishing” the project in 6 months. When I originally proposed the change to more feature-driven teams, mixing skilled and newer developers and testers together on the same team, came the cry:
“It’ll take us twice as long this way.”
“It’s so much less efficient than before.”
And on, and on. What was funny to me was that 3 of the “6″ months were already gone and not a single feature worked. We were half “gone”, and nowhere near half done.
The thing is that Ron was sure I was cooking my own goose with upper management. What he, and most other developers don’t know is that upper management has gotten used to the state of things. If developers say one month, management has seen enough history to know that it’ll really be 3-4 months. So when I come in and do things different from what developers are used to, upper management is thrilled - that’s why they brought me in the first place.
The difference is that by working based on features, and measuring project progress by feature-units completed per iteration, I drive down variability. This creates solid data about progress saying when we’ll be done (more or less). This is quite different from the “normal” course of many projects:
“OK, so it’s been 8 months now on your 6 month project. When will you guys be finished already?”
Without the data, your only strategy is hope: “Umm, I hope the developers will be done this week(?)”
Don’t get me wrong. I trust my developers and testers deeply. But it’s not their job to know how to estimate and manage projects. PMs who take developers estimates as is and stake the project on that being correct are setting themselves up for failure - with only themselves to blame.
Now back to your nice warm-and-fuzzy blogging… 
Posted in Management, Testing, The Team | 18 Comments »
Monday, June 4th, 2007
Some Technical Difficulties
Ayende and I had an email conversation that started with me asking what would happen if I added an Order to a Customer’s “Orders” collection, when that collection was lazy loaded. My question was whether the addition of an element would result in NHibernate hitting the database to fill that collection. His answer was a simple “yes”. In the case where a customer can have many (millions) of Orders, that’s just not a feasible solution. The technical solution was simple – just define the Orders collection on the Customer as “inverse=true”, and then to save a new Order, just write:
session.Save( new Order(myCustomer) );
Although it works, it’s not “DDD compliant”
In Ayende’s post Architecting for Performance he quoted a part of our email conversation. The conclusion I reached was that in order to design performant domain models, you need to know the kinds of data volumes you’re dealing with. It affects both internals and the API of the model – when can you assume cascade, and when not. It’s important to make these kinds of things explicit in the Domain Model’s API.
How do you make “transparent persistence” explicit?
The problem occurs around “transparent persistence”. If we were to assume that the Customer object added the Order object to its Orders collection, then we wouldn’t have to explicitly save orders it creates, so we would write service layer code like this:
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))
{
IOrderCreatingCustomer c = this.DbServices.Get<IOrderCreatingCustomer>(msg.CustomerId);
c.CreateOrder(message.OrderAmount);
scope.Complete();
}
On the other hand, if we designed our Domain Model around the million orders constraint, we would need to explicitly save the order, so we would write service layer code like this:
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))
{
IOrderCreatingCustomer c = this.DbServices.Get<IOrderCreatingCustomer>(msg.CustomerId);
IOrder o = c.CreateOrder(message.OrderAmount);
this.DbServices.Save(o);
scope.Complete();
}
But the question remains, how do we communicate these guidelines to service layer developers from the Domain Model? There are a number of ways, but it’s important to decide on one and use it consistently. Performance and correctness require it.
Solution 1: Explicitness via Return Type
The first way is a little subtle, but you can do it with the return type of the “CreateOrder” method call. In the case where the Domain Model wishes to communicate that it handles transparent persistence by itself, have the method return “void”. Where the Domain Model wishes to communicate that it will not handle transparent persistence, have the method return the Order object created.
Another way to communicate the fact that an Order has been created that needs to be saved is with events. There are two sub-ways to do so:
Solution 2: Explicitness via Events on Domain Objects
The first is to just define the event on the customer object and have the service layer subscribe to it. It’s pretty clear that when the service layer receives a “OrderCreatedThatRequiresSaving” event, it should save the order passed in the event arguments.
The second realizes that the call to the customer object may come from some other domain object and that the service layer doesn’t necessarily know what can happen as the result of calling some method on the aggregate root. The change of state as the result of that method call may permeate the entire object graph. If each object in the graph raises its own events, its calling object will have to propagate that event to its parent – resulting in defining the same events in multiple places, and each object being aware of all things possible with its great-grandchild objects. That is clearly bad.
What [ThreadStatic] is for
So, the solution is to use thread-static events.
[Sidebar] Thread-static events are just static events defined on a static class, where each event has the ThreadStaticAttribute applied to it. This attribute is important for server-side scenarios where multiple threads will be running through the Domain Model at the same time. The easiest thread-safe way to use static data is to apply the ThreadStaticAttribute.
Solution 3: Explicitness via Static Events
Each object raises the appropriate static event according to its logic. In our example, Customer would call:
DomainModelEvents.RaiseOrderCreatedThatRequiresSavingEvent(newOrder);
And the service layer would write:
DomainModelEvents.OrderCreatedThatRequiresSaving +=
delegate(object sender, OrderEventArgs e) { this.DbServices.Save(e.Order); };
The advantage of this solution is that it requires minimal knowledge of the Domain Model for the Service Layer to correctly work with it. It also communicates that anything that doesn’t raise an event will be persisted transparently behind the appropriate root object.
Statics and Testability
I know that many of you are wondering if I am really advocating the use of statics. The problem with most static classes is that they hurt testability because they are difficult to mock out. Often statics are used as Facades to hide some technological implementation detail. In this case, the static class is an inherent part of the Domain Model and does not serve as a Facade for anything.
When it comes to testing the Domain Model, we don’t have to mock anything out since the Domain Model is independent of all other concerns. This leaves us with unit testing at the single Domain Class level, which is pretty useless unless we’re TDD-ing the design of the Domain Model, in which case we’ll still be fiddling around with a bunch of classes at a time. Domain Models are best tested using State-Based Testing; get the objects into a given state, call a method on one of them, assert the resulting state. The static events don’t impede that kind of testing at all.
What if we used Injection instead of Statics?
Also, you’ll find that each Service Layer class will need to subscribe to all the Domain Model’s events, something that is easily handled by a base class. I will state that I have tried doing this without a static class, and injecting that singleton object into the Service Layer classes, and in that setter having them subscribe to its events. This was also pulled into a base class. The main difference was that the Dependency Injection solution required injecting that object into Domain Objects as well. Personally, I’m against injection for domain objects. So all in all, the static solution comes with less overhead than that based on injection.
Summary
In summary, beyond the “technical basics” of being aware of your data volumes and designing your Domain Model to handle each use case performantly, I’ve found these techniques useful for designing its API as well as communicating my intent around persistence transparency. So give it a try. I’d be grateful to hear your thoughts on the matter as well as what else you’ve found that works.
Related posts:
Posted in Architecture, Business Rules, DDD, Data Access, Databases, Dependency Injection, Development, NHibernate, OO, Performance, Simplicity, TDD, Testing, Threading | 11 Comments »
Monday, June 4th, 2007
Jimmy’s recent post called out some of the insights on the advantages of Ruby from Niclas’ keynote at DevSummit 2007. Jimmy writes:
In Ruby it’s easy to redefine the visibility of a method from private to public for testing purposes. This was just one small detail in his talk of course, but I started to think about how much pain I quite often go through regarding this in legacy code.
Let me just start out by saying that dealing with legacy code is far from easy. However, when writing new code, or as a part of refactoring that legacy, adding interfaces to your design can help you get around those visibility and testing issues.
For instance, if you only let “client” code access the interface, and not the implementation (probably using some kind of dependency injection), then you could leave all sorts of methods public on your concrete class without worry that the client will call them since the interface doesn’t expose them. Now that the methods on the concrete class are public, you can easily test that class.
The way to package your code to make sure this occurs follows a very simple design principle. This is much easier to put in practice on new development, but you’ll find that it isn’t that hard for legacy either. Since legacy code often doesn’t make use of interfaces, and the implementation is already packaged, and your new client code will already be separately packaged, you’re 90% there!
If you can change the legacy code, you’re actually 95% there. Just create a new package for the interface that the client code will use. Then change the legacy code to implement that interface - since the methods will be pretty much the same, it’s not that much work.
If you can’t change the legacy code, create a “wrapper” class that implements the interface and delegates the calls to the legacy code.
Finally, let me sum up by saying that I think Ruby is great. However, I think that often many advantages are attributed to anything new that may have already been possible/easy with what we already have today. Sometimes, the new stuff helps raise awareness on important issues - and then we can have great discussions on how to solve those issues with today’s (yesterday’s ?) technology 
Posted in Dependency Injection, Development, OO, Simplicity, TDD, Testing | No Comments »
Thursday, May 17th, 2007
I just read the kind of hoops you have to go through in order to test your WCF service implementations. Oh. My. GOD.
If that’s the best there is, NOBODY is going to be testing their WCF services. That’s scary.
When using this message-based design, your service implementations tend to look like this:
public class WorkflowMessageHandler : IMessageHandler
{
public void Handle(Stage1Msg msg)
{
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))
{
IWorkflow wf = this.DbServices.Get(msg.WorkFlowID);
wf.Handle(msg);
scope.Complete();
}
}
}
And it’s this easy to test them:
[TestMethod]
public void TestWorkflowMessageHandler()
{
WorkflowMessageHandler handler = new WorkflowMessageHandler();
handler.Bus = this.MockBus;
// set up expectations on bus in terms of messages returned
Stage1Msg msg = new Stage1Msg();
// fill msg with data
handler.Handle(msg);
// verify expectations on bus
}
That’s right, it’s just plain old unit testing the way we test everything else these days.
I’m beginning to get the impression that the new suite of technologies that is coming out of Microsoft is making things more complicated than they need to be.
Well, maybe that’s just me.
Posted in Architecture, SOA, Simplicity, Testing, WCF | No Comments »
Saturday, April 21st, 2007
When implementing a domain model, often object-relational mapping technologies are used. Like many tools, with their use comes the danger of abuse - abuse to the point of invalidating the benefits of the pattern itself.
From some pointers about how to use (and not to use) these tools, see why object-relational mapping sucks.
Martin Fowler’s has this to say about the Domain Model Pattern:
At its worst business logic can be very complex. Rules and logic describe many different cases and slants of behavior, and it’s this complexity that objects were designed to work with. A Domain Model creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form.
In short, using Object-Oriented techniques to handle the complexity.
A more comprehensive discussion about what happens when it is not used can be found under the Anemic Domain Model Anti-Pattern:
The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is very little behavior on these objects. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.
The fundamental horror of this anti-pattern is that it’s so contrary to the basic idea of object-oriented design; which is to combine data and process together. The anemic domain model is really just a procedural style design…
In terms of Domain-Driven Design, this pattern is also known as Domain Layer.
Domain Models do a lot for encapsulating Business Rules, thus making them amenable to automated testing. This hinges on keeping the Domain Model independent of things related to Data Access.
It is therefore almost required to use some kind of Object/Relational Mapping tool to make it possible to persist objects belonging to the domain model to databases and other kinds of storage.
The use of DataSets in .NET is often a sign of the Anemic Domain Model Anti-Pattern.
One thing to keep in mind when working on a domain model is that you probably won’t get it “right” the first time, and will have re-work the division of responsibility a couple of times. Techniques like Test-Driven Development help out immensely for that.
Posted in Business Rules, DDD, Data Access, DataSets, NHibernate, OO, TDD, Testing | 10 Comments »
Monday, April 16th, 2007
How much, and what kind of documentation do we need to create even if we have “self-documenting code”? Or is that kind of code enough all by itself? I for one yearn for the day where the code really will be enough, and I think that Scott and Ayende do too. First of all, I think that as time progresses, the size of systems that the average developer works on is increasing substantially. And the larger a system is, the more we find a kind of code/design dialect that developers use to talk about that system. I think that these dialects are significantly different between framework/open source code, and application code. So, when a new developer comes in, do we tell them to “just read the code”? Or if the application has gone into production some time ago and now needs to be enhanced but the original team is long gone, what can be done?
What I usually suggest (and practice) is to have some kind of documentation explaining “language” of the system – what things go together, how, and why; and just as importantly, what things must be kept apart. This can be a Software Architecture and Design document, or even videos of the design sessions where things were first discussed. The relevant requirements should be a part of this as well. We need to know that the reason asynchronous messaging was used was for the strenuous scalability requirements, otherwise we might start adding the high-productivity Visual Studio Web Services we like so much.
Continuous integration is a boon to projects who use them. But developers who are only familiar with building solutions in Visual Studio may not be used to working that way, keeping code checked out for weeks at a time.
Test-Driven Development and Architecture will help those who know about it. We should probably write something up about how the system should be enhanced. Side-effect or not, developers and testers will need to know how we test the system – what tools are used in which way and at which stage of the development lifecycle. We could reference existing methodologies as well as in what ways we deviate from them and why.
What sustainable business value do we provide by leaving behind us alien artifacts and practices? I’m not saying not to use state-of-the-art designs, techniques, and practices. On the contrary, I think that they are the key to sustainable business value. Necessary, but not sufficient. Documentation, of whatever flavor you find most suitable to each specific thing you are documenting, should be considered by the team as a whole, and the conclusions presented to stakeholders. The famous Chrysler C3 project’s long-term business value is shaky as the result of those stakeholders decision that documentation wasn’t necessary – in no way was the Agile process faulty in that respect.
Finally, you may be surprised the holes you find in your own thinking when forced to write down and explain to someone just coming in “how we do things around here”, I know I was. I can tell you that in the cases where I did that exercise, several stupid, costly mistakes were avoided. Fleshing out your thinking isn’t necessarily big design up front (BDUF), it’s just smart.
Posted in Agile, Architecture, Development, Management, TDD, Testing | 3 Comments »
|
|
|
Recommendations
Sam Gentile, Independent WCF & SOA Expert
“Udi, one of the great minds in this area. A man I respect immensely.”
Ian Robinson, Principal Consultant at ThoughtWorks
"Your blog and articles have been enormously useful in shaping, testing and refining my own approach to delivering on SOA initiatives over the last few years. Over and against a certain 3-layer-application-architecture-blown-out-to- distributed-proportions school of SOA, your writing, steers a far more valuable course."
Simon Segal, Systems Integration Manager at LinFox
“Udi is one of the outstanding software development minds in the world today, his vast insights into Service Oriented Architectures and Smart Clients in particular are indeed a rare commodity. Udi is also an exceptional teacher and can help lead teams to fall into the pit of success. I would recommend Udi to anyone considering some Architecural guidance and support in their next project.”
Ohad Israeli, Chief Architect at Hewlett-Packard, Indigo Division
“When you need a man to do the job Udi is your man! No matter if you are facing near deadline deadlock or at the early stages of your development, if you have a problem Udi is the one who will probably be able to solve it, with his large experience at the industry and his widely horizons of thinking , he is always full of just in place great architectural ideas.
I am honored to have Udi as a colleague and a friend (plus having his cell phone on my speed dial).”
Eli Brin, Program Manager at RISCO Group
“We hired Udi as a SOA specialist for a large scale project. The development is outsourced to India. SOA is a buzzword used almost for anything today. We wanted to understand what SOA really is, and what is the meaning and practice to develop a SOA based system.
We identified Udi as the one that can put some sense and order in our minds. We started with a private customized SOA training for the entire team in Israel. After that I had several focused sessions regarding our architecture and design.
I will summarize it simply (as he is the software simplist): We are very happy to have Udi in our project. It has a great benefit. We feel good and assured with the knowledge and practice he brings. He doesn’t talk over our heads. We assimilated nServicebus as the ESB of the project. I highly recommend you to bring Udi into your project.”
Yoel Arnon, MSMQ Expert
“Udi has a unique, in depth understanding of service oriented architecture and how it should be used in the real world, combined with excellent presentation skills. I think Udi should be a premier choice for a consultant or architect of distributed systems.”
Vadim Mesonzhnik, Development Project Lead at Polycom
“When we were faced with a task of creating a high performance server for a video-tele conferencing domain we decided to opt for a stateless cluster with SQL server approach. In order to confirm our decision we invited Udi.
After carefully listening for 2 hours he said: "With your kind of high availability and performance requirements you don’t want to go with stateless architecture."
One simple sentence saved us from implementing a wrong product and finding that out after years of development. No matter whether our former decisions were confirmed or altered, it gave us great confidence to move forward relying on the experience, industry best-practices and time-proven techniques that Udi shared with us.
It was a distinct pleasure and a unique opportunity to learn from someone who is among the best at what he does.”
Jack Van Hoof, Enterprise Integration Architect at Dutch Railways
“Udi is a respected visionary on SOA and EDA, whose opinion I most of the time (if not always) highly agree with. The nice thing about Udi is that he is able to explain architectural concepts in terms of practical code-level examples.”
Nick Malik, Enterprise Architect at Microsoft Corporation
“You are an excellent speaker and trainer, Udi, and I've had the fortunate experience of having attended one of your presentations. I believe that you are a knowledgable and intelligent man.”
Sean Farmar, Chief Technical Architect at Candidate Manager Ltd
“Udi has provided us with guidance in system architecture and supports our implementation of NServiceBus in our core business application.
He accompanied us in all stages of our development cycle and helped us put vision into real life distributed scalable software. He brought fresh thinking, great in depth of understanding software, and ongoing support that proved as valuable and cost effective.
Udi has the unique ability to analyze the business problem and come up with a simple and elegant solution for the code and the business alike. With Udi's attention to details, and knowledge we avoided pit falls that would cost us dearly.”
Motty Cohen, SW Manager at KorenTec Technologies
“I know Udi very well from our mutual work at KorenTec. During the analysis and design of a complex, distributed C4I system - where the basic concepts of NServiceBus start to emerge - I gained a lot of "Udi's hours" so I can surely say that he is a professional, skilled architect with a fresh ideas and unique perspective for solving complex architecture challenges. His ideas, concepts and parts of the artifacts are the basis of several state-of-the-art C4I systems that I was involved in their architecture design.”
Aaron Jensen, VP of Engineering at Eleutian Technology
“Awesome. Just awesome.
We’d been meaning to delve into messaging at Eleutian after multiple discussions with and blog posts from Greg Young and Udi Dahan in the past. We weren’t entirely sure where to start, how to start, what tools to use, how to use them, etc. Being able to sit in a room with Udi for an entire week while he described exactly how, why and what he does to tackle a massive enterprise system was invaluable to say the least.
We now have a much better direction and, more importantly, have the confidence we need to start introducing these powerful concepts into production at Eleutian.”
Gad Rosenthal, Department Manager at Retalix
“A thinking person. Brought fresh and valuable ideas that helped us in architecting our product. When recommending a solution he supports it with evidence and detail so you can successfully act based on it. Udi's support "comes on all levels" - As the solution architect through to the detailed class design. Trustworthy!”
Robert Lewkovich, Product / Development Manager at Eggs Overnight
“Udi's advice and consulting were a huge time saver for the project I'm responsible for. The $ spent were well worth it and provided me with a more complete understanding of nServiceBus and most importantly in helping make the correct architectural decisions earlier thereby reducing later, and more expensive, rework.”
Ray Houston, Director of Development at TOPAZ Technologies
“Udi's SOA class made me smart - it was awesome.
The class was very well put together. The materials were clear and concise and Udi did a fantastic job presenting it. It was a good mixture of lecture, coding, and question and answer. I fully expected that I would be taking notes like crazy, but it was so well laid out that the only thing I wrote down the entire course was what I wanted for lunch. Udi provided us with all the lecture materials and everyone has access to all of the samples which are in the nServiceBus trunk.
Now I know why Udi is the "Software Simplist." I was amazed to find that all the code and solutions were indeed very simple. The patterns that Udi presented keep things simple by isolating complexity so that it doesn't creep into your day to day code. The domain code looks the same if it's running in a single process or if it's running in 100 processes.”
Liron Levy, Team Leader at Rafael
“I've met Udi when I worked as a team leader in Rafael. One of the most senior managers there knew Udi because he was doing superb architecture job in another Rafael project and he recommended bringing him on board to help the project I was leading. Udi brought with him fresh solutions and invaluable deep architecture insights. He is an authority on SOA (service oriented architecture) and this was a tremendous help in our project. On the personal level - Udi is a great communicator and can persuade even the most difficult audiences (I was part of such an audience myself..) by bringing sound explanations that draw on his extensive knowledge in the software business. Working with Udi was a great learning experience for me, and I'll be happy to work with him again in the future.”
Eytan Michaeli, CTO Korentec
“Udi was responsible for a major project in the company, and as a chief architect designed a complex multi server C4I system with many innovations and excellent performance.”
Evgeny-Hen Osipow, Head of R&D at PCLine
“Udi has helped PCLine on projects by implementing architectural blueprints demonstrating the value of simple design and code.”
Nimrod Peleg, Lab Engineer at Technion IIT
“One of the best programmers and software engineer I've ever met, creative, knows how to design and implemet, very collaborative and finally - the applications he designed implemeted work for many years without any problems!”
Consult with Udi
Guest Authored Books
|