Overview

Cloudflare R2 object storage hosts the video files directly and serves them free of egress fees; the thumbnail is a plain static image served from the site itself and wired in as the HTML5 <video> element’s poster. There is no Cloudflare Stream or Images product involved.

Static sites (plain HTML, no backend) can’t host large video files economically on normal web hosting. FTP/shared hosting plans are small and often meter bandwidth. The fix used here:

  1. Upload the raw MP4 files to a Cloudflare R2 bucket, made public, instead of the site’s own host.
  2. Reference R2’s public URL directly in a native HTML5 <video> tag on the page.
  3. Give that <video> tag a poster image. A plain static JPG stored alongside the site’s own assets, so a thumbnail shows before playback starts.

No Cloudflare Stream, Cloudflare Images, or any transcoding/thumbnail-generation service is used. R2 is pure object storage (S3-compatible); the browser’s native video player does all the playback work, and the thumbnail is just a picture someone exported from the video and uploaded as a normal image.

Cloudflare R2 setup

One-off, done in the Cloudflare dashboard:

  1. Sign in at dash.cloudflare.com (a free account is enough. R2 doesn’t require an active domain on Cloudflare).
  2. Go to R2 Object Storage → Create bucket. Give it a name (e.g. my-site-videos); the default region/storage class is fine for this use case.
  3. Open the bucket → Settings → Public access → enable R2.dev subdomain access. This is the switch that matters: without it, objects are private and the URLs below return 401/403.
  4. Cloudflare then shows a public base URL in the form https://pub-<hash&gt;.r2.dev. That hash is unique per bucket. Any object uploaded to the bucket is reachable at https://pub-<hash&gt;.r2.dev/<object-key>.

Free tier limits: 10 GB storage, 10 million Class A (write) and 10 million Class B (read) operations per month, and zero egress fees z. The normal cost that kills “just host it on S3” for video doesn’t apply here. For a personal/portfolio site with a modest number of video clips this comfortably fits the free tier.

Optional, for production use: map a custom (sub)domain to the bucket instead of using the r2.dev subdomain — R2 → bucket → Settings → Custom Domains → Connect Domain. This needs the zone to be on Cloudflare but gives a branded URL (e.g. videos.example.com/clip.mp4) and lets you put caching rules in front of it.

Uploading and linking a video

  1. In the bucket, click Upload and drag in the MP4 file (any browser-playable codec works. H.264/AAC MP4 is the safest default for broad compatibility).
  2. The object’s key is its filename. The public URL is simply the base URL from setup plus the (percent-encoded) filename:
     https://pub-f2fbf596a6394cfdbbd77ce54c203071.r2.dev/My%20Video.mp4
  • Spaces and other special characters in the filename must be percent-encoded in the URL (e.g. My Video.mp4 → My%20Video.mp4). Renaming files to use hyphens or underscores before upload avoids having to do this by hand.
  • That URL is a plain, directly-playable video resource. Paste it into a <video><source> tag, an <a href> download link, or fetch it from JavaScript. No signing, tokens or API calls are needed because the bucket is public.

Embedding the video with a thumbnail poster

The HTML is a native <video> element. A wrapper <div> with padding-based aspect-ratio sizing keeps it responsive (this predates widespread use of the CSS aspect-ratio property, which would be the cleaner way to write new code today):

<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;">
<video
playsinline
controls
poster="assets/images/thumbnails/my-clip.jpg"
style="position:absolute;top:0;left:0;width:100%;height:100%;">
<source
src="https://pub-f2fbf596a6394cfdbbd77ce54c203071.r2.dev/My%20Video.mp4"
type="video/mp4">
</video>
</div>

Key points:

  • padding-bottom:56.25% is the aspect-ratio trick for 16:9 video (56.25% = 9/16). Change this percentage to match the clip’s actual aspect ratio.
  • poster is the attribute that shows the thumbnail before the user presses play. It’s a standard HTML5 <video> attribute, not anything Cloudflare-specific. The browser swaps it out for the first video frame once playback starts.
  • src is the R2 public URL from the previous section.
  • playsinline stops the video taking over the full screen on iOS Safari when played.
  • No JavaScript is required for this to work; a JS player library (e.g. Plyr can be layered on top for consistent custom controls, but it’s optional.

Thumbnails: how they’re actually produced

Worth flagging clearly since it’s easy to assume Cloudflare generates these automatically. It doesn’t, in this setup. The thumbnail is just a JPG:

  1. Export a single frame from the video (a screenshot at a good moment, or a frame pulled with a tool like ffmpeg: ffmpeg -i input.mp4 -ss 00:00:05 -vframes 1 thumb.jpg).
  2. Save it into the site’s own static assets (e.g. assets/images/thumbnails/my-clip.jpg). It’s deployed with the rest of the site, not uploaded to R2.
  3. Point the <video> tag’s poster attribute at that local path, as shown above.

So there are two separate storage locations in play: the (large) video file lives in R2, and the (small) thumbnail image lives with the rest of the site’s static assets on ordinary web hosting. If a clip has no thumbnail prepared, simply omit the poster attribute. The browser then shows a blank/black frame until playback starts, which is why it’s worth taking two minutes to grab a frame for every video added.

If you want Cloudflare itself to generate thumbnails automatically (rather than exporting a frame by hand), that requires the separate Cloudflare Stream product instead of R2. Stream transcodes uploaded video and exposes a https://videodelivery.net/<uid>/thumbnails/thumbnail.jpg endpoint out of the box, at a usage-based cost per minute stored/streamed. That trade-off (manual thumbnail + free R2 storage vs. automatic thumbnail + paid Stream) is worth deciding deliberately rather than assuming one implies the other.

Why this approach? Cost, limits and alternatives

 R2 (this technique)Cloudflare StreamYouTube/Vimeo embed
Storage costFree up to 10 GB, then ~$0.015/GB-monthUsage-based, per minute storedFree
Egress/bandwidth costFree (no egress fees)Usage-based, per minute streamedFree
ThumbnailManual (export a frame yourself)AutomaticAutomatic
Adaptive bitrate / transcodingNone — one file, one qualityYesYes
Branding / adsNoneNonePlatform branding, possible ads (YouTube)
Setup complexityLow (one bucket, plain URLs)Low-medium (upload API, player embed)Lowest (paste an iframe)

Imagine messaging systems as the backstage crew of the IT world, the unsung heroes facilitating a frenzied exchange of data between apps and services. They’re like the postal service of the digital realm, ensuring your messages get to the right recipient. In this mildly serious showdown, I’m pitting Apache Kafka and RabbitMQ, the dynamic duo of messaging systems, against each other. They’re like the Batman and Robin of IT, each with their unique style and capabilities.

In the Left Corner – RabbitMQ

RabbitMQ struts in as the multi-purpose message broker, with more protocols than a Swiss Army knife. It’s like a chameleon, adapting to flexible messaging patterns and complex routing logic. It’s the “Mr. Nice Guy” of messaging, making life easy for consumers.

In the Right Corner – Kafka

Kafka, on the other hand, is the rockstar of distributed event streaming. It thrives in high-velocity, high-volume data streams, handling them like a pro. It’s your go-to choice for real-time data pipelines and stream processing. Kafka’s motto is “Keep it simple, stupid!”

Round 1: Complexity

RabbitMQ follows the “complex broker, simple consumer” approach, putting most of the heavy lifting on the broker’s shoulders. Kafka, in contrast, prefers the “simple broker, complex consumer” model, where consumers need to put on their thinking caps.

Round 2: Scalability

Both are tough nuts when it comes to resilience and availability, but Kafka is the heavyweight champion of hyper-scale scenarios. It can handle petabytes of data and trillions of messages daily, spread across hundreds, or even thousands of brokers. RabbitMQ does its best but can’t quite match that superhuman strength.

Round 3: Language Variety

If you want to talk in different languages (Java, Go, Python, PHP, you name it, matey), both Kafka and RabbitMQ have a variety of dialects. Kafka, though, has a bigger fan club and more linguistic diversity.

Round 4: Integration

Kafka plays well with others, offering a broader range of integrations. It’s like the popular kid who knows everyone at the party. RabbitMQ has its friends, mostly in the database and plugin world.

What is Apache Kafka?

Apache Kafka is the caffeine-fuelled, open-source event streaming platform that started at LinkedIn. It’s like The Flash, sprinting through high-velocity data streams. Think of it as the party planner for real-time data pipelines, microservices, and more.

What is RabbitMQ?

RabbitMQ is the multilingual, multi-protocol message broker that can chat with anyone. Initially, a brainchild of Rabbit Technologies Ltd, it’s now part of VMware. RabbitMQ excels at message-driven communication in distributed systems and is your best friend when it comes to flexible messaging patterns.

The Architectural Face-Off

Kafka’s Lair

Kafka rocks three main elements: producers, consumers, and brokers. Producers toss messages to brokers, while consumers snatch data from these brokers in a pub/sub dance. The secret sauce lies in Kafka’s partitions. They make Kafka superhuman with fault tolerance, scalability, and parallelism.

RabbitMQ’s Realm

RabbitMQ’s world revolves around publishers, consumers, and message brokers. Producers send messages to exchanges, which then sort them into queues using bindings. Finally, the brokers serve the messages to eager consumers. It’s like a busy train station where messages are passengers and exchanges are train schedules.

The Showdown Continues: Features

How do Kafka and RabbitMQ fare in the features department?

Messaging Capabilities

Kafka has its custom binary protocol over TCP, while RabbitMQ prefers the AMQP 0-9-1 protocol. Both support various data formats, message ordering, and message replay. Kafka even offers exactly-once semantics, which RabbitMQ lacks.

Data Structure and Storage

Kafka keeps data in topics and offers long-term persistence options. RabbitMQ stores data in queues and streams and provides the possibility for long-term persistence via streams. Kafka’s storage is like a big library, while RabbitMQ’s is more like a revolving door.

Scalability, Performance, Reliability

Kafka is the speed demon, handling millions of messages per second with low latency. It’s your pick for hyper-scale scenarios. RabbitMQ is no slouch, but it may need more players to achieve the same throughput. Kafka’s the Ferrari, while RabbitMQ is the reliable estate car.

Developer Experience and Ecosystem

Kafka’s got a massive community and a treasure trove of resources. RabbitMQ’s community is large but doesn’t shout about it. Both offer a range of clients, deployment options, and command-line tools.

Ecosystem

Kafka wins the ecosystem battle with a bucket load of integrations, connectors, and built-in stream processing via Kafka Streams. RabbitMQ has fewer friends but can still hold its own.

Total Cost of Ownership

Self-managing Kafka can be expensive, especially at scale. RabbitMQ is more budget-friendly but might require additional components for stream processing.

So what do I think?

In the epic battle of Kafka vs. RabbitMQ, the winner depends , as always, on your specific needs. Kafka is your superhero for high-velocity, high-volume data streams, while RabbitMQ is the versatile sidekick for flexible messaging patterns. Make your choice wisely, and may your async adventures be legendary.

And lo and behold, I have opted for RabbitMQ for my latest contrivance, by the way!

Why does PHP refuse to kick the bucket, you ask? Even those clever clogs who can juggle more web stacks than a circus performer often opt for PHP. Why, you wonder? Well, because it’s the ‘Easy Peasy Hypertext Processor’!

When it comes to server-side rendering, PHP makes it so straightforward that even your Nan can do it – and she’s still struggling with the TV remote. Modern Frameworks? PHP’s got ’em, in flavours like MVC, REST, and even micro-frameworks for those who think the heavyweight contenders are just too chubby. And let’s not forget about PHP’s composer, which lets you play with packages just like you’re picking candy from the npm candy store.

PHP isn’t about reinventing the wheel; it’s more like having a garage full of fancy wheels for your web development chariot. Stability, you ask? Well, the JavaScript realm changes its clothes more often than a fashionista, while Ruby on Rails is now as big and bloated as your Aunt Ethel after Christmas dinner. PHP is the dependable old uncle who’s not into changing suits every season – your code remains relevant for eons.

Deployment is as cheap as chips – a £5/mo Linux server can host a PHP app and set it up faster than you can say “supercalifragilisticexpialidocious.” Maintenance? Minimal. Scaling? As easy as slicing birthday cake. Plus, PHP plays so nicely with Apache and Nginx that they invite it to all the web development parties.

Hiring help? PHP is like the Macaulay Culkin of web languages – it’s home alone all over the world! Need a freelancer or an onshore or offshore team? No problemo. Managing them, though? Well, that’s another story.

So, in a world of web development choices, PHP might be the wild card you never thought you’d play. I’m currently building a side project with PHP and the Slim microframework. It might not suit all endeavors, but hey, we’re living in the age of abundance, my friend.

Ah, the SQL sleuth script. This SQL query is like a detective with a magnifying glass, scouring the entire SQL Server database for a string. It’s on a mission to find that elusive text, and it’s not taking no for an answer. Armed with a cursor and dynamic SQL, it peeks into every nook and cranny of the database, checking tables and columns, yelling, “Find me if you can!” 🕵️💼🔍

Just remember, while it’s determined, it’s not the most efficient detective in town, it’s down and dirty and doesn’t need a temporary table. It might take a while, but when it’s done, you’ll know where that string is hiding. It’s like a SQL version of “Where’s Waldo,” only with your data. 🔍🤔🕵️‍♀️

Any improvements? Just let me know.

DECLARE @search VARCHAR(100), @table SYSNAME, @column SYSNAME

DECLARE curTabCol CURSOR FOR
SELECT c.TABLE_SCHEMA + '.' + c.TABLE_NAME, c.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN INFORMATION_SCHEMA.TABLES t
ON t.TABLE_NAME=c.TABLE_NAME AND t.TABLE_TYPE='BASE TABLE' -- avoid views
WHERE c.DATA_TYPE IN ('varchar','nvarchar') -- searching only in these column types
--AND c.COLUMN_NAME IN ('NAME','DESCRIPTION') -- searching only in these column names

SET @search='Find me if you can'

OPEN curTabCol
FETCH NEXT FROM curTabCol INTO @table, @column

WHILE (@@FETCH_STATUS = 0)
BEGIN
EXECUTE('IF EXISTS
(SELECT * FROM ' + @table + ' WHERE ' + @column + ' LIKE ''%' + @search + '%'')
PRINT ''' + @table + '.' + @column + '''')
FETCH NEXT FROM curTabCol INTO @table, @column
END

CLOSE curTabCol
DEALLOCATE curTabCol

Much as I’ll admit to some spittle-flecked indignation when it comes to Visual Studio 20-anything, it has largely been the development tool that has paid my mortgage and allowed me to eat biscuits and cake. But this one takes the biscuit, cake, mug of tea and plate.

I’m happily working away, writing code when suddenly find in files stops working with the wonderful message “No Files Were Found To Look In. Find Was Stopped In Progress” Ah it’s simple. I’ve obviously fiddled with the search options and not selected the file types to search in or something similar. Nope –  everything looks just fine.

Ah I know. Close devenv and start again. Nope – exactly the same.

So, off for a coffee and moan and someone says: “Press Ctrl+Scroll Lock a few times and it’ll be fine”. This sounds a bit Mornington Crecsent to me, but it worked.

Sometimes I wonder if I should just go back to using notepad.exe

Today seems to be the day for posting useful stuff on the blog. Actually, it’s just so I can quickly useful find bits of code I might need again.

So I’ve a got a web page that displays some text a user has entered that may contain URLs and I’d like them to be displayed as actual hyperlinks.

 

public string ConvertUrlsToLinks(string msg)
{
string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}

 

Not that this is is going to compete with a full blown keyword or tag service like Google offer, but I needed a very quick way to suggest keywords and tags as users filled out a blog form. There’s no fancy thesaurus or library of data, but it gives surprisingly good results. At least, it gives the user a few hints and ideas about what they should put in as a keywords.

public string GetKeywords(string text, int minCount, int minLength, string additionalWords)

{

string keywords = "";

Dictionary dict = getKeywords(text, minCount, minLength);

foreach (var entry in dict)

 

keywords += entry.Key + ",";

if (additionalWords.Length > 0)

keywords += additionalWords;

return keywords.Trim(',');

}

private Dictionary getKeywords(string text, int minCount, int minLength)

{

text = StripHTML(text);

text = StripCrap(text);

text = text.ToLower();

var stopWords = new string[] {"about","above","across","after","again","against","all","almost","alone","along","already","also","although","always","among","an","and","another","any","anybody","anyone","anything","anywhere","are","area","areas","around","as","ask","asked","asking","asks","at","away","back","backed","backing","backs","be","became","because","become","becomes","been","before","began","behind","being","beings","best","better","between","big","both","but","by","came","can","cannot","case","cases","certain","certainly","clear","clearly","come","could","did","differ","different","differently","do","does","done","down","down","downed","downing","downs","during","each","early","either","end","ended","ending","ends","enough","even","evenly","ever","every","everybody","everyone","everything","everywhere","face","faces","fact","facts","far","felt","few","find","finds","first","for","four","from","full","fully","further","furthered","furthering","furthers","gave","general","generally","get","gets","give","given","gives","go","going","good","goods","got","great","greater","greatest","group","grouped","grouping","groups","had","has","have","having","he","her","here","herself","high","high","high","higher","highest","him","himself","his","how","however","if","important","in","interest","interested","interesting","interests","into","is","it","its","itself","just","keep","keeps","kind","knew","know","known","knows","large","largely","last","later","latest","least","less","let","lets","like","likely","long","longer","longest","made","make","making","man","many","may","me","member","members","men","might","more","most","mostly","mr","mrs","much","must","my","myself","necessary","need","needed","needing","needs","never","new","new","newer","newest","next","no","nobody","non","noone","not","nothing","now","nowhere","number","numbers","of","off","often","old","older","oldest","on","once","one","only","open","opened","opening","opens","or","order","ordered","ordering","orders","other","others","our","out","over","part","parted","parting","parts","per","perhaps","place","places","point","pointed","pointing","points","possible","present","presented","presenting","presents","problem","problems","put","puts","quite","rather","really","right","right","room","rooms","said","same","saw","say","says","second","seconds","see","seem","seemed","seeming","seems","sees","several","shall","she","should","show","showed","showing","shows","side","sides","since","small","smaller","smallest","so","some","somebody","someone","something","somewhere","state","states","still","still","such","sure","take","taken","than","that","the","their","them","then","there","therefore","these","they","thing","things","think","thinks","this","those","though","thought","thoughts","three","through","thus","to","today","together","too","took","toward","turn","turned","turning","turns","two","under","until","up","upon","us","use","used","uses","very","want","wanted","wanting","wants","was","way","ways","we","well","wells","went","were","what","when","where","whether","which","while","who","whole","whose","why","will","with","within","without","work","worked","working","works","would","year","years","yet","you","young","younger","youngest","your","yours"};

var words = Regex.Replace(text, @"[,.?\/;:\(\)]", string.Empty).Split(' ');

var occurrences = words.Distinct().Except(stopWords).Select(w =>

new { Word = w, Count = words.Count(s => s == w) });

return occurrences.Where(wo => wo.Count >= minCount && wo.Word.Length >= minLength)

.ToDictionary(wo => wo.Word, wo => wo.Count);

}

 

minCount the minimum number of duplicate words to catch
minLength the minimum length of word to word on
additionalWords is a set of comma separated word you want tagged(!) to the end of the string. I just use this to force certain keywords and tags

So taking the content of this page (less the code snippet) like this:

string tags = GetKeywords(articletext, 2, 4, "dave");

results in:

“keywords,tags,minimum,word,dave” which isn’t a lot different from what WordPress generated for me automatically, so I used it for my post tags.

I had cause to visit my good friend, Mr Sherlock Holmes, one day last month to discuss a number of matters. Mrs Hudson let me in, took my hat and coat and ushered me to the library where I found Holmes deep in conversation around the table with a rather tall, bearded gentleman with a very shiny hat and oppressively respectable frock-coat. They were studying a large pile of manuscripts. I was about to withdraw, but Holmes quickly beckoned me in, indicating he wanted the door closed.

 “My dear Watson, you couldn’t have come at a better time”, he said cordially.

“You looked otherwise engaged”.

“Very much so”, he replied. “But I should like you to meet Colonel Kerr”. The tall man turned, walked towards me, gave a bob of a greeting and offered his hand.

“Colonel Kerr, this gentleman has been my partner and helper in many of my successful cases and I’m sure will be able to offer some assistance. Colonel Kerr, please meet my good friend Dr Watson”.

We shook hands, he gave a quick little glance from his small, piercing eyes and returned to the table to resumed his studies.

“Watson, I just need to quickly conclude a few matters with Colonel Kerr before he leaves. He has to catch his sailing to South Africa that departs from Southampton this afternoon. Once he has gone, I will explain everything. I know you share my enthusiasm for the bizarre and unconventional puzzles and this promises to be a very interesting one.”

Holmes’s quick eye noticed my questioning glances and gestured towards the side cabinet. “Help yourself to some fruit. Colonel Kerr was kind enough to bring fresh supplies from his travels when he arrived this morning.”

Holmes joined the Colonel at the table and they resumed their study of the manuscript with whispered excitement.

I inspected the large bowl of fruit on the side cabinet with interest. It was well stocked and it had been a while since I had eaten bananas. I’ve always had the suspicion the banana exporting countries conspire to make bananas increasingly difficult to peel. The banana tops refuse to snap open like they used to and one has to resort to a knife. And these bananas were no different. I had the devil of a job with each banana I tried, so decided to abandon my attempts.

“Watson. I’ve decided to accompany the Colonel to the station. We have some more business to complete and the Colonel is late for his train”. Holmes and the Colonel had gathered their papers and were rushing out of the library. “Mrs Hudson will see you out. Meet me here tomorrow at 2pm”.

I heard the gathering of coats, the front door shutting and all was quiet. A sudden still hit the room. Again, Holmes had left me very much in the dark with the promise of revealing all. As I turned to leave, I noticed something on the table. A small pile of banana skins that had been obscured by the mountain of manuscripts was clearly visible. I wandered over to examine the evidence. How on earth had they been peeled?

The banana skins had been torn into many pieces, so it was impossible to fathom any clues. I decided to wait until tomorrow and left Holmes a short note.

It was a quarter-past one when I started from home the following day. I made my way across the park, and so through Oxford Street to Baker Street. I climbed the stairs to the door, knocked and was greeted by Mrs Hudson.

“Sir is in the library,” she said while taking my coat.

“Ah Watson”. Holmes was clearly brimming with self satisfaction as he always did when he’d solved a mystery. “Your note and the pile of banana skins deprived me of sleep last night,” he said buttoning up his pea jacket and taking his heavy hunting crop from the rack. “We’ve solved many mysteries together. Most of them seemingly unsolvable, some impossibly so. However, I confess I had to resort to outside help on this one”.

Holmes pulled a crumpled telegram from the inside pocket of his pea jacket, tapping it with his crop.

“It seems Watson, we need to observe the animal world more closely. This telegram from Colonel Kerr I received this very morning, has made me realize that sometimes we are not as intelligent as we think we are”.

He continued to tap the telegram with his crop with each syllable, so emphasizing his point.

“Colonel Kerr simply peeled those bananas by watching how monkeys do it. No matter how un-ripe a banana is, a monkey will always successfully peel it from the wrong end.”

Holmes obviously took a certain relief from explaining this and shrugged his shoulders.

“So, remember to always peel bananas from the wrong end,” he retorted.

“Nice retorting!” I retorted.

OO purists have long argued that switching on the type of an object by using some conjured up member enum is wrong. And I agree. Fundamentally, it’s nasty and you can satisfyingly waggle your finger at poor OO design.

However, sometimes things aren’t so easy and straightforward. I’m currently working with a complex financial trade class hierarchy that simply can’t be changed – it just wouldn’t be practical. I needed some new functionality that switched on an instance of the base class of the hierarchy. Ok, so it breaks all the rules, but at least it’s switching on a common base type and not completely unrelated types. Peter Hallam’s article describes the problems with a generalised type switch built into the language and why it’s not practical.

So what follows is stream of software design consciousness that touches on the relative casting performance of C# as vs. is, lambda functions, generics and fluent interfaces (method chaining) that achieves a solution.

Lets assume we have some simple class hierarchy. These classes do nothing, but demonstrate the principles involved. We’ll use these throughout the examples.


// Our base class
public class Trade
{
    public void TradeMethod()
    {
    }
}

public class GenericTrade : Trade
{
    public void GenericTradeMethod()
    {
    }
}

public class SwapTrade : Trade
{
    public void SwapTradeMethod()
    {
    }
}

public class SpotTrade : Trade
{
    public void SpotTradeMethod()
    {
    }
}

A first stab at switching on type might be like this:


public void doSomething(Trade trade)
{
    if (trade is GenericTrade)
    {
        GenericTrade genericTrade = trade as GenericTrade;
        genericTrade.GenericTradeMethod();
        // ....
        // ....
    }
    else
        if (trade is SwapTrade)
        {
            SwapTrade swapTrade = trade as SwapTrade;
            swapTrade.SwapTradeMethod();
            // ....
            // ....
        }
        else
            if (trade is SpotTrade)
            {
                SpotTrade spotTrade = trade as SpotTrade;
                spotTrade.SpotTradeMethod();
                // ....
                // ....
            }
            else
            {
                // Default actions
                // ....
                // ....
            }
}

Well it works, but it has a couple of problems.

  • C# offers the syntactically concise way to upcast and downcast using as and is. Unfortunately as Emilio Guijarro shows, the relative performance of ‘as’ vs ‘is’ when typecasting means ‘is‘ is pretty slow.
  • Somehow, the if…else.. If …else structure seams very clunky when there’s more than a few types.

To get around using the slow ‘is‘ is easy.


public void doSomethingElse(Trade trade)
{
    GenericTrade genericTrade = new GenericTrade();
    SwapTrade swapTrade = new SwapTrade();
    SpotTrade spotTrade = new SpotTrade();

    if (genericTrade as GenericTrade != null)
    {
        genericTrade.GenericTradeMethod();
        // ....
        // ....
    }
    else
        if (swapTrade as SwapTrade != null)
        {
            swapTrade.SwapTradeMethod();
            // ....
            // ....
        }
        else
            if (genericTrade as GenericTrade != null)
            {
                genericTrade.GenericTradeMethod();
                // ....
                // ....
            }
            else
            {
                // Default actions
                // ....
                // ....
            }
}

This requires an instance of each type, but the structure is even more horrible than before. So abandon that way of doing it. What we really need is something that is readable. Something like this would be ideal:


public void doSomething(Trade trade)
{
    switch (trade)
   {
      case GenericTrade:
            // ...
            // ...
            break;
      case SwapTrade:
            // ...
            // ...
            break;
       case SpotTrade:
            // ...
            // ...
            break;
        default:
            // ...
            // ...
            break;
      }
}

Bart De Swet’s article that describes a solution that yields a similar code structure. This is implemented using method extensions which is unnecessarily complicated, so I devised a similar solution using instance methods.

So here’s my take on a switch class – I’ve called it SwitchOnType for clarity:


public class SwitchOnType<T1>
{
    bool _break = false;
    private T1 _object;

    public SwitchOnType(T1 obj)
    {
        _object = obj;
    }

    public SwitchOnType<T1> Case<T2>(Action<T2> action) where T2 : class
    {
        if (_break == false)
        {
            T2 t = _object as T2;
            if (t != null)
            {
                action(t);
                _break = true;
            }
        }
        return this as SwitchOnType<T1>;
    }
    public void Default<T2>(Action<T2> action) where T2 : class
    {
        if (_break == false)
        {
            T2 t = _object as T2;
            if (t != null)
                action(t);
        }
    }
}

And here’s how it’s used with our class hierarchy example:


public void doSomething(Trade trade)
{
    new SwitchOnType<Trade>(trade)
        .Case<GenericTrade>(genericTrade =>
        {
            // It's a GenericTrade
            genericTrade.GenericTradeMethod();
            // ...
            // ...
        })
        .Case<SwapTrade>(swapTrade =>
        {
            // It's a SwapTrade
            swapTrade.SwapTradeMethod();
            // ...
            // ...
        })
        .Case<SpotTrade>(spotTrade =>
        {
            // It's a SpotTrade
            spotTrade.SpotTradeMethod();
            // ...
            // ...
        })
        .Default<Trade>(t =>
        {
            // Default actions
            t.TradeMethod();
        });
}

Although there’s a few extra {‘s and )’s, the structure is close to the ideal. This is mainly possible using method chaining (also known as fluent interfaces), by returning this (well a genericized this) in the case method and passing the code to be executed if the case test succeeds as a lambda function. Note if none of the Case methods succeeds, the Default method will get called. If you want to know more about fluent interfaces read Martin Fowler’s article.

So just accept that sometimes you have no choice and have to accept that it’s right to do what’s wrong – is that software or life. Or both.

“Is a URL a URI?”
“Is a URI a URL?”
“What does URL stand for?”
“What does URI stand for?”
“What does URL mean?”

I’ve been asked so many times I’ve lost count and for the sake of my sanity, I’ve decided to explain their distinquishing marks.

URL  – Uniform Resource Locator
URI – Uniform Resource Identifier

Sometimes these achronyms are used interchangably which is almost entirely wrong. Basically a URL is a specific type of URI because it uses specific protocols like http:  ftp: and mailto: URI defines a larger, more generalized superset.

Effectively, URL is no longer a valid in technical conversations or documents and you should use URI regardless of how big a pedant you are. A URI describes both the way you access something and it’s designated location.

You may see some explainations where U is defined as Universal. This is wrong and the author is just confused.

So, let’s call the whole thing off.

Create your own website, free on WordPress.com.Create your own website.
Start free