Posts Tagged “design”


Code Proxies and why You should care


Head first

Instead of going about what a proxy is, I’ll first describe usage scenario or two to make the explanation more concrete.

non functional aspects aka AOP

Consider any “service class” you might have written, lets assume it has a well defined public API – probably using an interface. Now lets say that you want to start logging the amount of time each of these methods of the public API take. A common solution would look like that:

This violates a few engineering principles (repeated code, magic strings, etc.), makes debugging annoying, clutter the view, and overall not-fun

Meanwhile in Dynamicland

With the ability to replace a method in runtime, a developer in Ruby/Javascript/et-el can easily patch these methods and add the cross cutting concern in run-time.

Back to c#

The concept of AOP is not unfamiliar to c# developers. While some solutions use compile-time code weaving (a-la postsharp) and other techniques, the more common one (which is in use with most IoC containers, as NHiberate and other frameworks) is to use a DynamicProxy. Meaning that in runtime, user code will ask a factory (or IoC) for an object of type X, and will get and object of type Y, where Y is subtype of X, and was dynamically generated in runtime to override X’s public methods, and apply the aspect there. Not unlike any other Wrapper / Decorator class, except for the fact that no-one needs to manually writing code for the wrappers, but instead write the aspect once, and apply it for many types/methods


NHibernate, to allow lazy loading of properties, uses a dynamic proxy when creating instances of objects that were read from the DB, decorating public virtual mapped getters with a “Load the content when first accessed” concern. this is totally transparent to the user. The fact the NH uses (at least by default) runtime dynamic proxies, and that (at least by default) it works with class-based pocos for entities (and not interfaces) is why the docs tell you to use virtual properties if you want Lazy Loading.

And wouldn’t it be nice when writing GUI apps to have PropertyChanged events be wired automatically?

Proxying interfaces

Here is where it is getting even more interesting IMO

The proxying technique can be actually applied to interfaces, not only virtual classes. Meaning that you can actually generate code in runtime to implement certain contracts without having actual implementation of those interfaces in your user code at all!

A fine example of that approach is in Castle’s DictionaryAdapterFactory (see essence, a dynamic proxy is created in runtime to implement a given interface’s properties, allowing typed read/write access to untyped <string,object> datastores (Session, Cache, ViewBag, you name it)

Another example where I used that technique in the past – in a RPC client/server scenario, you need to keep a few things in sync: The server’s endpoints (http in my scenario), the method signatures on both the server and client, and more.The system was using an interface (with a couple of attributes for metadata e.g. URL parts) to declare the servers’ API. The server holds implementations for the interface and in runtime it reflects over the interface to build the endpoints (think MVC routes), while the client generates dynamic proxies from the interfaces that call out to the server in a transparent way. This way we avoided the need to constantly regenerate client proxies (lots of repetitive code and clutter in the codebase, tax on source control and process, and difficult to manipulate and extend), as well as being refactoring-friendly (because it is all code, and magic-strings such as url prefixes etc are defined in exactly one place).

Where is the code?

Sorry, running out of time here. I will post an example implementation for a dynamic proxy in c# in a follow-up post.

From MongoDB to Azure Storage


My blog has been running happily for some time on a MongoDB storage. It used to be hosted on a VM in a really awesome company, where I had both the application and the DB sharing a 2GB VPS, and it worked pretty well.

At some point I moved the app to AppHarbor (which runs in AWS) and I moved the data to MongoLab (which is also on AWS). Both are really great services.

Before it was running on MongoDB, it used to be running on RDBMS (via NHibernate OR/M) and I remember the exercise of translating the Data Access calls from RDMBS to a Document store as fun. Sure, a blog is a very simplistic specimen but even at that level you get to think about modeling approaches (would comments go on separate collection or as subdocuments? how to deal with comment-count? and what about tag clouds? what about pending comments that are suspected to be spam?)

I am now going to repeat that exercise with Azure Storage.

The interesting data API requirements are:

Given the rich featureset of MongoDB, I was able to use secondary indexes, sub-documents, atomic document updates and (for 4, 6 and 8) simple mapReduce calls. The only de-normalization was done with CommentsCount field on post, which is atomically updated every time a comment is added or removed from the post, so the system stayed fully consistent all the time. The queries that required mapReduce (which could get pricy on larger data-sets, and annoying even on small ones) where actually prone to aggressive caching, so no big pain there.

I will be exploring (in upcoming posts, its 2am now and the baby just woke up) what it takes to get the same spec implemented using Azure Storage options – mostly Table Storage and Blog Storage.*

How do you pass values from Controller to View with MVC3


The scenario: Given a blog application, with the following layoutimage

with two possible usages – a post page: imageand a homepage:image

Let’s define the view model:

  string Title
  string Body

  PostData Post; 

  PostData[] Posts

  Tuple&lt;string, int&gt;[] Archive
  Tuple&lt;string, int&gt;[] TagCloud
  string[] Similar

The views:

How data moves around:

Given that I want typed access to the view parameters in the view (for the sake of intellisense and refactorings), how would I model and pass the data around?

I’ve pseudo-code-grade written two options: the first is to use inheritence in the view model to achieve type-ness, on the expense of flexibility (composition is difficult with class hierarchy, and you need to be aware of and grab the viewModel instance in various places). The second is flexible (use the ViewData dictionary) but getting type-ness is cumbersome and partial (strings scattered around, casting needed etc.)

see if the gist widget does not load in-place I do have a solution that works for me With the many years that I’ve been writing complex web apps using various ASP.NET frameworks and almost always with c# based, static-typed view engines, I have a solution that works very nicely for me. But I want to be aware of the MVC3 canonical / textbox way So for all you MVC3 ninja’s out there – please describe your way of doing it.

I will describe my approach in an upcoming post and I’d appreciate any input on it

Object Oriented Mess


Following the “why I do not like (certain widely used paradigms in the ) Ruby (community), I would like to bring yet another specimen representing the same problem.

DISCLAIMER: I’m writing this on a 10hour flight, that got extended by 3 more hours of waiting at the gate because apparently it take 3 hours to fix “a software problem with the passengers cabin lighting system”. I’m not joking you.I’m tired, pissed off, and terribly missing my family whom I did not see for almost three weeks. Hence – I might get distracted, digress here and there, and sound a bit impatient at times. Leave now if you possess a soft soul (but do click on the flashy ads on the sidebar before you do that).This is also going to be a much longer post than my usual ones I’ve had for the last two years +. I hope to make that happen more often, as I have some more free time now that I left Delver. More on this on a (near) future post.

It’s not you, it’s all of you Since I’ve been doing mostly rails and ruby lately, my examples would probably have a ruby color spread all over then. Don’t get me wrong though, this is not going to be an anti-Ruby rant. People certainly are doing the exact same thing in the Java and .NET worlds, especially people who have “read” Evans book but never really groked it. They are 100% certain that OOP is about “making your objects smart” and forgetting what an object in that sense should actually represent (hint – encapsulate business goals and processes in well defined boundaries). Perhaps the way OOP is taught universities is to blame (Animal Kingdom? really?) as they concentrate on the technicalities of Is-A vs Has-A and not on how to approach modeling in the first place. In order to make things worse, I will use the terms ‘class’, ‘object’, ‘instance’ and ‘whuuzaa’ interchangeably.

So, where was I? ah – another concrete example for bad design caused by oversimplified OOP implementations


(or .family_name, whateva)

OOM – Object Oriented Mess So you have your domain objects (or Models if you’ve never heard about other frameworks but Rails) and since you did not read Evans book you think that you should “encapsulate their logic” and by that you refer to the .url property. Cuz the User class (/object/model/entity/whuuzaa) represents a real user and that is the model for the user. So in your application (say a website) you’d want to include urls to the user’s profile page, so you’d be giving your view engine (template, jsp, view script, xib, you-get-te-point) a bunch of Users, and then you’d call .url on each of them – and voila – the “generate user profile url” problem got completely abstracted !. You’d even have a IHaveUrl interface (or UrlContainer if you’re from java, or a creepy act_as_urlifiable Module if you’re from … enough with that) and then you can enjoy the fun of calling .url on anything.IT WOULD JUST WORK.

Until it doesn’t.

One model to rule them all Is there really a single way to represent a User in your system? I bet that a User instance used to populate the User Profile page is quite different and a lot richer than a User instance that would be used in a recurring list of the User Profile’s friends list, which would require perhaps only name, image, and guess what – url !

What’s that thing doing here? Within a recommendation-engine service, that runs complex calculations on the users and their related activities on the site to get relevance scores, the url does not mean anything. If the User Entity is used there then the .url method is just hanging there meaning nothing, contributing nothing while perhaps adding complexity and confusion

Oops, sorry, I didn’t mean to say that And to make it worse – on other parts of the site (think an admin back-end) a user’s url can mean a completely different thing – like a url to the whereabout of the user’s administration page, or whatnot.

Hey there are other people here Put the url example aside, if you do a feature, which is relevant for a certain part of the application, yet you choose to expose your code to central part of the system (such as a central User class), then you end up stepping on other people’s toes. And they most certainly will step on yours. At some point in the future some bugs in your feature will creep in, and you’d have hard time locking the problem down, before noticing that someone else used the code you exposed on that entity for the sole purpose of your feature, for a whole different thing, giving that code a different meaning, which inevitably clashed with yours.

So what would YOU do Ken? Encapsulating features in their own set of classes would be the way to go. The surface of the system that need to be aware of a feature should be kept to minimum.

I think that it would be a safe bet to say that the process of generating a profile page url for a given user (or any other ‘thing’ in the system) should live within the boundary of the presentation code, probably as a helper or a static method (don’t get me started on the never-ending testability argument – that’s a whole different post. Just make your code work already and stop arguing about testability. already !) You might want to add some syntactic sugar there to get the .url thing working (like a c# extension method or a Ruby module) but I’d avoid even that. It is good avoid a code that might have dual meanings. I’d take <%= Urls.ProfilePage(name, id)%> (maybe with a couple of overloads) over <%= user.url %> any day of the week. Especially on Fridays when I don’t have time for surprise-bugs-oh-crap-my-weekend-is-going-to-be-short-again.

You’re the best reader in the world Btw, if you got to this point without either getting bored or pissed at me, then hurray to you. You are either a good friend, totally drunk, or both.

Follow @kenegozi