Separation of Concerns – A real world lesson

July 13, 2012 Leave a comment

About a year ago I was tasked with creating a simple module for my company that could manage notes for the various system “entities” — things like invoices and customers that might benefit by having explanations or instructions. In essence a user could select one of these objects and choose to view or edit any existing notes in a container/widget format (a repeater with user controls for each note) with the ability to create new notes as well. The intention was to provide instant information and feedback across all our various applications and web sites for all permitted users to consume, including our employees as well as clients. This module was completed and implemented and has greatly improved communication and visibility in key areas of our operations.

Very recently another project has arisen that involved messages. Our company has found itself in the position of needing a task-based messaging system that would be used internally as a sort of workflow communication system between departments. In a nutshell it would allow a task with instructional message and association to a system entity (again, an invoice or customer) to be assigned to a person and then sent out for that person to take action upon and, when completed, close the task. At the UI level there would be host client applications that would expose some widget or “message center” where the user could be alerted to open tasks and within a single click quickly be navigated to the right place to perform the necessary actions. Of course this would involve a queue, periodic pop-up alerts and a centralized library between the multiple UI clients and the persistence layer.

In round-table discussion it was suggested that maybe we could leverage this into the existing notes functionality. Now, while I may have described these two systems in a way that that makes them sound quite different, consider why it might on the surface seem appealing to blend them. First, we have an existing and functional system that already performs a simple version of creating and emitting a message. Moreover, the notes module relates its content to all of the entities considered by this new task notification system. It is natural to think the two could be married somehow. They shouldn’t though. This is an excellent example of Separation of Concerns – a concept often relating to classes in object-oriented design. Loosely interpreted, SoC suggests that one should avoid building complex and loosely-interdependent functionalities into a single class or functional set of classes. Instead it is better to break out these functionalities into constituent parts and allow them to interact as distinct units. In other words, the fact that notes and notifications share some common threads is not compelling enough to consider merging them.

The thing is, I remembered at the time that the notes system was first discussed there was minor awareness that a task notification system could be on the horizon. At the time I recognized the similarities and lobbied to build a more complex system that would be flexible and extensible enough to not only take care of the immediate notes need but also get a two-for-one by laying the foundation for the eventual notification system. Sure, it would mean more development time but could save us time later. Ultimately the decision was to go with the simple, closed system that did only what was required for notes. In hindsight this was the right move because we wound up with a quickly developed system that did exactly what we needed and also allowed for time to better flesh out the details of exactly what the use cases are for the notification system (recall it was all conceptual at that time, not issue-driven).

The notification project has gained steam only because of a small subset of current needs. There are however many conceptual use case variations I can see that are almost certainly going to arise once this is implemented — things such as multiple co-recipients, passive notifications (i.e. no task, just information), chained approval and automated alerts. This is the kind of software solution where a manager uses it and then thinks of three other ways it could solve other problems. Hell, I’ve already come up with a few for our department and its not even made yet. So I see a small amount of irony in that we are yet again faced with the question of staying tight to the immediate need or put in hooks for eventual permutations. And yet again I am lobbying to consider the bigger picture.

Only this time I think I’m right, and here’s why.

The notifications system is going to require some sense of a “model” that defines the rules or configuration of the process from end to end. This model will be used as a basis for a designer that can be used to essentially build an instance of the model. That instance is what becomes persisted and is sent to the individual user queues, encoded with all the information required to perform the necessary actions. When dealing with such a model-based system there is a distinct advantage to using interfaces to define the members (methods and properties) of the model’s components. Interfaces allow you to build the system independent of concrete classes, thus decoupling the conceptual aspect of the system from the implementation.

In other words, let’s say a notification has a property called ‘Sender’ of type Person — this is the person who creates the notification. The type Person should have a name, maybe a user ID and let’s throw in a title for the sake of diligence. All these values can be used by the presentation layer to assist in identifying the sender to the recipient. Works for our narrowest use case. Now, let’s say the very next use case to come after release is that we have a database job send alerts out to multiple recipients. Is a DTS job a person? No. Can we cram it into that box? Sure! The name can be, um, ‘System Process’ (hopefully we did not break it out into first and last name properties). UserID? Heck, let’s make it zero or a random GUID if you prefer, but either way it does not reflect the same ID system that internal users are identified by. Great! What’s next… Title. Um… oh, forget it! This is just terrible design and painful to watch unfold. Consider that we would also need to support a collection of recipients as well. Refactoring that would be a bear.

In my opinion the best way to address these almost certain coming issues is to plan for them now. Having a Sender be an IActor interface allows for inherent multiplicity. Instead of Name (or FirstName, LastName) we could have a generic property called DisplayName. UserID can extend to ActorID and we only need a mapping table to assist in bringing together disparate ID systems. Now we can still have a Person class used when it is a real employee, but we can also have a DtsJob class as well, and they can both work equally as well because they only need to implement IActor and satisfy the required members of that interface’s contract. Taking this a step further a notification’s sender and recipient can be defined as IActor objects, so the concrete types become irrelevant to the conceptual requirement that something initiates the notification and something receives it or is assigned to it. Heck, now we can have mutiple IActor recipients as a collection with virtually no effort and we can support a few more use case scenarios.

Oh, and by the way, notes can be retro-fitted to this model if the need ever arose. The IActor recipient could be the notes repository which programmatically would process the note generation. See, the notes system is just a specialized case of the larger notification model. It made no sense to build notes with this interface system because of time constraints but also there was only one known implementation of the model. Now that we have two and many more coming it is imperative that we switch to an abstract system of interfaces because otherwise any new requirements will likely incur significant refactoring or code duplicate — and those are resource costs that only get higher with each revision.

ASP.NET MVC & VB – Where are the examples

July 3, 2012 3 comments

I finally got around to teaching myself ASP.NET MVC (using 4.0 / razor / Entity Framework 4.1 / VS 2012 RC) and found myself in a bit of a bind today. Despite the fact that I am a VB.NET MVP I have been working in C# just so I can keep my chops up with the language. I never get the chance at work to use C# so I force myself to do all personal projects in C#. The short of it is that I love MVC 4 and especially the razor syntax. Very powerful, very flexible. I have been catching on quickly enough and have found ample examples on the web to do what I need, which is very comforting to know that there is a huge amount of support for what is still not the mainstream web technology for MS (yet!).

And then I started up a test project at work to show some colleagues. It was in VB.

The experience could not have been more night and day. Examples of razor code segments in VB on the Googlewebs is like finding a needle in a haystack. To clarify, I was searching for specific answers — if I just did a general search like “MVC4 VB.NET” then I would find basic tutorials easy enough. But I’m not looking for encompassing tutorials. I’ve already started getting into the details of implementation so I need to solve specific issues. Unfortunately that sort of content appears to be blanketly in C# and I have to say that this is disheartening to a professed VB-enthusiast. For instance, I was trying to find the syntax for declaring a WebGrid HTML helper in razor (recall that I am new to MVC) so whatever I had used back a few weeks ago was half-fading from memory. Not a problem though – I’ll just find a quick sample from some forum thread or article just to get the ball rolling – a mix of search terms that included “MVC3”, “MVC4”, “VB.NET”, “webgrid” and “razor” I eventually had to give up around my twelfth result and translate a C# example instead. Honestly, I would have done this much earlier but I was just amazed at the lack of VB coverage. I pride myself on finding things fast through search – even with technologies I’ve never even seen before. This however was debasing. (For the record is a good reference that has ample dual language examples.)

So what’s with the near absence of VB code samples anywhere – in MS documentation or in developer forums. I can only conclude that ASP.NET MVC 3/4 is not a technology widely adopted by VB.NET developers. I know there are plenty of VB.NET developers out there but I suspect that the perception that VB’ers are mainly stuck on Windows client applications (Winforms mostly) may have some truth to it. Windows development does constitute about 90% of the content in the MSDN Visual Basic General forum forum. It’s what I have done primarily for the last seven years. The VB language team at Microsoft, through the effort of achieving “language parity”, has done a stellar job of elevating the language to the position of true equal to C# in terms of power and flexibility (with a very few exceptions) with the onset of .NET 4.5. Its detractors have little more than perception and job market opportunities to point to for C# superiority. Unfortunately for VB those things count for a lot. Too bad though. Vb.NET is a great language that, together with the power of the Visual Studio IDE, can offer blinding fast speed for the experienced developer as well as clear and simple readability. As evidence I offer case-insensitivity, auto-completion, code prettification and the lack of superfluous curly braces.

One last gripe with my brief exploration of MVC 4 with VB.NET. When trying to create an out of the box “basic” solution on my home machine (VS 2012 RC) I received the following error from the IDE at the tail end of generating the solution:

MVC 4 Error

I believe this may be behind my inability to access the WebGrid class in code on the razor form – thank goodness my real project is done in C#. I’ll have to assume this is some issue with VS 2012 RC (since the project I did at work was with VS 2010 SP1) but this whole business with VB has got me paranoid now. The second time I started a VB MVC 4 project at work using VS 2010 I noticed another issue. With VB defaults set to Option Strict On (which is recommended) some of the auto-generated code fails to compile because of loose casting. My guess is that the generation code was written for C# first and then ported to VB CodeDOM parser without a proper review of project context. This just suggests to me that VB was an afterthought. Kinda pisses me off, really.

Categories: MVC, Uncategorized, Visual Basic Tags: , ,

New Microsoft Surface tablet

June 19, 2012 Leave a comment

Microsoft Surface tablet

I just got a look at the new tablet that Microsoft announced officially today and I am very impressed. Design-wise they seem to have knocked it out of the park — and they really needed to do that with the ultra strong competitor that Apple has in the iPad. So much is riding on this release that was already revolutionary for the shake up of its core Windows operating system, but to introduce an even more radical move in terms of full hardware integration is like starting a new book let alone chapter.

And how did they keep this so secret for so long?

Really though, I am equally impressed with the marketing put into this unveiling website. The site itself is edgy with a touch of hipster – evidenced by the adjectives used in the spec sheet categories – and the video is like nothing I’ve seen from Microsoft before. It tells a compelling product story through powerful imagery. The message I get from the video is a product that defies rules (laws of physics, gravity), offers inexplicable attraction (many odd magnetism shorts), and stands up (literally, once) to the unyielding (hardened steel, stone). I’ve never been stirred by Microsoft’s past marketing attempts (i.e. series of commercials for Vista or Windows 7), and even the Microsoft Stores (I visited the one at Tyson’s Corner outside DC) have a safe if not sterile feel to them. However, if this video is any indication of what MS has in store for the marketing barrage coming over the next six months leading up to Christmas then they may just define themselves as distinct from Apple. That is something they desperately need to do since since, like Apple, they are going with tight vertical integration, a juried app approval process an no side-loading (except for pricey enterprise licenses).

Microsoft is obviously investing heavily into the light consumer market with the stress on the RT, apps and touch devices. It’s hard to comprehend that they are also trying to release to Enterprise concurrently. It is clear though that Enterprise was not expected to pull this new OS into success (I suspect Win9 will have to take up that mantle) so it is natural to assume that the growing market of recreational users is the one to stake a claim in right now. Truly enterpise is not going anywhere too soon away from Microsoft.

As nice as the new Surface is I will definitely wait… mainly because I am not currently in need of another machine right now and partly because I like to gauge market response before I buy. I’ve been fooling around with the RC version of Windows 8 (running on Oracle Virtual Box on my laptop) but find it tough to love without the touch capability. Again, I have a hard time seeing enterpise wanting to deal with widespread confusion among office workers trying to grapple with the schizophrenic dual-OS identity. People in my office have a hard enough time understanding basic operations in Windows 7. As a developer it is mostly useless since I can only use desktop mode to code with Visual Studio.

Anyhow, I wish Microsoft the best with this venture. The tech world needs competition to impel progress.

Categories: Uncategorized

Why the default form instance does more harm than good

February 2, 2012 1 comment

First things first. The default form instance is a feature of VB.NET for versions 2.0 and up, applicable only to WinForms projects, and provides a forms management functionality that is in keeping with the code “feel” of VB6, the predecessor of VB.NET. Functionally, this feature allows for the programmer to use the name of a form to directly reference instance members on that form’s class (i.e. controls, properties). This feature made sense when working with forms in VB6

This of course flies in the face of object oriented design (and the .NET framework’s design patterns for that matter) which leaves the onus on the developer to be in control of his own object instances. In essence it introduces a non-OO principle into an OO language — and this is the starting point of my argument that in net sum, this is a harmful feature… at least in the way it is presented in the default WinForms Visual Studio template (I’ll clarify that later).
Read more…

Shared events and memory leaks

July 26, 2011 Leave a comment

I had something happen to an application I recently had been refactoring that resulted in a very serious memory leak. I work mostly with single-thread, data-driven applications and so rarely create the opportunity to fall into such traps given that the .NET framework manages garbage collection so well… actually, given that the framework manages garbage collection so well when you don’t try to get too tricky. In fact, I can’t recall even finding a memory leak in any previous applications in the past six years — though it’s plausible that I just never knew of one if it did exist. But this one was very obvious and the solution pointed to an almost unforgivable coding sin that I definitely should have caught. So if you ever have found yourself creating and using shared (static in C#) events then you may want to read on for a cautionary tale. Read more…

Categories: .NET, Application Design

When to use custom exceptions

June 12, 2011 Leave a comment

Have you ever found yourself in a situation where there seems to be no exception type that is a fit for the exception you want to throw? In smaller, stand-alone projects it is easy to just ignore the problem and use a plain old, generic Exception. After all, you’re the only one who’s going to see it, right? For larger, more complex projects or for class libraries that will be consumed by other assemblies that may not be written by you it can be useful or necessary to throw exceptions that have targeted meaning. The solution is to make your own, and the .NET framework has provided us the means. Read more…

Parsing large numbers to words (english)

May 8, 2011 1 comment

I’ve occasionally seen a request for this functionality pop up in the forums over the years. A developer is given the task to write out in words a number the way it may be spoken by a person. Actually, a more common use for this functionality is with bank checks where we write out the amount in words. So $1,234.56 would be written out as One Thousand Two Hundred Thirty Four Dollars and Fifty Six Cents. It’s amusing that the people who search for this functionality in code are surprised and even annoyed that the .NET framework does not have this built in… as if the framework does not have enough stuff already, right? A while back I came up with a solution for this based on a forum request (see the revised code at the bottom). I thought I would share this here again as a separate blog post. Actually, I decided to upgrade the code a tad just for the sake of never leaving good enough alone 😉
Read more…