Musings<Biefeld>
- curiosities of development, life, the universe and everything -
Archive for the ‘Coding’ Category
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.


Wednesday, February 11th, 2009

Today when preparing for our code review I happened upon a few methods in our base repository. Those methods were using NHibernate to retrieve collections of objects from persistence. I started scanning over the methods and figuring out what they were trying to accomplish. After understanding their function I noticed that they were prime candidates for a refactoring.

The methods were:

public virtual IList<Entity> GetAll()
{
	return Session.CreateCriteria(typeof (Entity)).List<Entity>();
}

public virtual IList<Entity> GetActiveItems()
{
	ICriteria criteria = Session
		.CreateCriteria(typeof(Entity))
		.Add(Restrictions.IsNull("InactiveDate"));

	return criteria.List<Entity>();
}

public virtual IList<Entity> GetItemsLikeName(string name, string columnToCompareBy)
{
	ICriteria criteria = Session.CreateCriteria(typeof(Entity))
		.Add(Restrictions.IsNull("InactiveDate"))
		.Add(Restrictions.Like(columnToCompareBy, name, MatchMode.Start).IgnoreCase());

	return criteria.List<Entity>();
}

Analysis:

Now the first thing that tipped me off to the need for Refactoring was the DRY (Don’t pete and repete yourself) principle, which can be extrapolated into Attwood’s Curly’s Law and even further to the Single Responsibility Principle. At least, I thinks DRY’s a principle, maybe it’s classified as a technique, or to be more in tune with coding hype a code smell. Lol, code smells, it may work if compared to flatulence but if you compare it to cheese, the more pungent the odor, the better the cheese. Actually it has more to do with identifying different smells so that you know what needs to be refactored or reworked entirely. Anyway, they all pretty much are talking about the same thing, minimizing duplicate code/rules/processes.

The Break Down:

The first thing I noticed was the responsibility of all the methods, they are responsible for retrieving a collection of objects. I observed this by the methods’ return types of IList<Entity> and their names, GetAll(), GetActiveItems(),GetItemsLikeName().

Next all of the methods are following the same basic pattern(process) of creating an ICriteria object, setting the specified ICriterion(where my object equals some value) on that ICriteria and finally executing the retrieval of the matching objects. The following is some psuedo code of that pattern(process)

ICriteria criteria = Session.CreateCriteria(typeof(Entity))
		.Add(ICriterion)
return criteria.RetrieveMatchingObjects<Entity>;

The Refactor:

Now we know the reponsibility and the process of all three methods. From this knowledge we can refactor those methods to use one method, but we will want to keep the signatures of each method, because they still have a separate responsibility as well. Let’s see the common concern is collection retrieval through different criteria. To address handling the different criteria we can utilize c#’s keyword params to pass in a variable number of criterion. Now, our combined method signature should look like:

protected virtual IList<Entity> GetAllItems(params ICriterion[] criterion)

Our refactored method is ready to return a collection of objects and to accept n number of ICriterion.

Next we need to create our ICriteria creation:

ICriteria getCriteria = Session.CreateCriteria(typeof(Entity));

After that it’s on to handling our array of ICriterion:

if (criterion != null)
{
	foreach (var criteria in criterion)
	{
		getCriteria.Add(criteria);
	}
}

First we need to check if the array is null, it is always good to check for null before trying to loop through an IEnumrable. Once we are sure that the array is not null we can loop through that bad boy and add the criterion to our ICriteria object. At this point we can execute our query, I prefer burning at the stake, but it’s up to you. Anyway our retrieval and return will (survey says) look like:

IList<Entity> result = getCriteria.List<Entity>();

Next on the proverbial platter, both the GetActiveItems() and GetItemsLikeName() methods are using the same criteria in their queries, the null check of Inactive Date. Ah ha, another point to refactor, stop the repetition. Let’s create a read onlyICriterion property named WhereInactiveDateIsNull, remember fluent interfaces are your friend. If the name is unclear now, it may make more sense in a bit, so chill.

protected virtual ICriterion WhereInactiveDateIsNull
{
	get
	{
		return Restrictions.IsNull("InactiveDate");
	}
}

Alright so we now have our one method to rule them all, or at least the three methods we were looking at before.

The Result:

So now all of our methods are going to call the method we created and tell that method their own specific responsibilites through the criterion they pass in.

protected virtual ICriterion WhereInactiveDateIsNull
{
	get
	{
		return Restrictions.IsNull("InactiveDate");
	}
}

protected virtual IList<Entity> GetAllItems(params ICriterion[] criterion)
{
	ICriteria getCriteria = Session.CreateCriteria(typeof(Entity));

	if (criterion != null)
	{
		foreach (var criteria in criterion)
		{
			getCriteria.Add(criteria);
		}
	}

	return getCriteria.List<Entity>();
}

public virtual IList<Entity> GetAll()
{
	return GetAllItems();
}

public virtual IList<Entity> GetActiveItems()
{
	return GetAllItems(WhereInactiveDateIsNull);
}

public virtual IList<Entity> GetItemsLikeName(string name, string columnToCompareBy)
{
	ICriterion whereColumnValueStartsWithNameIgnoringCase
		= Restrictions.Like(columnToCompareBy, name, MatchMode.Start).IgnoreCase();

       	return GetAllItems
	(
		WhereInactiveDateIsNull,
		whereColumnValueStartsWithNameIgnoringCase
	);
}

The Interlude:

“Oh, this little guy? I wouldn’t worry about this little guy.”


That just popped into my head, I must be astral projecting again. Seriously, if you don’t know what that quote is from, you fail at life, nah, just joking, look it up. Hmm, it must be late, my mind is wandering. Blogging and jamming. Jamming, is that still a socially acceptable term? Jamming to The Tangent, great stuff.

The Conclusion:

Ah, the fruits of our labor are so sweet. Remember, I know it’s hard, but remmember when I was speaking of the fluent interface, ah now you remember. Excellent, so if we take a look at our new GetItemsLikeName() method we can see the fluency at work;

we want to GetAllItems(WhereInactiveDateIsNull,(and) whereColumnValueStartsWithNameIgnoringCase).


If you can’t glean what this is doing from the naming, I am sorry, but there is no hope for you, :) . This fluent interface does several things, it decreases the learning curve for new-comers, increases the readability of our code, and overall increases the maintainability.

I find that the best thing to do is try to contemplate the Single Responsiblity Principle, Dont Repeat Yourself Principle, or other sundry names for it; when you are satisfying your broken tests, assuming you are testing first. I know that sometimes it can be hard but it is a fracking awesome practice to achieve. Even if you can’t see the common responsibilities at first, definitely try to find them after your tests pass. Red, Green, Refactor.


Monday, February 9th, 2009


My pondering stems from a song (which hereby refers to a Twitter discussion, eh, why not?). This song was started by a tweet from one of my co-workers earlier today.


First a bit of background, I have been able to glean the key purpose(s) of Domain Driven Design from my co-workers and from researching it a bit here and there. Unfortunately, I have not been able to sit down and read through Eric Evans’ Domain Driven Design book. So, you might say that I am some what of a novice when it comes to domain driven design. One might say my knowledge of it, is fairly infantile, but they would be mediocrates.


I have learned are that DDD is a different mode of thinking about software. Analyzing the context of the business process you are reproducing with software and then translating that into the design said software. You come up with things like the Ubiquitous Language to better serve the need to replicate the targeted processes. That being said a lot of it seems to be logical conclusions that one would arrive at through thought, trial and error over an amount of time.


One of the key ideas that I took away from my gander into DDD, was that validation should happen at the domain level. I have been wrestling with this idea in my mind for a week or two. The wrestling began when I read a posting on Anemic domain models and subsequently read Martin Fowler’s original posting on the subject. After absorbing that information a light bulb ignited in my noggin, pretty much the whole domain model of the project I am currently working on satisfies the classic definition of an anemic domain model, i.e. classes containing only properties with getters and setters. Yikes! I realized that we had been doing everything wrong, all of our business logic was in our presenters. Well, there is no time to go back and correct everything at the moment. I have been striving to get away from this bad habit with our latest feature and it just so happens that today that along came a Twitter song regarding domain validation and more abstractly, anemic domain models.


My co-worker had a wonderful question about defensive coding / unit testing and a statement regarding domain validation:


@derickbailey:
“Q: should I do defensive unit testing / coding immediately, or wait until someone finds a bug to do the defensive coding?”
“i’m sold on “model / view / presenter / presentation model” idea at this point. presentation model contains input validation”
“example:’make sure i have a valid date time, not an empty string’. would you call that business rules? “


My overall response was yes, it is definitely worth defensive coding / unit testing, if you wait for the bug to crop up in the UI, it will be much more expensive to fix, which is expressed by Scott Bellware’s latest posting. There were also some other various tweets about the difference between UI validation and validation in the domain. Validation as business constraints not processes.


Derick’s question/statement led to this response from Bellware:


@Bellware:
“why are business rules and input validation not the same?”


Next, Bellware went into some abstract ideas that were relevant to the topic at hand, but went over my head completely. It seems he enjoys doing this regularly :D , but thats just my musings. Anyway, he and Derick were discussing the abstractions, then Bellware stated some things to me about DDD:


@Bellware:
“what if the only domain is the domain that creates the need for that validation?”
“if it’s all you need to deal with, then you don’t need anything more elaborate”
“a domain that isn’t built for a specific context is pure technical masturbation. it earns you demerit points, not promotions.”


Bellware’s statements got the Grey matter churning in my head. At first, I was thinking of domain and context synonymously in my head, but then he clarified it for me. Context refers to such things as a web application, an operating system application, hardware driver etc. Derick’s example of getting a date from a string can be viewed as strictly a concern when dealing with a web interface(context). Is Bellware proposing a domain should be geared towards a specific interface implementation? If a domain is not aimed at a specific context then is it a fruitless effort in self indulgence?


Well, now I am stuck in an endless loop pondering my perceptions of DDD. It would probably be prudent to invest some time reading Eric Evans’ Domain Driven Design, to get a better grasp on the tennents of DDD and the reasoning behind them. I’m sure I will gain more understanding in time from research and mulling these ideas over in my head.


As a side note, this song has proven to me the usefulness of a tool such as Twitter. I was somewhat skeptical of it at first, and had passed it off as another mundane social networking tool used to gratify the cravings of narcissists. It seems it can be used for good and evil.


Friday, February 6th, 2009

How often do you use lambda expressions?  I use them a great deal, mostly when I am making method assertions in Rhino Mocks.  If you do the bare minimum, which i see a lot, the expression can be somewhat cryptic.

Less readable:

Users.Find(x => x.Id == selectedUserId)

I am guilty of doing this as well, without even realizing.  Maybe I am just being nit picky.

I think it is much more readable if you use something more descriptive than some arbitrary letter in the alphabet.

More readable:

Users.Find(user => user.Id == selectedUserId)

This becomes much more useful when you are coding more complex lambda expressions.  One example is when making a method assertion using Rhino Mocks.

Less readable:

_userRepository.AssertWasCalled
(
     x => x.Save(newUser),
     o => o.IgnoreArguments()
);

With that assertion we have two arbitrary letters, what the heck does ‘x’ and  ‘o’ represent.  Are we talking about hugs and kisses.  I don’t think so.

So to remedy this, lets change ‘x’ to ‘userRepository’ and ‘o’ to ‘method assertion’.  I believe these terms will make the assertion much more readable and concise.

More readable:

_userRepository.AssertWasCalled
(
     userRepository => userRepository.Save(newUser),
     methodAssertion => methodAssertion.IgnoreArguments()
);

With that little change it is much easier to understand what is being asserted and what parameters are being set on that assertion.

The hardest part is breaking the habit of using arbitrary letters.  In the long run a more descriptive expression improves the readability of the code.  It will also decrease the amount of time it takes a new person to understand the lambda expressions in the code base.

Monday, November 24th, 2008

Here is some useful JavaScript that wrote today to change a CSS class based on the state of a checkbox.

function replaceCssClassOnElementBasedOnCheckBoxState(checkboxId, elementToChangeId, checkedCssClassName, uncheckedCssClassName)
{
    var selectedElement = document.getElementById(elementToChangeId);
    var checkBox = document.getElementById(checkboxId);
    if(selectedElement && checkBox)
    {
        if(checkBox.checked)
            selectedElement.className = checkedCssClassName;
        else
            selectedElement.className = uncheckedCssClassName;
    }
}

For Example:

The style of this div should change based on the state of the checkbox.

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