[ weird things ] | how to get the best of both (programming) worlds with a little c#

how to get the best of both (programming) worlds with a little c#

A little coding fun with hash maps and delegates for trivial parallelization...
i heart coding

And so it’s come to this. Don’t tell me you never thought this would happen. You’re reading a blog by a programmer. Sooner or later, you were going to see some code. It’s not like there weren’t any hints either. In my post about why Weird Things moved to Medium, there was a mention of using object oriented C# to create dynamic widgets for a blog engine. It’s not a really complicated trick requiring lots of advanced code, and that’s exactly why I want to share it. It’s a fun way to apply a strategy pattern in a way that functional programming partisans claim object oriented languages shouldn’t be able to do, and may come in handy for readers who also write code for a living and might want another trick for their toolbox.

First, for those who aren’t quite sure what this who “strategy pattern” thing is, a brief primer. Programmers often use (or at least should use) certain approaches to solving common problems called patterns to speed up their work. One of these patterns revolves around giving the code a hint how a chunk of data should be processed in a given situation while the software is running. Imagine planning your software’s behavior as a chess match. You go in with a basic strategy of how to force your opponent into a checkmate, but you’ll also have backup plans for what to do should your opponent pull off certain menacing moves. What you see on the board will dictate your strategy for the rest of the game.

Sounds pretty simple until you realize that a simple 1 or 0 flag won’t cut it for a lot of possible outcomes in real world code. How do you communicate an elaborate set of conditions to a plastic and metal box? In object oriented programming, we use handlers. You see, object oriented programming, or OOP for short, uses the concept of classes behind everything we do, and a class is a grouping of data and algorithms that define an object. So if you wanted to represent a plane, think of all the things that define a plane (i.e. wings, landing gear, tail) and what a plane can do (like fly, turn, land) and the best way to represent them, you’d make an Airplane class. You can then use this class to create airplane objects, instances of that abstract notion of an airplane as you’ve defined it. A handler in a strategy pattern holds the algorithm into which you’ll pass the data you need to get what you want out of it based on the conditions at your program’s runtime.

Unfortunately, handler objects are kind of messy and in commercial code will require other patterns to properly implement. OOP is great at creating a framework for high level reasoning with complex, organized data sets, but it comes with a lot of overhead that’s required to manage all those objects. And because many of those objects contain not the actual data but pointers to where it lives in memory, failure to handle the objects properly could result in weird side effects as underlying data either unexpectedly changes or fails to change. So the name of the game in taming the OOP beast can be best summed up by these three things: simplicity, simplicity, simplicity. You always have the power to make things complicated and because it’s cool to see a code equivalent of a Rube Goldberg machine work you’ll be temped to try. The charred bones of many coders lie at the entrance of that cave, and you’d be wise not to make the same mistake as them.

And this brings us to what I was doing and why I was doing it. Basically, all I wanted was to have a sidebar with widgets, just like WordPress, and broke them down into two broad types: a widget to showcase posts with the first image in its contents, and a widget that rendered a custom HTML string. By the time they would be seen by a reader, they’d all be rendered as plain old HTML because that’s critically important for basic SEO, using the following MVC .NET Razor models for what I called the Post Ad Box Widget and the Content Widget, respectively…

Please note that the view model for the Content Widget will vary from one widget of this type to another. The widget’s metadata, which we’ll examine in just a bit, will record the name of the view we need to use. This is what I ultimately wanted them to look like fully rendered…

wip screenshot

So where do we get the data for the widgets? We get it from a SQL Server database table that holds some flattened widget metadata. We have a name, an icon font symbol, and the order in which it should appear in the sidebar for the absolute basics, but our main focus will be on the fields holding the pointers and parameters for stored procedures that will gather the data for the widgets’ contents. It’s this data we need to handle and this is how we’ll do it. When we query this metadata table, this is what we see…

db screenshot

All right, so we have a handler for each widget, but that handler is just a string. What are we supposed to do with that? Well, that string goes into the internal mapping of a widget handler object like so…

Here’s what happened. In C# there is a Dictionary class, which is basically just an implementation of a hash map, a basic key/value store with one major limitation. Since C# is statically typed, I need to specify what sort of data will go into this hash map ahead of time. So my key is a string, and my value is the seemingly weird looking Action object with its own set of odd parameters, one of which is a widget and the other is something called a Row. What are those?

Well, the Action class is a delegate, a pointer to a piece of functionality that lets me pass functions as first class citizens and invoke them when I want, just like in a functional language. Ok, ok, maybe not just like in a functional language because I’m bound by the number of arguments and their types unlike in say, JavaScript where I can assign any old function to any old key and invoke it with whatever number of parameters I want. However, I could argue that standardizing your handling methods in certain applications is a good practice from a conceptual standpoint.

This brings us to the Rows object type. This is a class that comes from a port of this library I wrote and used to formalize my database transactions for dealing with complex cell data, and testing in enterprise apps. Internally, a row is exactly what it sounds like, a hash map of a database row returned by a query. Rows is merely a collection of these has maps. So we basically get a handler name, rows of data for the handler to process, retrieve a pointer to a method we set up to create either a model for an HTML string in a view we specified for the widget, or populate a collection of post ad boxes, then call this method and pass the prerequisite data to it. Easy!

And now, for the final touch. Each widget exists as its own thing within the context of a sidebar. It has its own content, its own model, and its own data set, which we get by executing the dynamic SQL in its metadata. This means that they’re trivially parallelizeable and we could retrieve them faster side by side than one after the other since they don’t share any data with each other and we don’t have to manage the pointers for this data when we send them into our handler. This is why in the method with which I load the widgets looks like this…

Let’s break it down. Using helpers from my QueryLogic library, I get all the required data, load each widget’s logic for executing its SQL, execute it and capture the data in a useful, disconnected form, then send it and the widget into my handler to finish the setup. I add this functionality into a collection of delegates, then run them in parallel. And when the process is done, out come fully populated widgets ready to display their data. All I need to do is call this method from a part of the application where I’ll pass my models into the views and render the HTML.

And there you have it, easy, parallelized metadata-driven widget handling using an OO language able to mock the ease of functional monads and the ability to treat them as first class citizens.

# tech // programming / web design / web development


  Show Comments