Musings<Biefeld>
- curiosities of development, life, the universe and everything -
Archive for February, 2009
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.


Thursday, February 12th, 2009

Intro (stream of consciousness and twitter):

I had and intriguing tweet session (song; in my twitter terminology) with James Marcus Bach. I learned of him through Scott Bellware’s tweets and decided to start following him. I went to Bach’s website, and and learned what I could from it. From what I could glean James Bach is a self-educated man achieving goals through his own passion for life and learning. He has a contempt for the educational system in this country, which is a contempt I share. Concerning the technology sector he has done software testing and has become an expert in the field. He seems to be pursuing the status of polymath, which is a very honorable goal, one that I would like to achieve in my life time. I have read his scholarly blog posts and they are inspiring to say the least. He also has a software testing oriented blog which is a good read as well.


Our interchange began when I read his tweet about copy-editors not sharing his line of thought about the formality of his writing. For some reason I decided to tweet at him about how the future of writing is going to be stream of consciousness narrative. Which is a form a narrative that I find quite entertaining and informative. Basically, stream of consciousness is distinguished by following every thought process that occurs in the narrator’s mind at the time the are pursuing a specific conclusion or idea.

To some extent I think that the goal of twitter is to communicate people’s thought processes to others. I believe when properly utilized this can lead to informative discussions, which benefit all parties following the narrator(tweeter).


I think that the other strength of stream of consciousness is the way it humanizes the narrator and his narration. This humanization is achieved by spiritual and emotional qualities of that are intertwined throughout the narrative. This human factor is a key aspect to connecting with the user on a more intimate level. Almost every technical blog that I read uses a very detached, dry, highly technical language. They seem to take themselves too seriously, it can be amusing at times but then it becomes drab and uninteresting. I understand that the technicality of these posts is inherent in what is being discussed, but I believe stream of consciousness could enhance them greatly.

Practicing Stream of Consciousness:

I believe that there are various types of this narrative process which are expressed through subtleties in the narration. Below are the two main types that I believe exist. Each type has its usefulness and when applied properly will greatly enhance the readers/listeners experience. I go into some examples of each type to help clarify the differences.

Dissociative Stream of Consciousness -

One form occurs when there may or may not have a specific goal in mind and the author shares spontaneous thoughts. For example, while I am writing this blog post and analyzing the subject matter in my head, I am bouncing a small, foam, orange Miller Light basketball on my desk, which I acquired at a bar last year from a beer company’s beer girls. I was at a small wing restaurant drinking beer with co-workers when I received it. I am also listening to a seventies progressive rock band named Gentle Giant, and dreading having to go back through this post and link it up, it’s going to be very tedious. This style is more of a dissociative style, since you are not following a particular mental map of how you arrived at a conclusion.

Associative Stream of Consciousness -

The best way to exercise this form is to pose a question and narrate the thoughts that lead to your answer. Let’s see, what is a good question to illustrate this type. This may not even be valid, because I have to think of something and then make sure that there are enough extraneous processes for us to follow. Okay, I fear it may have to be a bit contrived for learning purposes.

What is your favorite color? Well the societal imposed norm for this question is gender based, females will say pink and males will say blue. So if I don’t say blue am I not a male? What if I am a male and say pink, does that classify me as less of a male? Why the heck is there a perceived answer to this question based on gender? It was probably promulgated by male dominance in society throughout the ages. Maybe it was actually women who promoted the distinction. I know that I have little color matching skills, an thus since I am male I can extrapolate that to all other males, ;) . Is there some kind of predefined spectrum of colors that I can choose, like colors in the human-visible spectrum of light. Well I know my father likes green and green is green with me, but I have been partial to bright blue throughout my life. I have also always liked black, but I’m not sure that black can be an appropriate answer, because by definition it is the absence of all visible colors and white is the presence of visible colors. Can I answer with a color based on an observable object, say the color of a banana? Does the color have to be given in print or computer constructs, CMYK or RGB? Whatever, I’ll go with my gut instinct, the only hex color I know by heart #3366FF.


With the associative type we are following all of our mental paths that lead us to our conclusion. On to the twitter song that brought about this post.

The Twitter Song (in chronological order):

@jamesmarcusbach said:
You know how in old movies everyone wears a tuxedo or smoking jacket, even at home? Copy-editors want all writing to be formal. Screw them!

@seanbiefeld said:
stream of consciousness is the future

@jamesmarcusbach said:
stream of consciousness is the future? As opposed to reflection, analysis, understanding? How easily manipulated we will be!

@seanbiefeld said:
i just find that there are many writers/bloggers out there that take themeselves too seriously

@seanbiefeld said:
…they and write intellectulally stimulating articles that are missing emotional and spiritual stimulation

@seanbiefeld said:
therefore what they write tends to come off as highly technical but not satisfying the needs of the human condition

@jamesmarcusbach said:
Is stream of consciousness the route to emotional and spiritual discourse?

@seanbiefeld said:
wish twitter apps provided spell checking, themeselves = themselves, lol

@seanbiefeld said:
not necessarily the route to such things, more of a display of humanity to the reader

@jamesmarcusbach said:
serious question: do you feel that humanity comes out more in tweets? Or is it the interplay of tweets that does it?

@jamesmarcusbach said:
I find myself really confused. Conversations are sequences, but the sequences are hard to follow in Twitter. Is there a tool?

@seanbiefeld said:
tweets increase the probability of humanity coming out, but the individual must have not hesitations in what they tweet

@seanbiefeld said:
no tool that I’m aware of, disjointed is the norm, the logging aspect of tweets allows for one to piece together sequence

@jamesmarcusbach said:
So, for you, spontaneity is paramount in tweets?

@seanbiefeld said:
spontaneity can bring out humanity, the other part i see in tweets is discussion which can bring enlightenment

@seanbiefeld said:
while stream of consciousness tends to exude spontaneity it can lead to enlightenment

@jamesmarcusbach said:
Disjointed is the norm! Maybe so. I’m a bit worried that’s something a drug dealer would say to a new client.

@seanbiefeld said:
personally i have used twitter so far to increase my understanding of my craft by consuming the thoughts of my peers

@seanbiefeld said:
… and engaging myself in discussion of those thought streams

@jamesmarcusbach said:
I’m very interested in seeing an example of enlightenment by tweet. Then I could truly say that “life is tweet”.

@jamesmarcusbach said:
Twitter is conversation as a box of chocolates. Retweeting is “oooh, try this one!”

@seanbiefeld said:
my proof of personal enlightenment is a tweet session I had with @derickbailey and @bellware http://sbiefeld.com/?p=68

@seanbiefeld said:
it is somewhat recounted by that post but the post cannot encompass the entire discussion

@seanbiefeld said:
there is much promulgation of, lets call it spam, but I am a twitter novice and unsure of exact what retweeting is

@jamesmarcusbach said:
Wow! You are selling me, Sean.

@seanbiefeld RT said:
: @seanbiefeld Wow! You are selling me, Sean. – sarcasm? Electronic human interaction denies us context and inflection

@seanbiefeld said:
thus the downfall of electronic communication, subtleties in voice, facial expression, and body language

@seanbiefeld said:
but without twitter we would never had conversed, like with anything, there are good, bad and ugly

@seanbiefeld said:
i wish there was an app that allowed you to capture meaningful tweets, wait that could be a profitable idea, i claim dibs

@jamesmarcusbach said:
No sarcasm. Absolutely serious. You’re giving me a picture of how philosophy can be practiced on Twitter.

@seanbiefeld said:
I have only been using it for around a week but it seems if you want substantive tweets, limit those you follow

Conclusion:

After re-reading through the song above, I realized that i made a great number of spelling and grammatical errors, yikes, I blame sleep depravity. Twitter is a tool that encourages stream of consciousness narration, whether the users know they are actively participating in this form of narration is another matter. Twitter shines when users start up associative thought streams, which in turn generate discussions among multiple people. When this is not occurring there are a lot of inane dissociative streams, which can be good and bad. This discussion that @jamesmarcusbach and I had, furthers the proof that twitter can provide an informative outlet for those who seek it.


Signing off, seanky, to the g-funk era

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.

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