Musings<Biefeld>
- curiosities of development, life, the universe and everything -
Archive for the ‘Coding’ Category
Wednesday, November 16th, 2011


Hello techies,


I have been using Appcelerator recently. It is a pretty cool tool, it allows you to create cross platform mobile applications for iOS and Android, writing JavaScript.


Appcelerator’s Titanium Framework uses the CommonJS API so you can reference javascript files as “modules”, it is very reminiscent of node.js which also implements CommonJS.


Below is a simple async module I wrote, inspired by codeboxed’s gist, to make requests to a web server. Stick it in a file named SimpleHttpAsync.js


  //////////////////////////////////////////////
 //                Simple Async              //
//////////////////////////////////////////////

exports.call = function (options) {
    //create the titanium HTTPClient
    var httpClient = Titanium.Network.createHTTPClient();

    //set the httpclient's properties with the provided options
    httpClient.setTimeout(options.timeout);
    httpClient.onerror = options.error;

    //if and when response comes back
    //the success function is called
    httpClient.onload = function(){
        options.success({
            data: httpClient.responseData,
            text: httpClient.responseText
        });
    };

    //open the connection
    httpClient.open(options.type, options.url, true);

    //send the request
    httpClient.send();
};

The following is example code of importing and using the module

//import the module
var simpleAsync = require('async');

//call the function
//handle errors and successful request
simpleAsync.call({
    type : "POST",
    url : "http://www.someurl.com?somekey=somevalue",
    error : function (error) {
        //do something to handle error
    },
    success : function (response) {
        //do something with the response data from the server
    },
    timeout : 10000
});


It’s nothing special, but the documentation for Appcelerator is pretty sparse and I thought it might be useful for those new to the Appcelerator Titanium Framework.


As always enjoy and let me know if you have any comments/suggestions/questions. Thanks!


Friday, October 21st, 2011

Hello all, it’s been a while since I have blogged anything, been extremely busy with personal events in my life. So to get back into the swing of things I am going to KISS this post.

I recently needed to convert XML to JSON in PHP. Thankfully, PHP has built in functionality to handle precisely this task.

First we need to get contents of the XML file, we need to use file_get_contents() and pass it the URL to the XML file. We remove the newlines, returns and tabs.

$fileContents = file_get_contents($url);

$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

Next I replace double quotes with single quotes and trim leadign and trailing spaces, this helps to ensure the simple XML function can parse the XML appropriately. Then we call the simplexml_load_string() function.

$fileContents = trim(str_replace('"', "'", $fileContents));

$simpleXml = simplexml_load_string($fileContents);

The final step we need is to convert the XML to JSON, for that we will use the json_encode() function.

$json = json_encode($simpleXml);

That’s it! All together now:

<?php

class XmlToJson {

	public function Parse ($url) {

		$fileContents= file_get_contents($url);

		$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

		$fileContents = trim(str_replace('"', "'", $fileContents));

		$simpleXml = simplexml_load_string($fileContents);

		$json = json_encode($simpleXml);

		return $json;

	}

}

?>

Now if we want to utilize our creation we can create a file which uses the class we created above, assuming we store the XmlToJson class in a file named XmlToJson.php. We can create a file for a specific XML web service, include our class and call it XmlToJson::Parse($url). Just for fun we’ll point to the XML for the NFL scorestrip.

<?php

include 'XmlToJson.php';

print XmlToJson::Parse("http://www.nfl.com/liveupdate/scorestrip/ss.xml");

?>

Now we can call our new file, say we name it getNflDataAsJson.php, it will return the converted JSON. Calling it from jQuery below:

$.getJSON('getNflDataAsJson.php', function(data) {
	//do something
});

Thats all I’ve got, let me know if you have any questions, things you would do differently or general comments.

Thanks much!

Wednesday, September 21st, 2011

Found this solution rather simple when you want to serve images from your database.

public class ImageController
{
	readonly IImageQueries Queries;

	public ImageController(IImageQueries queries)
	{
		Queries = queries;
	}

	public FileResult Show(int id)
	{
		DateTime? dateCreated = Queries.GetDateCreatedById(id);

		//invalid image, return 404
		if (dateCreated == null)
		{
			HttpContext.Response.StatusCode = 404;

			return null;
		}
		else
		{
			string ifModifiedSince = HttpContext.Request.Headers["If-Modified-Since"];

			//check if image has been modified
			if (ifModifiedSince != null && dateCreated.Value <= DateTime.Parse(ifModifiedSince))
			{
				HttpContext.Response.StatusCode = 304;
				return null;
			}
			else
			{
				HttpContext.Response.Cache.SetLastModified(dateCreated.Value);

				dynamic image = Queries.GetById(id);

				return new FileContentResult(image.Bytes, image.MimeType);
			}
		}
	}
}
Friday, September 9th, 2011

Hello fellow techies on this roller coaster called life. It has been a while since my last post, I have been focusing on some other more important aspects of my life.

What I want to talk about in this post is the idea of a dynamic view page which removes the need for a View Model data transfer object. I have started to try this out on project that I am working on, for views that are essentially read only. All these views are concerned about is displaying data/information.  I do not yet know how useful this is but I thought it was novel and will be exploring it’s usefulness. Plus, the lazy side of me likes the idea of not creating data transfer objects if possible.

Two side effects of this approach are the loss of the strongly typed Model on your view, which is a non-issue for a page without inputs.  The second is the loss of intellisense (the very first time a member is used on a dynamic) when working with the Model in the view, which could be a minor loss in that you wont know something is wrong until you run it, but thats the way it goes.

To accomplish this you start off by creating a DynamicViewPage that inherits ViewPage.  Have some overrides and new up some properties and you should be set.

public class DynamicViewPage : ViewPage
{
	private ViewDataDictionary<dynamic> _viewData;

	public override void InitHelpers()
	{
		base.InitHelpers();
		Ajax = new AjaxHelper<dynamic>(ViewContext, this);
		Html = new HtmlHelper<dynamic>(ViewContext, this);
	}

	protected override void SetViewData(ViewDataDictionary viewData)
	{
		_viewData = new ViewDataDictionary<dynamic>(viewData);
		base.SetViewData(_viewData);
	}

	public new AjaxHelper<dynamic> Ajax { get; set; }

	public new HtmlHelper<dynamic> Html { get; set; }

	public new dynamic Model
	{
		get
		{
			return ViewData.Model;
		}
	}

	public new ViewDataDictionary<dynamic> ViewData
	{
		get
		{
			if (_viewData == null)
			{
				SetViewData(new ViewDataDictionary<dynamic>());
			}
			return _viewData;
		}
		set
		{
			SetViewData(value);
		}
	}
}

Now your view needs to inherit from DynamicViewPage.

Inherits="Web.Views.DynamicViewPage"

In your controller you can ask your persistence abstraction of choice for some data and return it to the view.

public ActionResult Index()
{
	IEnumerable<dynamic> foos = FooQueries.GetAll();
	return View(foos);
}

Where this can get interesting is when you have a linq provider that returns dynamic objects. Then essentially your domain model is king and you eliminate a lot of DTOs. That’s all I’ve got for now. I attached a sample application that demonstrates the dynamic view, enjoy!

Thursday, August 27th, 2009


Whilst researching using MSpec with ReSharper I found it difficult to find all the resources I needed in one place. This is an attempt to condense everything into that one place and facilitate those seeking to accomplish the same task.

Step 1 – Git It:

First thing’s first, grab the latest Machine Spec source from github.

$ git clone git://github.com/machine.machine.specifications.git mspec

Step 2 – Build It:

Next, open it up in Visual Studio, set it to build in release mode and build it. Now the binaries will be ready for you.

Step 3 – Setup ReSharper:

Now we need to setup ReSharper to be able to utilize the MSpec framework and run the tests in ReSharper’s test runner. To do this we need to add a plugins directory to the “JetBrains\ReSharper\v4.5\Bin” directory or the where ever the bin directory for your ReSharper is located. In the Plugins create a Machine.Specifications directory, so you should now have a path similar to; “JetBrains\ReSharper\v4.5\Bin\Plugins\Machine.Specifications”. Place the following dlls in the newly created folder: Machine.Specifications.ReSharperRunner.4.5.dll and Machine.Specifications.dll.

Step 4 – Write some Specifications:

Coolio, now to test some behaviors, the dlls needed in our test project; Machine.Specifications.dll, Machine.Specifications.NUnit.dll or Machine.Specifications.XUnit.dll, and the appropriate test framework dll.


Let’s take a look at a couple of examples to get used to the syntax. The most common keywords you want to pay attention to are Subject, Establish, Because and It. Declare the Subject of your Spec, Establish a context of the spec, Because x occurs, It should do something. For more complex scenarios you can use the keyword, Behaves_like and the Behaviors attribute which allows you to define complex behaviors. If you need to perform some cleanup use the Cleanup keyword.

Now for a couple of simple contrived examples…

This first specification looks at adding two numbers:

[Subject("adding two operands")]
public class when_adding_two_operands
{
	static decimal value;

	Establish context = () =>
		value = 0m;

	Because of = () =>
		value = new Operator().Add(42.0m, 42.0m);

	It should_add_both_operands = () =>
		value.ShouldEqual(84.0m);
}

The second specification looks at adding multiple numbers:

[Subject("adding multiple operands")]
public class when_adding_multiple_operands
{
	static decimal value;

	Establish context = () =>
		value = 0m;

	Because of = () =>
		value = new Operator().Add(42m, 42m, 42m);

	It should_add_all_operands = () =>
		value.ShouldEqual(126m);
}

The code being tested:

public class Operator
{
	public decimal Add(decimal firstOperand, decimal secondOperand)
	{
		return firstOperand + secondOperand;
	}

	public decimal Add(params decimal[] operands)
	{
		decimal value = 0m;

		foreach (var operand in operands)
		{
			value += operand;
		}

		return value;
	}
}

Step 5 – Create Templates to Improve Your Efficiency:

Using ReSharper templates is a good way to improve your spec writing efficiency, the following are templates I have been using.

This first one is for your normal behaviors:

[Subject("$subject$")]
public class when_$when$
{
	Establish context =()=>	{};

	Because of =()=> {};		

	It should_$should$ =()=> $END$;
}

This one’s for assertions by themselves:

It should_$should$ =()=> $END$;

Step 6 – Run the Report

The report generated is pretty much the exact same as the SpecUnit report. The easiest thing to do is place the following MSpec binaries and file in the directory where your test binaries are placed; CommandLine.dll, Machine.Specifications.ConsoleRunner.exe, Machine.Specifications.dll and CommandLine.xml. The command to run the report goes a little something like:

machine.specifications.consolerunner --html <the location you want the html report stored> <your test dll name>

This is the report generated from the example specs:

MSpecReportExample


Well, that’s about all for now, let me know if you have any questions.


Tuesday, May 12th, 2009


*UPDATE: Per sean chambers, this is an example of the adapter pattern


I recently ran into an issue where I needed to implement a simple email service to send users a randomly generated PIN when they are first entered into the system. To accomplish this I decided to just use the System.Net.Mail implementation.  To create and send an email you have to use the SmtpClient class which does not implement an interface. All I really wanted to test was that the Send() method was called, I did not want to write an integration test that actually sends an email.


One way to work around this problem is to create an interface containing the elements you need to mock from the compiled class.  After this, create your own class that inherits the compiled class and implements your interface. Now when testing, you can seemingly mock up the non-interfaced compiled class, which is exactly what I wanted to achieve. I am not sure whether this is the appropriate way to handle the issue, if anyone has any thoughts on a better way to do this, I would be grateful for the advice.

My specification ended up looking like this:


public class EmailServiceSpecs : ContextSpecification
{
	protected IEmailService _emailService;
	protected ISmtpClient _smtpClient;
	protected string _emailTo = "phillip.fry@planetexpress.com";
	protected string _emailFrom = "hermes.conrad@planetexpress.com";
	protected string _emailSubject = "New Process to Improve Morale";
	protected string _emailBody = "From now on all employees will be required to have Brain slugs, remember, a mindless worker is a happy worker.";

	protected override void SharedContext()
	{
		DependencyInjection.RegisterType<IEmailService, EmailService>();

		_emailService = DependencyInjection
			.GetDependency<IEmailService>(_emailTo, _emailFrom, _emailSubject, _emailBody);

		_smtpClient = MockRepository.GenerateMock<ISmtpClient>();

		DependencyInjection.RegisterInstance(_smtpClient);
	}
}

[TestFixture]
[Concern("Email Service")]
public class when_sending_an_email : EmailServiceSpecs
{
	protected override void Context()
	{
		_smtpClient.Stub(smptClient => smptClient.Send(new MailMessage()))
			.IgnoreArguments()
			.Repeat.Any();

		_emailService.Send();
	}

	[Test]
	[Observation]
	public void should_send_email()
	{
		_smtpClient.AssertWasCalled<
			(smtpClient => smtpClient.Send(new MailMessage()),
			assertionOptions => assertionOptions.IgnoreArguments());
	}
}

Below are my email classes:

public interface ISmtpClient
{
	void Send(MailMessage message);
}

[MapDependency(typeof(ISmtpClient))]
public class SubsideSmtpClient : SmtpClient, ISmtpClient { }

public interface IEmailService
{
	void Send();
}

[MapDependency(typeof(IEmailService))]
public class EmailService : IEmailService
{
	public EmailService(string to, string from, string subject, string body)
	{
		Email = new MailMessage(from, to, subject, body);
	}

	protected MailMessage Email
	{
		get; set;
	}

	private ISmtpClient _smptClient;

	protected ISmtpClient Smtp
	{
		get
		{
			_smptClient = DependencyUtilities
				.RetrieveDependency(_smptClient);
			return _smptClient;
		}
	}

	public void Send()
	{
		Smtp.Send(Email);
	}
}
Tuesday, April 14th, 2009


I just finalized my text color theme for visual studio. Just thought I would share it with everyone. It is geared towards those of you who have resharper installed, but it should still work fine without it.


The theme is based off of the textmate twilight theme. I was going for a low contrast theme that is easy on the eyes.  I have tried the Vibrant Ink theme and it is too abrasive for me. My goal was to make warnings and errors blatantly obvious and distinguish classes from interfaces. I also love how the comments are dark and do not draw attention, I am not a big fan of comments.  I think the code along with BDD tests should be self-explanatory of what is going on.


All resharper warnings show up as red text. Build errors have red squiggly lines under them.  Breakpoints have red background.


Here is a c# example:



Here is an example of an aspx page:



Style sheet example:



JavaScript example:



Let me know if you have any suggestions.


Grab the Visual Studio settings file here!


Tuesday, March 3rd, 2009


As .net developers do you ever feel like Microsoft is hindering your development by the development tools they impose on us. I have been thinking about this lately and decide to discuss it, or this might actually be a rant, forgive the rant. I aim to take a brief look at web development the Microsoft way, how it has evolved, and the hindrances imposed on the community.

The Microsoft Web Development World

Now I have never developed Microsoft web applications pre-webforms, i.e. pre-Asp.net, so I am not going to comment on that. What I am going to focus on is Microsoft’s asp.net development frameworks. As a side note, I have not done much development on the windows side of things, but it seems that it has been stagnating. I would love to see Microsoft write some bindings for GTK+ and/or Qt, and support those cross platform toolkits. Pie in the sky dreams, I know.

ASP.NET – Web Forms

Somehow in their brilliance, big brother decided that abstracting HTML and Javascript into a infinitely more complex framework would be a good idea. This is ludicrous, don’t introduce unnecessary bloat into a framework. The page life cycle is ridiculous, all the built in webform controls use some retarded infinite inheritance scheme. Also what’s Microsoft’s infatuation with span tags, they wrapped all their webform controls in them.


Lol, I know this is common knowledge and has been discussed at length before but I still have to deal with it on a daily basis and it feels like I’m trying to cut off my leg with a steak knife. My interest lies in finding the true reasoning behind this. I have to working theories. One is that Microsoft is so loving and kind towards their developers that they wanted to coddle them, and that coddling most likely stemmed from their lack of respect for us and our intelligence. The other theory is that Microsoft convoluted the framework without realizing it due to their arrogance, believing they own the world and the way they are doing things must be right.

ASP.NET AJAX

Next the web 2.0 boom arrived and everyone was clamoring for more interactive web UIs. The .net developers yelled loud enough and long enough that they wanted to have the same thing that they were witnessing in other web frameworks. The keyword here is ajax. So what does Microsoft do, they don’t take this moment and think about totally redesigning their asp.net framework, they say lets create some more complex web controls and use them in conjunction with an uber-complex ajax framework.


Awesome, we now how fresh steamy poo piled on top of old rotting, festering poo. Thanks big brother. Instead of realizing their mistakes they made with web forms they exacerbate the problem. Now we get a seemingly dumbed down ajax scheme, oh just wrap everything in an update panel and Microsoft will do the rest. Besides the fact that this removes all control you have over the interactions between the server and client, you also can not use any other javascript inside of these panels. So once again it boils down to arrogance, contempt, and a lack of foresight.

ASP.NET MVC

Now, Microsoft sees a significant proportion of developers moving to ruby utilizing the ruby on rails framework. Also the community is yelling and screaming again, must be appeasement time. Did Microsoft actually take an introspective look and realize how ass backwards webforms is? Doubtful, they just figured out that they better do something to try and hold onto market share and give the community some fools gold. So they copy ruby on rails, ooooh, way to go big brother, you’re so innovative!


It is way too late in the game, asp.net mvc is something Microsoft should have done long ago. Back when they were formulating asp.net webforms. There is no excuse for Microsoft not to have created a framework like this when they introduced the asp.net ajax stuff. It’s ridiculous, and still they are losing market share, I wonder why.


They ignore their base long enough and they won’t have a base. What are we supposed to drink the kool-aid and be satisfied, the MVC pattern is how old? Oh, wow they are supporting a way to unit test the UI interactions, wow how progressive you are Microsoft. Where is the support for plugins, where is the support for RESTful web services? The point is there is nothing to be impressed about, it’s ridiculous that people are excited, this should have happened long ago.

Conclusion

Now don’t get your panties in a wad I’m not all cynical, I like c# as a language, even thought it is a static language and I like the CLR. Hopefully MVC is a sign that Microsoft is going to be moving at a less stagnant pace. I don’t think they will be.


Things like Mono, NHibernate, the alt.net community supplement the failings of the giant, but we should be fed up. Microsoft doesn’t listen, because of their corporate culture, which i doubt will change. Adding things to the web framework that should have been there long ago is nothing to celebrate, there i said it, “Big whoop, want to fight about it”.


On a larger scale, why is Microsoft not listening to the community more, why are they not seeking to improve the community along the lines of the ruby community? Where is Microsoft’s version of package management like ruby gems? Where’s their continuous integration/build tool? Where’s their testing framework? Where’s there promotion of best software practices, i.e. SOLID, TDD, BDD, Agile methodologies, Lean methodologies? The answer is no where, all of that exists inside the community without Microsoft’s support.


The community is bettering ourselves in spite of Microsoft’s stagnation. Now think what could be accomplished if they actually fully embraced the community and threw their money and clout behind what the community stands for, it would be great. I am very doubtful that will happen, though, I think it will take mass exodus from .net development for Microsoft to ever get the message. If nothing happens the .net community will continue to stagger along at the pace of Microsoft, it will not reach its potential, and the community will wither and die.


There is an entire software industry that needs to mature, the .net community is but a sub-section of it.  It would be great if we could lead the industry in best practices and passion for our craft.

Wednesday, February 18th, 2009


Obviously the answer to the titular question is yes.


I have recently found myself questioning whether the logic I am coding belongs in a domain service or in the presenter. I actually found the same logic in the presenter residing the base repository. Something definitely smells wrong, almost like the putrid smell of death, lol, nah just a DRY smell and a hint of mixed responsibility odor. The presenter was calling the Repository directly which was kinda of an indicator, but it is valid to do so, depending on the scenario.


The application that I am currently working in is a web application. That being said, I feel it is valid to consider the web limitations part of the current domain, not just a concern of the presentation. If we need to move to a windows app or something else, it will take a lot of refactoring, so why not just view the web’s issues as part of what affects the domain. Besides, is the purpose of the domain to be abstract enough to support multiple platforms or to dimish complexity? Anyway, that’s another discussion altogether, and I’m digressing.


Here’s the skinny, that’s a valid colloquialism isn’t it. I found string to integer conversion happening in two different places. Once in the presenter, grabbing a string Id from the view, converting it, calling an overloaded GetById method from the repository or throwing an exception if the Id was invalid. The overloaded GetById method was in the base repository, it either accepted a string Id or integer Id, if the string Id was invalid it was throwing an exception. Yikes, this is scary, and to think I was the one that coded all this, frightening, I know. I am recovering so don’t you worry yourself. Now to the current code:

Code to be Refactored:

Presenter

public virtual void InitializeView()
{
	if(TreatmentIdIsValid())
		LoadTreatment();
	else
		throw new ApplicationException(string.Format("A Record of Waste cannot be completed because of the invalid treatment id: {0}", View.TreatmentId));
}

private bool TreatmentIdIsValid()
{
	int validTreatmentId; 

	bool treatmentIdIsValid = int.TryParse(View.TreatmentId, out validTreatmentId); 

	if(treatmentIdIsValid)
		CurrentTreatmentId = id; 

	return treatmentIdIsValid;
} 

protected virtual void LoadTreatment()
{
	try
	{
		CurrentTreatment = Repository<ITreatmentRepository>.GetById(CurrentTreatmentId);
	}
	catch
	{
		throw new ApplicationException("Could not retrieve the specified treatment");
	}
}

Base Repository

public virtual Entity GetById(string id)
{
	int parsedId;

	if (!int.TryParse(id, out parsedId))
		throw new ApplicationException("Could not convert the given id: " + id + " into an integer");

	return GetById(parsedId);
}

public virtual Entity GetById(int id)
{
	return Session.Get<Entity>(id);
}

I think that there is no place for logic in the repository it should be left to the domain service. You could even argue that this functionality is common and can be moved to a domain utility. For ease I am going to move it to a domain service. Now, lettuce see the refactoring to the code above:

Refactored Code:

Presenter

public virtual void InitializeView()
{
	LoadTreatment();
}

protected virtual void LoadTreatment()
{
	CurrentTreatment = RecordOfWasteService.GetParentTreatmentById(CurrentTreatmentId);
}

Domain Service

public virtual Treatment GetParentTreatmentById(string id)
{
	int validTreatmentId;

	if (!int.TryParse(id, out validTreatmentId))
		throw new ApplicationException("Could not convert the given treatment id: " + id + " into an integer");

	return GetParentTreatmentById(validTreatmentId);
}

protected virtual Treatment GetParentTreatmentById(int treatmentId)
{
	try
	{
		CurrentTreatment = Repository<ITreatmentRepository>.GetById(treatmentId);
	}
	catch
	{
		throw new ApplicationException("Could not retrieve the specified treatment");
	}
}

Base Repository

public virtual Entity GetById(int id)
{
	return Session.Get<Entity>(id);
}

Alrighty then, we got any logic out of the repository, I’m feeling better already, my face has gone from grimace to grin, and no not the McDonlad’s character Grimace. Super serial, a la Al Gore about ManBearPig, what was Grimace, was he what you turn in to if you only eat McDonalds and nothing else?


The responsibility of the repository should be to read and write to persistence/web services/messages etc. The string validation logic is in the domain service, I may pull it out to a base service or utility service. Our presenter is so much simpler now, and not worried about logic that it shouldn’t have to worry about. Hmm, the cleanliness is delightful. There is no more duplication of logic in the presenter and repository, w00t! Now let me know your thoughts, comments, opinions etc. of dissent or agreement, it will help me and hopefully others learn and grow. I’m off to watch the some Teenage Mutant Ninja Turtle original series, wow, I’m a nerd.

Saturday, February 14th, 2009

Issue at Hand:

I have been recently sumo wrestling with the idea of entity validation in my mind. So far, the validation problem, which is like, E. Honda, has the advantage over my mind which is currently like, Chun Li. The worst thing is all the other thoughts in my head are constantly struggling against my entity validation thoughts. As Homer Simpson says, “Every time I learn something new, it pushes some old stuff out of my brain”. Except for me E. Honda is doing his grab move, where he squeezes his opponent between his fat, and squeezing all of my current thoughts out of my brain. I don’t understand how sumo wrestling evolved as a sport, do they really have nothing to do in Japan. I bet it was the master creation of some drunken emperor. Umm, let’s see I want to watch two super fat dudes wearing nothing but a diaper try to knock each other out of circle with their bellies, muahahaha, they’ll be playing this sport for centuries!

Ideation:

I have been pondering about the idea of validation. Dictionary.com says valid is: “sound; just; well-founded, producing the desired result; effective”. Wiktionary’s valid definition in terms of logic is:“A formula or system that evaluates to true regardless of the input values.” When we think of validation in a programmers state of mind, the definition of valid in the logical sense, seems to jive the best. If x == y then it is valid if x != y it is invalid.


Entity validation is determined by business rules and processes. It appears that there are two fundamental approaches to validation, proactive and reactive validation.

Reactive Validation:

The most common way I have seen validation handled is the addition of an IsValid state to the entity. A good way of implementing this approach can be found in a posting by Jimmy Bogard. Whenever a business rule or process is broken the entity is no longer in a valid state. Then the user is informed of the problem in a different layer of the application. This form of validation is a very reactive way of handling validation. Meaning that it waits until something bad happens and then performs a function to cope with the contaminated actions. I don’t like this reactionary response, I would rather use something more preventative.

Proactive Validation:

What is valid validation? I wonder how many times I can use the word valid, or one of its etymological children in this post? What is a valid number of uses? I think the answer is 42.


So, is valid validation a proactive or reactive approach? I believe that proactive is always the best approach. My definition of proactive entity validation is never allowing an invalid entity to exist. This means removing the concept of an IsValid state on the entity. Once that is removed you don’t have to do an IsValid check everywhere in the application, which is my main gripe with the reactive solution. Is it valid for your domain to ever contain an entity in an invalid state, something about this scenario makes my skin crawl and stomach churn, or maybe it has to do with something I ate last night. Hmm, it was spicy so maybe. An invalid entity just seems like a bad idea, it is a treacherous force that will actively work against you like Saruman’s voice being cast across middle earth. I think being proactive is a much cleaner approach, and will cleanse your domain of IsValid checks. Wow, that is just a proof less rant.


Now the question is, what’s the best way to implement such a proactive solution? That’s the E. Honda I have been wrestling with. Let’s go over the broad definition of proactive entity validation. An entity cannot be created if it does not meet the business rules. Once we have a valid entity it cannot be modified unless the modifications satisfy the business rules. The stumbling block arises when your entity’s validity is based on a certain context. For example, it is valid to have a physicians drug order without a signature. When the process requires that the order to be sent to the pharmacy, the order is only valid when it has a signature. Ah, now the proactive solution becomes tricky because valid is defined by context. Following the proactive approach I could not create the entity without a signature, because it would be an entity in an invalid state. The only solution that I have thought of to this is having a drug order without the signature and a drug order request that inherits drug order and has the signature. The pharmacy then receives that drug order request with the signature on it.

Outro:

I have not yet fully fleshed out the details of how exactly this would be implemented. I hope to hammer out a spike with a spiked drink. I do believe that using a proactive approach to entity validation falls more in line with domain driven design by having a tighter coupling to the business language. A drug order does not need a signature to exist. A drug order request with a signature fulfills the need of the drug order being sent to the pharmacy.


Be a proactionary and not a reactionary.


Musings<Biefeld> is proudly powered by WordPress
Entries (RSS) and Comments (RSS).