Organization is Key to Development


I started out this morning looking at a the Test List Editor on a project I am working on. At the top were a bunch of broken tests with a few live tests. At the bottom were hundreds of live tests, but none were organized. There were 538 live tests and at least twice that many that no longer existed. Ouch!

Unit Test Organization

I am thankful someone pushed the idea of unit testing to the organization, but the lack of organization of the tests gives me pause. What if a developer only wants to run tests for a particular assembly? In the current setup, you have to organize the tests by project and then manually click each of the tests. This is a time consuming effort that has to be repeated each time you have to run the tests.

Fortunately, this nightmare can be solved in Visual Studio by simply placing tests into lists. You can then run the tests in isolation rather than running every single test in the entire suite. At minimum, I would focus the tests on area and break down so unit tests and integration tests (if any) are separated. Further separation may be needed to test specific functionality. Another possibility is starting with tests that run for a build and those that don’t. The important takeaway is you should organize your tests. Below is an extremely minimalist approach I took in a recent project.

image

In case the above seems a bit strange, I use a modified BDD style when testing. I say modified as I use the default MSTest bits and organize by behaviors. Why is a topic for another blog entry.

In short, if you are going to create tests (and you are, right?), you need to keep the tests organized. If you need an analogy, think of the test list editor like a library. Unless the books are ordered so you can find them, they are worthless. Every library needs a librarian, which brings me to the next topic.

Other Organization Needs

Another clear organization need in every development shop is a clean way of organizing documentation and other artifacts. One of the most popular tools for organizing content is SharePoint. And nearly everywhere I go I find something like this:

image

Pretty standard search and I find numerous items that have absolutely nothing to do with the topic I am searching for. In addition, I find multiple versions of the same document. The second issue can be cured, at least partially, by informing users how to open a document for editing and save back rather than save a new document with the same name each time, but you still need someone to keep up with the organization.

Summary

I guess the point of this post is anytime you have a library, you need a librarian. Without one, the “books” get moved all over the place until it is very hard, if not impossible, to find them.

Peace and Grace,
Greg

Twitter: @gbworld

Using Flags Instead of Arrays of Enum


This is a short post based on a problem I had today where I have to either loop through an array of enum multiple times to ensure proper ordering or actually tear the array apart. The problem, however, is very common.

Here is the issue, so you understand the context of this article. I have a service method that requires an array of a particular enum. The call is something like this:

var client = new ServiceClient();
var request = new TreeRequest( { more here} );
var purposesArray = { PurposeEnum.Systems, PurposeEnum.Accessories };
var response = client.GetTree(request, purposesArray);

This seems fine, if you examine it directly, as I can iterate through the enum values and run the service to product the hierarchy needed. But, there are two issues.

  1. The enum values must run in a certain order, as the root of the tree comes out of a particular value
  2. The current service call accepts multiple values, but only runs the first one

The second item above is not problematic from the enumeration array standpoint. I would have created a method with only one purpose and then added an overload when I was ready, but I am not completely opposed to preparing for the future (not quite true, as this particular future may never be, but that is a topic for a rant post).

The top item is the more problematic item. let’s illustrate. Suppose someone sets up the enumeration array like so:

PurposeEnum[] enumValues = { PurposeEnum.LastValueToRun, PurposeEnum.MiddleValue, PurposeEnum.ShouldBeFirstValue };

Now imagine this order is important (as it is in the service I have) and I have code like this:

foreach(var purpose in enumValues)
{
AddToTree(context, purpose);
}

Even if we assume an array is guaranteed to keep objects in order rather than take a place on the heap, I now have a useless answer returned to the client consuming my service, as I need to ensure the Systems enum value is first.

Worse than that, I have tightly coupled my service to the client, as the client has to understand my array is not really an array, but an array with a set of business rules dictating order. Ouch!

To decouple, if I want to guarantee proper ordering, I have to employ something that ensures the value with primacy is first in the array, like the following code.

foreach(var purpose in purposesArray)
{
if(purpose == PurposeArray.Systems)
{
newArrayList.Add(purpose);
}
}

foreach(var purpose in purposesArray)
{
if(purpose != PurposeArray.Systems)
{
newArrayList.Add(purpose);
}
}

PurposeEnum[] newArray = newArrayList.ToArray();

The problem here is I end up with a lot of code just to keep ordering. Nasty! Nasty! Nasty!

There is an easy solution when ordering is important … (fanfare please) … Bitwise operations. In the case of an enum, this means [Flags]. If the PurposeEnum was set up with flags, it would appear like so:

[Flags]
public enum PurposeEnum
{
Systems = 1,
Accessories = 2,
Warranties = 34
}

You can actually simplify the above a bit, but the way I wrote it shows that the flags are binary in nature (each item is the value of the previous times 2). This is important, as using binary allows me to specify order internally without regard to whether the programmer consuming my code knows the proper order to get results.

Now, I can have a person simply send me a single value, and I can order based on business rules:

if((purpose && PurposeEnum.Systems) == PurposeEnum.Systems)
{
//Run the first item to set the tree up properly
}

//ETC

Either of these is fine from the client side, as they yield the same integer value:

var purposeArray = PurposeEnum.Systems || PurposeEnum.Accessories;
var purposeArray = PurposeEnum.Accessories || PurposeEnum.Systems;

The order is dicated by how I consume the enumeration, not the order in which the client places items on the stack.

This is not the only use of flags, nor the best use of flags. It is merely something I noticed today where I have to think about ordering of an array.

Peace and Grace,
Greg

Twitter: @gbworld

Requirements and Acceptance Criteria Are Critical


Over the past few months, I have worked on a project with precious few requirements and no acceptance criteria. Essentially the dictate is done means “keep coding until I say it is fine”. The problem is this insanity never ends, as changes are placed into queue before the coding is “done”.

There are a few myths I have seen in action in various businesses. Here they are with the reality following:

  • Agile means loose requirements and very little documentation – This is false. Actually Agile needs requirements and documentation as much as any other methodology, the requirements are just stated in the form of a user story and some of the documentation is in the form of unit tests.
  • Business needs to be fluid, so we should not tie down “done” with a firm set of criteria – In reality, you need to define done as explicitly as you can. You may change (request) the definition over time, but a developer without a clear path is as likely to code away from the solution as code towards it.
  • Hire a bunch of really smart developers and you can get around firm specifications and acceptance criteria – While very smart developers are faster at coding their way out of a hole, and less likely to code inescapable holes, there was only one real miracle worker that ever walked the face of the earth … and it is not your developer.

    NOTE that really smart developers often over-engineer or over-complexify solutions when left to their own designs.

We keep trying to view planning (with its outcome of requirements and a definition of done) as an optional exercise. This is generally done in the name of time, but how much time is blown having a developer rewrite code? In my experience, not defining what is being built has always turned out more expensive than spending time up front to plan. If you are truly overloaded, rather than avoid planning, you should force planning. Otherwise, you will spin at the end of the project, trying to “plan” after development, which means figure out how to get the code to do what I want with the least amount of hours. This is an exercise is low quality and relies on a lot of luck.

A couple of things I have noticed in my career:

  • “Do everything this {website} does in a {mobile application} is not a requirement (you can change the {} types for your situation, if you like). As much as you might think it is a requirement, what is being done is up for interpretation, even if the basic business rules are the same, and the developer’s interpretation and yours are as likely to be different than they are to be the same. This is especially true when moving from one form factor (ex: web to mobile) or coding paradigm to another (ex: webforms to MVC).
  • “Code this until I am happy with it” is a recipe for disaster. While it leaves a lot of flexibility for the person who wants to be “happy” to massage the outcome, it causes badly bolted on code as new rules are manufactured. In the lucky cases, the code can be refactored to some level of quality, but this is more of an exception than a rule. Ouch!

Let’s take a quick example I can think of lately. The requirement, as loosely stated, was put together a tree of categories for eCommerce and append products to the tree. Then create a detailed file for the products. The acceptance was “I will let you know when it is right”. Here is part of the history:

  1. Add categories from another source
  2. Exclude some categories
  3. Replace images found in data source with a dictionary of categories and images
  4. Use a template to create a tree where none existed and append to a specific spot in the tree
  5. Create a featured products file
  6. Append that file to a specific node in the main tree file
  7. Exclude categories with no children or products
  8. Scrub HTML for certain nodes in the XML document, replacing many of the characters with HTML escape sequences
  9. Search for certain “illegal XML characters” and replace them (if acceptance criteria were built, it might have been as simple as convert from UTF-8 to UTF-7 – live an learn?)
  10. Do a binary scrub of characters not caught with the loose ruleset in #9

All in all, numerous hours (weeks?) were burned due to the lack of planning on many levels, equating to tens of thousands of dollars. If this is the rule in the organization, and you add all of the projects up, how many hundreds of thousands, perhaps millions, of dollars is the company burning through that could be avoided by setting down requirements and a definition of done?

What if requirements change during development? If this is not the best reason to use Agile methodologies, I don’t know what is.But, even if you use waterfall, you stop development on the feature(s) in question and refine the requirements before moving forward. To either a) let the development continue or b) continue altering output until “happy” is like dining in a really crappy fine dining establishment … a lot of money for a really bad meal.

The point here is you can’t plan a trip without knowing where you are going. By the same token, you can’t build an application without knowing what done looks like.

Peace and Grace,
Greg

Twitter: @gbworld

Why Planning is Important


I have been working on a project for quite some time that is considered time sensitive. Due to the time sensitive nature, actually creating full requirements and acceptance criteria is considered frivolous, so the concept is code and verify, based on some unknown standard. It is not quite that bad, but when someone (generally me) argues for planning, I am told the following are equally valid ways of approaching development for this project.

  1. Creating requirements and acceptance criteria (i.e. planning) and then coding to match the requirement and acceptance criteria.
  2. Coding based on a loose, one sentence, “specification” and then fixing issues based on User Acceptance testing.
  3. In short,  the group has opted for a “show me what you have and I will then tell what is wrong with it” versus “tell me what you want and I will show you what you have told me you desire”. While we ultimately end up with the same product, I disagree these are “equally valid ways” of developing a new application.

To illustrate this, think back to your last vacation. If you have not had one in a long time, you should go on one soon, but if you can’t imagine your last business trip. It went something like this:

You woke up at some time during the day (or night) and packed enough clothes for a week’s worth of time. Your spouse and children did the same thing. You then got in the car and drove to the airport and stated to the ticket agent “I have $1500 to fly and 4 people, so I need whatever ticket is the closest to $375 per person for a round trip”. Once you had your tickets, you got on the plane and flew.

When you landed, you went down to the car rental agencies and got a car, using the same logic. “I have $500 to spend on a car, so give me whatever car I can get for a week with that much money.”

You then drove off out of the airport and got on the road whichever direction fit your whim and drove until you found a hotel that seemed to be within your budget. You went up and got a room.

Once in the room, you looked at the local guidebook and figured out what types of things you could do in this town with the amount of day you had left and went out and had fun.

Does this sound even remotely like your last vacation (or trip)? No? Why not? Well, if you are a normal person, you can see all types of problems with this. Here are a few:

  1. What if $250 only buys a ticket to Idaho, in the middle of winter? Did you pack for snow or the beach?
  2. What if you can’t find a flight with 4 tickets available?
  3. What if the car rental agency does not have a car that fits your budget?
  4. What if the hotel does not have rooms available?
  5. What if the town you landed in has nothing you are interested in seeing?

I am sure I can think of more, but the point is that you would not schedule a vacation out of town without some idea of where you were going to go and where you were going to stay, right? But you would be this careless with a “mission critical” project?

There is a belief in some circles that not knowing everything about the final product means you should not nail anything down. To me, this is about as stupid as stating “I can’t book a room at the Hilton for our vacation because I am not sure what I am going to order for breakfast, lunch and dinner every day we are on vacation”. Yes, there are some parts of the project you may not be able to figure out right now, but not planning anything as a result means you are going to, at best, spend a lot more time (i.e. money) to develop the product.

What has happened on my current assignment is I am now getting back pieces to fix. They are logged as defects, but without a criteria of what is right, nothing, outside of failure to work, is really a defect. And, since there is no criteria, “defects” are being found in serial. Take one step forward, find a “bug”, fix that one bug. Rinse. Repeat until all the “bugs” are washed out. The biggest issue here is we can, with any confidence, state when the final product is going to be ready for release, as there is no firm definition of what done looks like.

This topic has been covered as nauseum, of course. Steve McConnell has some interesting insights in his book “The Project Software Survival Guide”, which I think should be mandatory reader for every manager that needs IT work done.

From McConnells’ company site, I have found a couple of neat gems from his book. The first talks about when a defect is created and how much it costs to correct. This is shown below.

If you do not have time to write requirements and work out the architecture and design, every defect is a requirements defect. Pretty expensive proposition, yet this is precisely what is being done.

Here are a set of images from Steve McConnell’s own site that describes perception versus reality. Management often believes this is the optimal development path:

They accept that there is a certain amount of unproductive time (meaning time not moving forward towards the end of the project, whether reworking bad code or going to get coffee), but they don’t want the burden of planning, which is seen like the picture below:

If I get rid of the planning (process), I end up with more productive time. The problem is the reality looks more like this:

Without proper planning, what started as a small amount of thrashing, ends up consuming a huge amount of time, as more and more “defects” are discovered and more and more code has to be reworked based on differing understandings of what is acceptable and what done look like. In addition, more and more time gets consumed in process, including planning how to get from “what we now have” to “what is acceptable. One thing missing from this diagram that is present in the book is the dot just before process and thrashing consume 100% of daily efforts. That dot indicates the luck projects that get released before all of the participants drown in the sea of non productivity.

The ideal situation is enough planning to understand both what done is and how to determine each feature is acceptable to fit that picture of done. This is shown in the final graphic linked from McConnell’s site.

In short: planning works. If you want to read McConnell’s entire treatise on this topic, click here.

My next topic, which I will post in a few days, will cover why “hiring rock stars” is not an adequate alternative to proper planning.

Peace and Grace,
Greg

Twitter: @gbworld

SOA Lessons: Insulate Your Client


In my last post, I lamented on the idea of creating an external layer where all of the services sit in a single project. In this post, I would like to talk about the idea of passing data directly from internal services through an External API without mapping the data. This topic was covered a bit differently in a previous post if you would like to look at the issue in greater detail.

As a disclaimer, this post focuses on a particular set of problems I have seen with immature External APIs that may not manifest themselves in more mature SOAs.

External API consumers are valuable to business. If they aren’t, there is no reason to have an External API. Initially, the external clients may not serve much value to your business, but overtime they do. This is especially true in an ECommerce situation, where you clients are using your APIs to help you sell. But this “truism” applies to all sorts of businesses.

From the standpoint of the development team, the external consumer is often “out of site out of mind”. Unless you are attempting a coordinated effort (a topic for another blog post?), your support and infrastructure teams will often have more of an idea of what your clients are doing than the development team.

The primary solution would seem to be “make the external client a first class citizen” and this is a dynamite idea. The problem is external clients are often not easily monetized, making it hard to place a priority on them.

Standard SOA

The title of this section is a bit misleading, as it suggests I am going to guide you through the creation of a “standard” SOA. Instead, I am going to cover a generic SOA setup I see in many organizations.

At the bottom layer of the SOA, services are created to expose persisted state (data). The services at this level may present objects that represent rows in database tables, especially in less mature systems, but more often tryt o distill the data a bit to serve up objects needed by various business applications.

On top of this layer, you find services that aggregate multiple services. This layer or layers of the SOA, models are being created that can be consumed by user interfaces. And it is at this layer many SOAs create the objects consumed by both internal and external clients.

The topmost layer comes in two flavors. The first is what my current client calls a “domain services layer”, which serves to map the aggregate service model to a domain model for the external world to consume. The other is a pass through layer in which the objects of the aggregate layer pass through the external service, which is not much more than an endpoint on an external service.

Insulating the Client Through Process

When the external layer is a pass though layer, breaking changes to objects on the aggregate layer will not always break the pass through. In cases where there are no changes to the external layer, service references are updated and the service is deployed. But the client can’t consume them.

To insulate the client from these changes requires process. A proper versioning strategy must be put in place and older versions of the internal services must be kept up until all clients have moved to the latest version. This also means external clients must be included in the testing process, even if their inclusion is only during the User Acceptance cycle.

In general, this works best if the External API team has some measure of governance over the internal services it consumes. At minimum, the external team needs the ability to issue a go – no go order when breaking changes occur in the pass through models or force the internal service to leave an older version alive while clients migrate to the new version.

If process and a versioning strategy are not in place, it is dangerous to maintain your external API as a pass through layer.

Insulation through Domain Models

Another means of insulation is to set up a Domain Model for the external API and “mapping” the returns from the internal service(s) to the External Domain Model. The main negatives to this approach are a bit of overhead (performance) and a maintenance requirement, especially when the maps are hand coded.

The benefit is breaking changes are instantly seen when the service reference is updated, as the changes now break the mapping. This insulates the client from change, as this breaking change has to be fixed. As the exception can often be fixed through mapping changes alone, the external client need not know the software was even changed, so the external API service can undergo a minor, rather than a major, revision.

Process or Domain Modeling?

The question comes to which should you use … process? domain modeling? both?

In my experience, attempting to solve a technological problem with process alone (or, expecting people to follow standards and rules) only works in an organization where software is reviewed completely prior to deployment. I have certainly worked in organizations with this commitment, but for every company I have consulted that had governance over process, there are 10 that do not.

This leads me to the domain modeling approach and insulation through adherence to contract. The entire underlying system may introduce breaking changes, but as long as the changes can be mapped to a consistent model, the outside world has no clue these breaking changes occurred.

The Cost of Change

As a kind of summary, I want to talk about how much change costs, or more specifically, how breaking changes to external APIs can be very costly.

Initially, an External API is a cost center. Until there is adoption, there is no financial benefit to having clients consume your data. But, even at this stage, failures in the API cause clients to shy away from using them. Enough issues and the stability of your API becomes public and most sensible people avoid it. This ensures the API will never be anything other than a cost center. Worse, it can be the proverbial albatross around your neck.

Over time, the stability of the API and its contracts, becomes more critical, as more and more clients begin to use the service. At this point, a breaking change is generally caught sooner, but rollbacks become extremely expensive.

While setting up mapping to an external domain model is not a cure all, it certainly adds a measure of safety for your clients to use the service.

The Point

The point here is changes that break software internally may be annoying, but they can most often be fixed without the outside world having any clue there is turmoil. Changes that break external software are more dangerous, as they cannot be hidden from view. By enforcing proper versioning strategies and treating the external API as a first class citizen, you can protect yourself from these public breakages. In cases where these processes cannot be put into place, breaking changes can be hidden from the outside world by insulating the clients by mapping to an external model.

From my experience, adding the small bit of overhead to protect the client from internal changes is the safest path, especially when you are in the early stages of creating processes to properly version change. If your organization is mature enough to have proper governance on releases and properly tests both internal AND external responses, a process driven approach is an option. And, if true performance is a showstopper, it may be your better option. Otherwise, adding a bit of insulation for clients is a very wise idea.

Peace and Grace,
Greg

Twitter: @gbworld

SOA Lessons: Don’t Put All Your Eggs in one Basket


When we think of the term “don’t put all of your eggs in one basket” in terms of IT, we more often think of not relying on a single vendor solution for everything. This is certainly a valid way to look at the term, but in SOA it also means we have to look at services and not just layers.

To put this in perspective, I am currently working on an external API solution for a large E-Comm company. In the current External API, which was released before I moved into the group, all of the services are found in a single “wrapper” project. On the plus side, it makes it easier to configure the services, as all of the configuration is found in a single web.config file. There are many negatives, however, which I will detail in this post.

Single Point of Failure

This is the largest negative on production. Recently, the solution was released and we discovered a vendor was overloading one of the services. The issue was discovered during deployment and manifested itself as failures in a wide variety of services. The reason for the systemic failure is the worker process for the failing service was the same worker process for all of the services. When the process was brought down, all suffered.

Fortunately, we knew which service was live and most likely to be the culprit, so we were able to alleviate the problem. If this was not the case, we would have had to pour through logs to determine the offender, which could have taken hours with the current state of affairs. That is unacceptable.

If you take this scenario a bit further and assume a coding error that kills the worker process rather than a load issue, imagine the troubleshooting. Especially if the exceptional case causing the failure was intermittent and due to the lack of a patch on the server in question.

One good reason to separate out the service endpoints is so you can move the services into their own process space. This is not mandatory in normal working conditions, but if there is an issue, and instrumentation and monitoring is not catching the culprit, separating the service into its own process accomplishes two things:

  1. Helps identify the point of failure
  2. Protects other services from failure

Both of the above are worthwhile reasons to separate each service into its own process space as a rule, and then making exceptions based on needs.

Single Point of Deployment

This negative is similar to the last negative, but focuses more on what it takes to fix a service that is in error. If all of the services exist in a single project, then all must be deployed at the same time, even if only one service has changes.

I think anyone reading this can see why this is a negative, but it is more insidious than moving pieces you should not have to move. Every time a software project is deployed, there is a potential for error. There are a variety of reasons why this is so, but we all have experienced a deployment that created a buggy condition. Often times it was code we did not even change where the bug shows up and often due to circumstances that have nothing to do with the code.

If you deploy a service that has no updates, and cause bugs due to mistakes in deployment, you have done a great disservice. Worse, the disservice was completely avoidable if you had simply segregated out the service so it did not require deployment with the other services.

Cross Contamination

When numerous service endpoints are added to a single WCF project, they will have different contracts, but often end up with the same binding rules and behaviors. This is normal and to be expected. Eventually, however, one service will be found to require more time to complete its work or a large payload (either request or response or both?) and edits will have to be made to the configuration file.

Changes that are specific to the contract and service endpoint are unlikely to have consequences outside of the service in question. But since at least parts of the configuration are shared, changes can impact the “sharing” services in a negative way. And, since we deploy at the same time, but often only test the service being updated, these negative consequences are often discovered by our consumers rather than our test team.

The Point

The point of all this is we can easily avoid the negatives explained in this post by making sure every UI project (in this case every WCF service) has its own project. Sharing a single solution is not an issue, although you will also want to make solutions for the individual services, as well. NOTE: Solutions are points of organization and a single project can exist in any number of solutions.

Separating out the services has a small negative of forcing you to make changes to multiple projects for “universal” binding and behavioral standards, but this negative is outweighed by the negatives of placing all of the services in a single project.

Peace and Grace,
Greg

Twitter: @gbworld

The Importance of Domain Models


Disclaimer: This post focuses on theory, so there are some bits that are oversimplified.

My current assignment is consulting a large eCommerce company on their external APIs. For those not well versed in this concept, the short story is I am focused on the architecture of web services exposed to the outside world. One of my primary tasks is determining project layout of the service solutions.

One of the newer services was set up as a pass through from an internal service. The objects exposed by the underlying service were merely bubbled up through the external service and exposed “as is” to the outside world. This post deals with why this is a mistake and how a service should be modeled. While my focus is external services, the methodology presented should work as a reference model for many types of development.

Domain Models

First, we need a working definition of a domain. In Wikipedia, a domain is defined as follows:

Domain A sphere of knowledge, influence, or activity. The subject area to which the user applies a program is the domain of the software

In an eCommerce company, we have many domains. Some deal with knowledge of the product, others with finance and yet others with shipping and receiving. Each of these domains has different needs. As an example, let’s look at a customer as he relates to various applications in an eCommerce scenario:

Ordering – Need full customer information, including address(es), phone number(s)  and payment information. Not all of this information is mandatory in all steps of the process, however, so we might even represent the customer in a variety of domain models. As a real world example, it is unlikely we will need the customer’s payment information anywhere but the payment process.

Warehouse – There is no need for any customer information to pick items. We do need the order represented so the shippers can identify the customer, but the customer is optional

Shipping – A customer, as far as shipping is concerned, is a name, a shipping address and a phone number (so the carrier can call if there are issues).

Reading the examples above, it should be clear that a domain does not equal an application. In the space of browsing and ordering, for example, the application likely crosses multiple domains. This is not important for this article, and we are not going to create a domain model. Now that you understand the domain and the domain model, let’s focus on the core issue for this exercise.

Core Issues

The core of this article is when an internal service is exposed to the outside world without creating a separate domain model. The model looks like the following diagram:

DIAGRAM

On the surface, this does not seem like such a bad idea. After all, why should I not expose the same objects to the outside world? The main reasons are:

  1. The outside clients are not insulated from changes to the internal change. In more OO terms, the inner model is not encapsulated and there is no abstraction. Encapsulation is more important here than abstraction, of course.
  2. Internal services often contain wording that does not apply to the outside world, or ‘companyisms”
  3. Internal needs are different from external needs and there are often internal “secrets” that should be kept internal only.

Insulation (Encapsulation)

When you design a service that passes through objects from an internal service, there is no insulation from change. Every time you change the objects in the internal service, the external service must be changed to match the internal service. Done properly, the service is versioned and the original service is properly deprecated so it is kept alive until external clients can switch their programming to fit the new service.

This does not sound like such a big deal over all, but consider most internal services are not thought through with the same rigor as external services. This means there are generally more changes to an internal service than the outside world will tolerate.

By adding a domain model to the external service, you can protect the external client from excessive versioning. As an example, if the only changes on the internal service are name changes, you can simply adjust the mapping to your domain model and release a new version on top of the old service. The internal service team need not keep an old version of the service alive, as the external client consumes the external domain model (not quite true, but that is a topic for another post).

Companyisms

Every company I have consulted for has some type of verbiage unique to the organization. In eCommerce, for example, I often see {CompanyName}Price for the standard retail price for the company, which is generally lower than the manufacturer’s standard retail price. In more extreme measures, company acronyms become part of the internal service model.

Regardless of the nature of the companyism, the outside consumer should not have to understand the unique vernacular of your company to consume the service. By creating a domain model which is focused on external clients, you eliminate companyisms from the objects served.

Company “Secrets”

Not all of the items served by the internal service are truly company secrets, but there are many things an external consume need not know. These items should “disappear” from the domain model used by the external service.

In an internal cart service, you may pass back private consumer data so the applications can expose this information to employees who need to know. If you expose this same service to the outside world, these “secreats” are also available. If, instead, you create a domain model, you can consciously remove these items from your model and avoid exposure to the outside world.

Pattern for an External Service

Now let’s look at a pattern for an external service. The pattern is modeled using the Core as Application methodology, as shown in the diagram below:

image

The idea here is the business logic is the application and Persistence (where you save data) and Experience (where the user reads or manipulates data) are not part of the application, per se, but extensions so work can get done. As with all analogies, there are some flaws in this view, but it is a very useful paradigm for developing high quality (testable?) applications. I will cover Core as Application, and its benefits, in another post.

As many are not familiar with the Core As Application model above, I will take you through an “n-tier” set up of the diagram. A couple of notes before going this direction.

  • The UI tier has been renamed experience, like the Core as Application model. This is done to illustrate the fact that our user’s are not necessarily human, as in a service. What we are focused on in this layer is the experience of the user, human or computer.When we focus on interface, we often see this as strictly I/O, which is a mistake.
  • The data tier is renamed persistence, like the Core as Application model. The reasoning is the application should not change based on where you are persisting your data. The only thing that should change when you switch from a file based persistent methodology to a database is your access method.
  • The business tier has been renamed core, like the Core as Application model. This is due to the fact that this tier contains the application. Switching out the experience layer does not change the application, nor does switching to another persistence method. Of the two concepts here, separating persistence (database) from core is generally easier than experience.

Now that we have the “rules”, here is a basic service diagram, with a rather simple implementation.

image

Here is an explanation of the parts of the diagram. The items in blue are items created via attributes in WCF and the Service Proxy, in green, is “free”, as it is created by .NET when you create a service reference.

  • Service Proxy – A proxy for a service created when the service is queried. The proxy comes for free in .NET, as it is created when you include a service reference or use the command line tool. NOTE that this assumes a SOAP service in the .NET Framework 4.0 or earlier.
  • Proxy Façade – The façade is utilized as a bit of an insulation against change in the methods of the underlying service.Adding a façade makes it easier to create an interface, which both a) makes it easier to test and b) allows for substitution for future versions of the service. When added to the factory and mapper, you end up with a very flexible model for change.
  • Mapper – The mappers job is to translate from the service model to the domain model. While this functionality can be encapsulated into the façade, keeping it separate makes it easier to unit test the façade. Using generics, the mapper can allow for flexible input while keeping the domain model objects as its primary output. This allows for easy change while adhering to a single interface.
  • Domain model – The model for the business logic, if any, contained in the external service.
  • Core – In a mapping type of service, the core is a pass through only. In an aggregation type of service, the core will “marry” output from multiple services. I find it unwise to have your external service serve as an aggregate. While it adds “weight” to the total solution, it is better to have another internal service handle the aggregation and have the external service focus on simple mapping of objects. This moves the complexity away from the external client and reduces the likelihood of erroring out  your consumers.
  • Data Contract – Standard WCF adorned objects. Per Microsoft’s suggestion, I use the IDataSurrogate interface to further separate the domain model from the representation to the outside world. The contract can be placed in the service layer, rather than core.

    NOTE: I am currently working on using the MVC pattern on the service, which may be more easily accomplished by bubbling up the data contract to this project. I will post findings later.

  • Operation Contract and Service Contract – These describe the behavior of the service and are a standard part of WCF. I will generally separate these into a separate assembly, although it is not mandatory, as changes here will alter the service.
  • The service – Standard WCF service. As a very simple “User Interface’ (experience piece), the WCF service contains very little code. This may be altered slightly if the service project contains the contracts.

If you feel multiple facades are needed throughout the history of the service, you can add a factory in front of the façade and use it to determine which façade (and thereby service) are used in a particular version.

I will cover the solution layout in more detail a future post.

Summary

Internally, most organizations go through a bit of chaos. In an ideal world, the developers in one department would treat the developers in consuming department as clients, this is often the exception in many organizations. Breaking changes in software are all too common and often break the software created by other departments.

The outside world is far less tolerant than your internal departments. When you break software, they may forgive you once, but eventually the decision will be made to go to a competitor. For this reason, you simply cannot alter service contracts without considerable thought.

To insulate the outside world from your changes, you must use a strategy that keeps the outside interfaces as static as possible despite the internal chaos. Using a domain model and data contracts, along with proper facades and factories, you can insulate the outside world from internal chaos and company specific naming. You also have the ability to remove any “secret” information.

The pattern applied in this article is not a “one size fits all” but rather a very good start for most situations. Feel free to alter the pattern to fit your specific needs. Also feel free to comment, as patterns should always be open for improvement and discussion.

Peace and Grace,
Greg

Twitter: @gbworld
Microsoft MVP Page: http://mvp.support.microsoft.com/profile/Beamer

Unit Testing Basics


I was recently in a talk with a couple of people where I am currently consulting and the question came up about what type of unit testing was best. Should one use TDD or BDD, or perhaps TDD with a BDD style? Or is it okay to write tests after the class is coded? So many questions.

Here is my short answer about testing for most places I have been involved: Just start testing. That sounds like a pretty bad answer, perhaps, but I find most organizations simply aren’t testing. At a previous gig, I came in and attempted to sell the unit test idea and was told there was no time in the schedule to allow for testing. Common theme.

At my current assignment, I currently have about 100 tests on my code. The number will increase as defects are found (rule: every defect requires a test) and I and the test team complete analysis of the rabbit holes in the code. The team I am closely aligned to has 0 useful tests (a few tests, but full integration and very limited to happy path). Another group has 6 tests, all of which are either useless, badly named, or empty. Actually all three in all but one case. Same theme.

Not Enough Time

The normal throw back is the time involved in writing tests: We can’t afford the extra time it takes to write tests. First, I think this is a bogus answer. Yes, there is an initial learning curve cost, but if your organization has no time for learning new technology, you really should not have your own developers. Technology is being vomited out at a rapid pace and organizations that do not factor in time to learn get farther and farther behind. And, yes, there is some time writing tests, but it is really minimal when you add all of the factors. Examine these:

  1. Testing first (TDD/BDD), and to an extent testing early (just after coding classes), helps the developer find design flaws before too much code is written, saving rewrite time. This, alone, is often enough to make up for the “extra” time of writing the tests.
  2. Testing first or early allows for safe refactoring of code. This improves both quality and maintainability. This does not save time, per se, but it does stop developers from wasting time seeking bugs out created when refactoring blindly.
  3. Testing adds a safe haven for maintenance and new features. Developers can ensure their changes do not destroy current functionality. This increase productivity in two ways. First, the developer feels safe coding and will code more quickly. Second, any bugs created by “fixing” or adding code can quickly be resolved.

I worked on one assignment recently where I had to take over a code base. The developer had already burned 5 weeks of time and the design decisions created a path where there was quite a few more weeks to solve the problem. Taking over, I rewrote most of the code and flipped the design to a more domain driven design. I reused algorithms, but the entire design was scrapped. Development time about 2 weeks, including tests.

During the development, it was discovered the number of lines in the output file were much larger than projected. The idea of spinning the entire object graph into memory had to be scrapped and lines had to be written to file as soon as the final answer for the line was determined. Major change. But, with tests surrounding the code, the refactor took less than a week. I can only imagine how long it would have taken with the original base.

Note that tests are not a magic bullet that saved this project all by themselves. The original design separated out the business objects in a way that described the output file very well.  Because of this design, moving from walking the object graph to passing a writer was much easier. There was also a difference in experience between the developers.

The important point here is the tests were written without a major time impact. And, because of the tests, a major design change had little impact on delivery. The correct argument, based on this project, is “you don’t have time NOT to test”.

How should I test?

This is a question that is hard to answer. There are all sorts of opinions on the best way, or even the right way, to test. With some purists, any deviation from the pure TDD or BDD way of testing is blasphemy. So, I will share my general “model” of testing.Determine the classes in your domain. Focusing on what you are building, from a business perspective, what do the objects look like?

  1. Write tests on the domain objects. These tests will “always” pass, so some consider them useless. I disagree, as you can reuse the tests when you start unit testing behavior, as most of your behavior alters state of at least one object.
  2. Determine the boundaries in your code. The question here is “where am I calling another library?”. You don’t have to do this perfect, but you should separate out your data access, domain objects, mapping data to domain objects, and core business functionality in your first pass. These are your boundaries.
  3. Write a “contract” library for each library that sits on a boundary. This is critical for mocking.
  4. Figure where you need to start. I generally will look at one of two areas: the area where I am the foggiest about the design or the area that has the greatest impact on the code. I then write tests based on the requirements.
  5. I generally skip the “it does not compile” step, but this is important when developing the discipline of TDD or BDD. I also often skip the “fail” step, going to first green. Yes, I know this is “wrong”, especially to the purist, but initial pass is most often 1 line of code, and I have yet to be bitten.
  6. Build up a battery of tests around the code base, building functionality up slowly.

How about the style of test? I prefer this type of model:

  1. Spin up the unit tested in class initialize and run the code
  2. Create a test for each piece of state it changes

Now, this is a general answer, as there are times when a single test is a more applicable approach. The important part is having a consistent way of testing, even if you blend testing styles based on different factors.

Testing Styles and Methodologies

I will now take a moment to run through a few different “styles” of testing, based on different methodologies. This is the most dangerous part of this post, as some purist will likely disagree with something I say here. Smile

Test Driven Development (TDD) Style

NOTE: TDD is a methodology where tests are written first to design the code. This section does not describe TDD. It merely covers a common style of organizing and writing tests.

As a style, this generally means writing a test class like so:

   [TestClass()]
   public class LogonInfoTest
   {
      [TestMethod()]
      public void ConstructorTest()
      {
         string userId = "IMontoya";

         string password = "P@ssw0rd";

         LogonInfo logonInfo = new LogonInfo(userId, password);

         Assert.AreEqual<string>(userId, logonInfo.UserId,
            "The UserId was not correctly initialized.");
         Assert.AreEqual<string>(password, logonInfo.Password,
            "The Password was not correctly initialized.");
      }


[TestMethod] [ExpectedException(typeof(ArgumentException), "A userId of null was inappropriately allowed.")] public void NullUserIdInConstructor() { LogonInfo logonInfo = new LogonInfo(null, "P@ss0word"); } [TestMethod] [ExpectedException(typeof(ArgumentException), "A empty userId was inappropriately allowed.")] public void EmptyUserIdInConstructor() { LogonInfo logonInfo = new LogonInfo("", "P@ss0word"); } }

The above taken from http://goo.gl/HinNT.

The basics here are the class identifies the the class being tested, while the methods identify what is being tested. There are other styles of organization, but most TDD examples on the web use the following “rules”:

  • Name of Test Class: {ClassBeingTested}Tests – Example: DomainMapperTests
  • Name of Test Method: {MethodBeingTested}Test

When I used this type of style, I would add _Pass and _Fail to have both a pass and fail test for each method being tested. I then changed my style to have more information on why there is a pass or fail. Eventually, my ruleset moved me to a a more BDD style.

Test Driven Approach with BDD styling

This is a hybrid I have been known to use, as true BDD (next section) requires more than merely writing unit tests. Using this style fits with the spin up in initialize, run numerous tests on state, style of test coding. Here is an example, using the same logon methodology from the TDD section.

[TestClass()]
public class when_logging_in_with_valid_credentials
{

  private static LogonInfo _logonInfo;
  private static string _userId;
  private static string _password;
  [ClassInitialize]
  public void ClassInitialize()
  {
    _userId = “IMontoya”;
    _password = “
P@ssw0rd”;
    _logon = new LogonInfo(userId, password);
  }

  [TestMethod()]
  public void should_have_userId_of_IMontoya()
  {
    Assert.AreEqual<string>(_userId, _logonInfo.UserId,
    “The UserId is not IMontoya. It is not initialized properly”);
  }

  [TestMethod()]
  public void should_have_password_of_P@ssword()
  {
    Assert.AreEqual<string>(_password, _logonInfo.Password,
    “The password is not P@ssword. It is not initialized properly”);
  }
}

NOTE: While I am not against this type of test, it really does very little for us, by itself, other than show the values are properly set. In my normal development methodology, I would have these types of tests on the state objects only and then reuse the tests. The test above illustrates the same code being tested as the previous section, and nothing more.

Notice that the you would need to set up a separate class for the failures. This means more classes are developed, although the amount of total code is about the same.

The important takeaway is the class describes what you are testing and the tests describe the expectations based on that test. In general, you will end up with more test classes using the BDD styling. As a basic rule, think TDD = fewer classes, more methods and BDD styling = more classes, fewer methods.

One reason I like the BDD styling method is I can write tests for the domain models (always pass, I know) and then reuse the test methods as I test behavior. Another is the method name explicitly spells out the expectation, so I can, in most cases, find the location of the error to set a breakpoint without walking code. Great time savings.

I watched Eric Hexter and Greg Long talk about testing yesterday and they used a similar naming standard for test methods, but spun up the class in each method. While I would head in a different direction (class initialize to spin class up), it was a very effective session. The important point here is the implementation can be different, but testing is the key. If you are not testing because of a disagreement with styling, change style rather than avoid testing.

Behavior Driven Design (BDD) Style

Unlike TDD, it is hard to talk about BDD merely as a style. As illustrated in the last section, you can use a BDD style with a unit test framework, but truly practicing BDD requires a test runner that allows you to fully express the behavior in a predictable way (as far as testing goes). There are a couple of BDD frameworks out there for .NET.

  • mSpec
  • SpecFlow
  • SpecUnit.NET

Due to ease of use, I prefer SpecFlow. There are some issues I have with the current implementation, primarily with helping stub in the steps files (there is a kludge when using nUnit), but I really can’t bitch too much, as it is open source and I can contribute. SpecFlow works with Gherkin, a language used with a testing tool called Cucumber (test tool for Ruby). The basics of Gherkin is you use the keywords GIVEN, WHEN and THEN, as such.

GIVEN {a precondition} – precondition
WHEN {I do something} – condition/event
THEN {I expect something} – expectations

You can add AND to have multiple preconditions, conditions and expectations. An example based on the SpecFlow bowling application example:

Scenario: Bowling a strike
Given a new frame
When I knock down all pins
Then my score should not be added up until the next two rolls are completed
And the value for the frame box should be “X”

SpecFlow will use a style where the object is spun up first, with all preconditions. The condition/event is then fired off and each of the expectations are tested.

I would love to take the original tests and describe them in Gherkin, but there is little value to the type of test, as there is no real behavior. It is nothing more than “I set the values correctly”.

Summary

This was a real short whirlwind tour of TDD, TDD frameworks with BDD styling and BDD. I did not even touch on some other testing methodologies. If there are any takeaways you should get it is this:

  1. The idea that testing takes longer is a myth. There is certainly learning curve, but that is true of anything new. There is also a small bit of time creating tests, but it is most often negligible, after you understand testing, and there is no impact when you consider the entire schedule. One might argue there is more time taken, but I would argue that time should have been taken making sure you were developing the right stuff anyway.
  2. The main difference on different testing types is the focus of the test. TDD style allows easy testing of state only, behavior only or behavior and state. BDD focuses on behavior, making state only testing a bit of a kludge. In most cases, you still will test the state of the system as related to behavior.
  3. If you have a question on which style, rather than spend a lot of time determining the path, why not go ahead and start testing? You can always adapt your strategy over time and refactor tests. It is far safer than changing code blind.

Hope this helps you on your journey. I will likely hit quite a few more posts on testing over the next few months.

Peace and Grace,
Greg

Twitter: @gbworld

TSA Scanners


There has been a lot of controversy over the new scanning procedures lately. And, like good stewards of the realm, the media has jumped into to protect the government “underdog” from the onslaught of the “ignorant Neanderthals” ignoring “good science”. The question, however, is whether or not we have properly labeled the sides.

There are two basic areas of concern for the masses who are against the new procedures. The first is health concerns over being scanned, primarily from backscatter X-ray radiation. The second is the privacy concerns.

Health Concerns

Are we getting too much radiation when we submit to scans? The government states no. The amount  of radiation from a single scan is estimated at .05 to .1 mrem (micro rems), which is 1000 times less than a standard X-Ray. CBS News then states a variety of things that will give you more radiation.

  • Living in a city
  • Sleeping next to a partner
  • Flying
  • Drinking water

There are two problems with the comparisons. First, we have no choice over many of the activities that give us radiation. We can’t stop living on this earth or drinking liquids. But, we do not have to submit to scans unless the government forces us to do it to fly. Second, the amount of radiation is under debate.

The figure quoted is a whole body radiation estimate from the device. If backscatter used the same energy as a standard X-Ray, your full body would get the dose mentioned. But backscatter radiation is not equivalent, as it uses lower energy and does not penetrate the body. A group of scientists in California have estimated the amount of radiation on the skin is likely to be 20 times higher, if not more. Considering the limited depth of the X-Ray, I would not be surprised to find this concentrated area receiving much higher doses. Until there is a peer reviewed study, all figures should be considered suspect.

The government estimates 1 additional cancer death per 200 million scans, so there is an awareness of a risk, albeit a very minor risk (except to that one person?). One additional death means many additional individuals coming down with cancer. The question is how many additional cancer deaths if the radiation figure is off by a factor of 20 … or more?

There are also scanners that use millimeter wave technology, or radio waves. The assumption is these scanners are safer, as they do not use radiation. Probably correct, but there are detractors from this idea. Scientists in California have shown that while radio waves cannot knock DNA base pairs or sequences out of whack, like radiation, they can do other types of DNA damage, like ripping the DNA strands apart. The setup of the millimeter wave scanners are different enough they could not cause this type of damage, but are there other unhidden types of damage?

There is also a topic I have not seen covered by the media and that is the fact that the scanners are set a low resolution. This leaves an option of increasing resolution; perhaps not with the current machines (not sure), but what if we decide we need more? Increasing resolution means increasing the beam, which means increasing the risk.

The risk appears to be very low. In fact, I would agree with the apologists that it probably is low, but I question whether or not it is necessary. More about this in the section on Effectiveness and Reasoning.

Privacy Concerns

One image that is being bandied about the Internet is this one:


Click photo to read article on this photo

This is stated to be a TSA image reversed in Photoshop. The gun in the back gives it enough validity for the average person to buy into what I see as a ruse. The problem is neither of the technologies present would capture the hair. NOTE: The photo shoot these pix were faked from is available here (NSFW).

But, even with the scans not able to capture this good of a picture, the scans are good enough to capture some detail which could embarrass someone. TSA has stated the images cannot be saved and later disseminated, but there are scans from the same type of scanners, albeit NOT in an airport, that have been released on the Internet. These scans are low resolution, but the resolution can be turned up.

I personally don’t have a lot of concern on the privacy front. I already have people scanning all of my possessions and occasionally rifling through my possessions. If privacy was a major concern, I feel the people should have revolted a long time ago. I will once again ask, however, whether or not it is necessary.

Effectiveness and Reasoning

If you have not seen the video of Adam Savage speaking in Seattle, you should take a look. On a recent flight, he states he accidentally carried on two extremely long razor blades which were not caught by the scanners. Others are envisioning terrorists molding explosives to their bodies, which would be missed by the scanners.

This leads one to wonder if the device is effective. And, if not, why burden the public with any risk?

This is not really about safety, but the appearance of safety. Certainly, the scans do catch some things. But the scans are only as good as the scanner, and they miss a lot. I have made it through security with full bottles of water, although they did catch my slightly oversized tube of toothpaste once (God forbid someone walking on with really clean teeth).

What we are observing is security theater. Make it look good and hopefully you will deter enough people that mean the public harm. At the same time, you will keep the average member of the public feeling safe enough to fly and ensure we have an airline industry to get us to our destinations.

When the security theater is merely an inconvenience, then it is probably fine. The deterrent is probably worth an extra half hour, right? But when you add inconvenience to a 1 in X chance of cancer and potential invasion of privacy, is it still worth it? If it catches people who bring very large razor blades on planes, then we might say yes … but they missed that one. Maybe next time?

The sheeple of the United States have acquiesced to the scans overall. I talked to a gentleman in the Austin airport the day before Thanksgiving who was ridiculing anyone who would not walk through the scans. I presented him with some contrary evidence that was backed by scientists, so he probably thinks I am one of the idiots now. Then again, perhaps I gave him a bit of food for thought.

My Thoughts

I am not going to go through the scanners. I don’t feel there is a huge risk, but I don’t feel there is a need to burden myself with any additional risk, no matter how small. If I go through the scanner, the government won’t make my plane arrive 4 minutes faster to offset the additional radiation. And they can’t shield me from radiation in my home town, or wherever I visit. There are simply no ways to offset this additional risk through some type of radiation “trade”.

Until there is a peer reviewed scientific study of the scanners, it is unlikely I will ever submit. And, even then, I don’t need to risk being one of the 1 in 200 million, no matter how small that risk is.

If the scans stop terrorists from blowing up planes, perhaps they can be a good thing. To date, I have heard of no incidents where the scanners have caught anyone. And, if they do, I would like some evidence the person would not have been caught by other means already in place, however, before giving any stamp of approval to a scanner.

I have serious issues with the idea that a handful of people dying of cancer each year is worth the security theater and appearance of safety. Until we show a case where it works, and previous technology would not work, I don’t see my mind changing on this one. Even then, I have to question how many such attempts thwarted by the scanners equal the number of projected deaths.

Peace and Grace,
Greg

Twitter: @gbworld

Domain Objects: The Importance of State


When I stoked up Windows Live Writer, my intent was to write an entry about testing. Specifically, I was going to aim at testing the domain. Then I realized I had never written an entry on domain objects and thought it was a necessary place to start.

As a disclaimer, this article is not the be all, end all of explanations of domain modeling. If you want a full treatise, you would be best reading Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans. If you want to stick in the .NET world, Applying Domain Driven Design and Patterns by Jimmy Nilsson is also a good read.

What is a Domain?

Now this is the thousand dollar question. What is a domain? Rather than answer the question straight out, let’s look at a scenario. Picture a company that takes orders via phone (or Internet, if phone orders seem antiquated). There is an application to take an order, another to box the items in the warehouse and a third to ship the items to the customer.

If we look at this scenario from the database, we might see a schema much like the one below.

image|
Above taken from Adventure Works, SQL Server 2008 R2

Now, if we take the schema above, we can build each of the applications by mirroring the schema as objects in the applications. This is acceptable, but not optimal. In addition, we are potentially exposing sensitive customer data, like payment information, to employees who have no need to see the information.

Let’s talk about a customer for a second. In the ordering application, all of the customer information is important. We need to know the customer’s name, address or addresses (if there are different home, credit card and shipping addresses, for example), at least one telephone, and at least one form of payment information. This application may be served well by simply mirroring the database schema. In other words, in the order “domain”, we need all types of information about a customer.

When we move to the shipping domain, however, we only need a name, phone number and shipping address. The customer object may be better set up like the following C# code:

public class Customer
{
    public string Name { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string PhoneNumber { get; set; }
}

In the warehouse domain, we don’t really need to have a customer object at all, as we simply need to pick some items and put them in a box. To aid the application in the shipping domain, we can print out a order label that can be scanned.

In the above example, there is one application per domain, but we can have multiple applications in a single domain. We can, theoretically, have applications that cross multiple domains, but that is a concept beyond this post.

Now we can return to the question: What is a Domain? A domain is a specific area of influence for an application. In my examples, I use the idea of an order domain, a warehouse domain and a shipping domain. Perhaps a weak example, but it shows that an object can radically change from the expected object in a relational database. And that is worth the price of admission (currently free).

Creating Domain Objects

In general, a domain object is an object that holds state. While there are patterns, like Active Record, that have “smart” objects that contain behavior, the norm for the domain are containers that hold current information about an object, or its current state. The repository pattern, which separates behavior and state, is much more common today.

To put it in a way that jogs memory, just think of BS. Domain objects deal with the S (state) in BS (behavior and state) and not about the B (behavior).

Since we are only dealing with state, it is extremely easy to make our domain objects, as we can use the simple property format:

public class ObjectType
{
    public Type PropertyName { get; set; }
}

When I start a new project, the first folder I create is the domain folder. I then set up two projects, one for domain objects and another for domain specific exceptions. I will then determine whether or not to test the domain objects, which is the subject of the next post. The Visual Studio project will look something like this:

image

I will cover more of the project setup I use in future posts.

Important Points

  1. A domain is an area of influence. When we develop an application, we need to find the Subject Matter Expert (SME) in that domain and have them help us determine the domain objects.
  2. Domain objects handle state and do not deal with behavior.
  3. Domain objects should be a primary or “first” concern when developing an application.

See you at the next post, which covers the question “should I set up tests on domain objects?”

Peace and Grace,
Greg

Twitter: @gbworld

Follow

Get every new post delivered to your Inbox.