Throttle Helper

2014-12-09 12:41 AM

I've been writing a lot of revision code recently which ends up spamming our service bus with events. Since I need to dial back the volume of messages that get sent per time chunk, I've gone through a few revisions of blocking - from Task.Delay(250).Wait(); to more obfuscated methods.

But I think this is my favorite so far - it's lightweight and pretty self-explanatory. The goal is to have a loop that will execute no more frequently than the given number of millis. So, if the target is 250ms and the body of the loop takes 300ms to execute, there's no waiting to be done. If the body takes 50ms, then we should wait for 200ms.

With some not-quite-clever use of Tasks we can accomplish this pretty easily:

public class Throttle
{
    private Task _control;
    private readonly int _minimumMillis;

    public Throttle(int millis)
    {
        _minimumMillis = millis;
    }

    public void Block()
    {
        // Only block if it's not the first time
        if(_control != null)
        {
            _control.Wait();
        }
        _control = Task.Delay(_minimumMillis);
    }
}

The only slightly tricky thing is in the _control = Task.Delay(_minimumMillis); call. We start a Task whose sole function is to wait for _minimumMillis. This waiting begins asynchronously while control is returned to the caller. Then, when Block() gets called again, that Task gets attached to after having waited for some amount of time already. This allows a smarter throttling so you can pump out as near to your desired throughput as possible.

This allows us to write a throttled loop, a la:

var throttle = new Throttle(1000);
for(var i = 0; i < 100; ++i)
{
    // Won't execute more frequently than once per second
    Console.WriteLine(i);
    throttle.Block();
}

But what if we want it to be just a little more magical? We can extension-method it right into the IEnumerable that drives a foreach loop!

public static IEnumerable<T> Throttled<T>(this IEnumerable<T> source, int millis)
{
    var throttle = new Throttle(millis);
    foreach(var item in source)
    {
        throttle.Block();
        yield return item;
    }
}

And, voila!

// Could be any IEnumerable
var source = Enumerable.Range(0, 10);
foreach(var i in source.Throttled(250))
{
    // Won't execute more frequently than 4/sec
    Console.WriteLine(i);
}

CROSS APPLY in Linq

2014-11-23 1:42 AM

Quick note: when trying to do a SQL-style CROSS APPLY using linq with a SQL database underneath, the C# linq statement

from a in Table<TableA>()
from b in Table<TableB>()
       .Where(c => c.Id == a.Id).Take(1)
select new { a, b };

is functionally equivalent to the SQL query

SELECT 
     * 
FROM 
    TableA a
    CROSS APPLY 
    (
        SELECT TOP 1
            * 
        FROM
            TableB b 
        WHERE
            b.id = a.id
    ) b

Interviewing Engineers at Spotlite

2014-06-25 1:43 AM

Interviewing engineers is hard; skill sets are difficult to discern, and it's really challenging to draw out evidence of talent while walking the line between banal/obvious technical questions and niche/overly-clever riddle-type questions.

Over the past several years, I've developed a bit of a philosophy on interviewing engineers. It's over here on the company blog:

http://www.spotlite.com/interview-goals-engineering-skills/

Enjoy!

Photoblog: Planes

2014-04-14 9:57 PM

This is one of my favorite personal shots ever, from a session out in the rain this past weekend.

http://ppcdn.500px.org/67068955/1006d26e77321822e3051df1cdfcba9e7400c7bc/4.jpg

Boosting Productivity by Quieting Outlook

2014-04-08 2:52 PM

Developers need large chunks of time in which they can focus intently on tasks to complete work well. In general, we cannot context switch with perfect compartmentalization: if I'm working on a project, get called to a meeting, then come back to the project, I've lost way more time than just the minutes that the meeting took up.

Since there is tons of information on why interruptions are bad, I'm going to omit that from this post and go directly to attacking Outlook. It's an okay tool for mail and planning, but its built-in defaults are terrible for developers and other concentration-type mental work.

My actions taken against Outlook are a direct response to this post on productivity by Scott Hanselman. If you don't subscribe to his blog, you should.

Turn off desktop notifications and sounds

It's amazing how much this one item helps: simply eliminating that little envelope that told me someone (or something) wanted my attention decreased distractions immensely.

I disabled all of the following things:

  • Desktop notifications
  • Sounds
  • Outlook icon flashing in taskbar
  • Outlook icon changing in taskbar

That last one is pretty subtle, but important: essentially, the goal here is to change Outlook from a "LOOK AT ME NOW" notification system to a "Check it when you have a few minutes" polling system.

Yes, I understand that this is a regression in technology, and even harks back to ye olde hotmail days. It makes you "check your email" instead of always being on top of all information at all times.

But, as it turns out, having a constant in-flow of communication makes it impossible to concentrate on any task.

Turn off 15-minute-prior meeting notices

One thing that took me a long time to realize was a huge hindrance is the 15 minute meeting notice. By default, Outlook decides that you need 15 minutes' advance warning of a meeting.

Now, this may be the case for some people, but I would posit that your average developer, who is much more concerned about writing good software than cramming for every meeting, does not need this.

So what do you do?

Two minutes' notice.

This is enough time to gather some context about the meeting, grab a cup of coffee and get to the conference room.

What are you waiting for? Tell outlook to do reminders at 2 minutes instead of 15! There's no reason that you should be interrupted that far in advance, wasting 13 precious minutes of concentration time.

Auto-sort into "Don't Care" inboxes

When you start getting a lot of email, your job description starts to feel like "deleting email." That's an antipattern and it is wrong. How can you combat that?

In short, you have three inboxes:

  • Inbox (External): From anyone outside of your organization
  • Inbox (CC): Emails that you're CC'd on
  • Inbox: Emails that don't get caught by either of those conditions

By doing this, you auto-filter out most of the junk that clogs your inbox and makes you an email-deletion-automaton.

Hanselman describes how to do this better than I could, so I'll just link out to him.

Read this.

Bonus: Lump your meetings into one day

All of the previous suggestions can be executed by you, on your machine, in a few minutes. This one is much more organizational.

Get your organization/department/team to have as many of its meetings as possible on a single day every week.

We started this a couple of months ago. Tuesday is meetings day.

Tuesdays suck for personal productivity, but boost company communication and collaboration.

But sacrificing most of one day means that Monday, Wednesday, Thursday and Friday are much freer from disruption, and can be more wholly dedicated to personal work.

Does this mean that you can't have meetings outside of your designated meeting day?

No. It's not a hard-and-fast rule, but rather an affinity. Try it out, it should help you if you can get your team on board.

Passwords and You: Partners in Freedom

2014-03-25 8:06 AM

Today I decided to delete my account at PayPal. I'd been meaning to for a while, but they sent me a marketing email which reminded me to finally carry it out.

First this meant resetting my password because I forgot what it was, since the last time I used it was...who knows.

paypal<em>password</em>3.png

They are Keeping me safer, so this should be easy.

Like any nerdy, security-minded person, I use a password manager so that I don't know the passwords to any sites I sign up for. KeePass is my facilitator of choice here - it's awesome and helps a ton. If you're not using it, you should.

Anyhow, I had KeePass create me a new, strong, secure password and I pasted it into the box.

paypal<em>password</em>0.png

Whoops. They won't let me copy/paste it.

wat.

Okay, sure, this is par for the course for bad security on the internet. Fine, I'll just use correct horse battery staple.

paypal<em>password</em>1.png

Oh. Yeah, we wouldn't want my password being too long now would we? Okay, shorter sentence:

paypal<em>password</em>2.5.png

Surely this one will work

paypal<em>password</em>2.png

rage

Review

Let's count the security missteps here:

  1. Disallow password pasting. Don't do this. Ever. All you're doing is foiling people who use good password management systems.
  2. Maximum password length. Why would this even be a problem, ever? Your passwords are hashed well, right? Since there's no way you have a PASSWORD NVARCHAR(20) field in your database, it makes no sense to have a maximum password length. The only thing you're doing here is restricting entropy and reinforcing bad password practices.
  3. Disallow spaces. In what universe does this make sense? Presumably this is in place to stop people from just typing a sentence in, but (a) the small maximum password length precludes that and (b) that actually makes for a pretty good password.

If you make websites, please do not do any of these things. It's like a master course in security anti-patterns.

Spotlite Blog: Federal Grant

2014-03-19 7:46 AM

I work at Spotlite. We do online insurance enrollment and benefit management, and it's a really exciting place to work.

I recently wrote a blog post on our authorization system, which is called Federal Grant. It was a really neat project to work on due to its depth and breadth, so if you want to learn a little bit about how we silo and administer permissions for a complex-but-configurable subset of role holders based on some additional, hierarchical allowances they're granted, check it out!

Federal Grant on Spotlite

Thin, Dumb and Pretty

2014-03-12 6:07 PM

MVC Applications should be Thin, Dumb and Pretty.

Thin

Don't make your actual MVC application responsible for a lot of tasks. It should handle collating data from a few (okay, maybe many) sources, displaying it to a user, and persisting that data back to those few (many) sources.

Dumb

Core business logic doesn't belong in MVC. If you have a monolithic software pattern, the core logic belongs in your huge service. If you follow a more microservice architecture, your MVC application should just be consuming and feeding disparate services. When the application gets smarter than that, business logic starts creeping up toward the top - exactly where you don't want it.

Pretty

Code isn't pretty to anyone who's not a developer. MVC's primary responsibility in an enterprise context is to display information to a user. Make its primary responsibility be displaying information in an intuitive way.

Photoblog: Dough

2014-01-14 6:42 AM

001<em>_DSC3544</em>Small.jpg

Photoblog: Chiberia 3

2014-01-07 8:41 PM

021__DSC4051.jpg

Photoblog: Chiberia 2

2014-01-07 8:40 PM

018__DSC4045.jpg

Photoblog: ChiBeria

2014-01-07 8:40 PM

016__DSC4042.jpg

Helpful Extension Methods: TryParse[x]()

2013-11-26 1:22 PM

Parsing into primitives in C# is not quite as nice as it should be, particularly if you're attempting to parse and soft-failing if the parse doesn't work. For instance, if we want to attempt to parse a string to a DateTime?, which is null if the parse fails and correctly set if it succeeds, we would have:

var input = "2013-01-10 06:11:20 AM";
DateTime? asDateTime;
DateTime target;
var success = DateTime.TryParse(input, out target);
if (success)
{
    asDateTime = target;
}
else
{
    asDateTime = null;
}

This isn't good - it's really chunky and gross. Additionally, I hate the out parameter modifier: my opinion is that classes and Nullable<T>s completely supplant any value it offers, and that it just promotes poor coding practice.

So let's wrap up the outs with extension methods so we never have to deal with these crummy parsing wrappers!

DateTime

Here's how we can wrap it up pretty easily:

public static DateTime? AsDateTime(this string input)
{
    DateTime result;
    if (DateTime.TryParse(input, out result))
    {
        return result;
    }
    return null;
}

And to illustrate the utility, it makes the original code snippet much more clear:

var input = "2013-01-10 06:11:20 AM";
var asDateTime = input.AsDateTime();

That's great! But let's keep in mind that there are several other primitives...

int

Fortunately, it's really easy to modify this code for most primitives in .NET - just replace DateTime with whatever target you have - in this circumstance, int:

public static int? AsInt(this string input)
{
    int result;
    if (int.TryParse(input, out result))
    {
        return result;
    }
    return null;
}

decimal

Wouldn't it be great if we could just write this as a generic? Unfortunately, all of the parse methods are static, implementation-specific methods that can't be called generically.

public static decimal? AsDecimal(this string input)
{
    decimal result;
    if (decimal.TryParse(input, out result))
    {
        return result;
    }
    return null;
}

The rest is up to you

At least having some extension methods to parse with less headache helps out a lot. Extend these to any other structs or classes that give you parsing headaches, and your code gets better little by little!

Lessons in Antipatterns: Leadership Vaccum

2013-11-21 9:55 AM

Leadership Vacuum is a fantastic excursion in antipatterns. If you haven't checked it out, you should.

It's written in-character as W. Albert Jameson IV, a manager who understands almost nothing about truly good management. Every post is a snapshot of his mind that discusses the "right" way to manage people; his way is always riddled with problems which are obviously wrong, yet widespread in their use.

And almost every post has an immediately-applicable "Oh wow, I should definitely not do this" takeaway.

As a sarcastic developer, I love antipatterns - and this is a fantastic, consistently-updated revelation of antipatterns that pop up all-to-frequently anywhere that leadership occurs.

Check it out!

http://leadershipvacuum.com/

Attempted Dictionary Access

2013-11-09 1:33 PM

Dictionarys in C# are super useful for any sort of key/value-related datasets; but what is the best way to access that data?

If you're confident that your source data is there, the clearest way is obviously to use the [] indexing operator:

var englishToSpanishWords = new Dictionary<string, string>
{
    { "ball", "pelota" },
    { "cup", "taza" },
    { "man", "hombre" }
};
var ballInSpanish = englishToSpanishWords["ball"];

But what if I'm not confident that my requested key will be there? If I attempt

var ballInSpanish = englishToSpanishWords["woman"];

I'll get a KeyNotFoundException, since my attempted key wasn't in the dictionary.

There are two relatively straightforward was to do this:

Simple Null Check

This method is completely straightforward, and is a fairly simple null-armoring.

static string TryToGetValue_NullCheck(IDictionary<string, string> dictionary, string key)
{
    if (dictionary.ContainsKey(key))
    {
        return dictionary[key];
    }
    return null;
}

However, .NET provides another method

TryGetValue

To be completely blunt, I do not like the TryGetValue() method that .NET provides for dictionaries. The out coding paradigm is completely outdated since we now have nullable types. However, it's a method provided by the framework, so it's worth looking at:

static string TryToGetValue_Framework(IDictionary<string, string> dictionary, string key)
{
    string output;
    if (dictionary.TryGetValue(key, out output))
    {
        return output;
    }
    return null;
}

Again this is pretty straightforward, but the workflow is not as immediately obvious as the regular null armoring is: setup a variable to house the result, attempt to set that value using the dictionary and key, then conditionally return a result based on the degree of success that was encountered in setting that variable.

But Which One is Better?

As far as coding practice goes, it's a toss up. The first method is a little more straightforward and readable, but the second one is provided by the framework and, while it's not unreadable, it uses a coding paradigm which I consider an antipattern.

How do we solve this? Let's do some profiling and see which one is faster!

Here's a small app I whipped up to profile the performance of these methods:

public static void Main(string[] args)
{
    var size = 10000000;
    var target = Enumerable.Range(0, size)
                            .ToDictionary(a => a, a => Guid.NewGuid());

    var resultList = new List<Guid>();

    var sourceData = Enumerable.Range(size / 2, size);

    var timer = Stopwatch.StartNew();
    // Half will hit the dictionary, half will not
    foreach(var i in sourceData)
    {
        if (target.ContainsKey(i))
        {
            resultList.Add(target[i]);
        }
    }
    timer.Stop();
    Console.WriteLine("Contains/Index access: {0} milliseconds for {1} total requests",    
                        timer.ElapsedMilliseconds, size);

    resultList.Clear();
    timer.Restart();

    // Half will hit the dictionary, half will not
    foreach (var i in sourceData)
    {
        Guid result;
        if(target.TryGetValue(i, out result))
        {
            resultList.Add(result);
        }
    }
    timer.Stop();
    Console.WriteLine("TryGet access: {0} milliseconds for {1} total requests",
                        timer.ElapsedMilliseconds, size);

    Console.Read();
}

Execute!

Contains/Index access: 717 milliseconds for 10000000 total requests
TryGet access: 439 milliseconds for 10000000 total requests

Wow - the framework's method is 39% faster than the null check. This isn't necessarily shocking, since the .NET guys built the method, but it's enough of a difference to warrant use of that method.

Wrapping the (ugh) out Method

Since I can't stand using out-parameter-using methods, let's wrap this in a helpful extension method which attempts to get a result and returns null if none is found.

public static TValue ValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> source, 
    TKey key) where TValue : class
{
    TValue result;
    return source.TryGetValue(key, out result) ? result : null;
}

The only problem here is that IDictionary<>s with a struct for the value type will not work. We need a different method for that.

public static TValue? ValueOrNull<TKey, TValue>(this IDictionary<TKey, TValue> source, 
    TKey key) where TValue : struct
{
    TValue result;
    return source.TryGetValue(key, out result) ? result : (TValue?)null;
}

Code Snippet: Move Cursor to Center of Main Screen

2013-10-25 1:46 PM

Having a lot of monitors at work, I sometimes have a hard time finding where the mouse's cursor is on the screen immediately. Here's a helpful little snippet to immediately move the cursor to the center of the primary screen:

Cursor.Position = new Point
    (
        Screen.PrimaryScreen.Bounds.Left +
            ((Screen.PrimaryScreen.Bounds.Right - Screen.PrimaryScreen.Bounds.Left) / 2),
        Screen.PrimaryScreen.Bounds.Bottom + 
            ((Screen.PrimaryScreen.Bounds.Top - Screen.PrimaryScreen.Bounds.Bottom) / 2)
    );

Two Towers

2013-09-30 8:45 AM

1262867<em>846555560124</em>725998.jpg

Marina City

Trump

2013-09-28 6:35 PM

135__DSC3237.jpg

Trump International Hotel and Tower

Helpful Extension Method: IsBlank

2013-09-20 4:53 PM

I frequently find myself using the static string methods like Format() and IsNullOrWhitespace(). Due to my laziness and the perceived inelegance of calling those static methods every time I want to use them, I have developed some helpful wrappers over time.

IsBlank

public static bool IsBlank(this string input)
{
    return string.IsNullOrWhitespace(input);
}

The really nice thing about this one is that it works on objects that are null due to the nature of extension methods. It allows your code to be more readable since the reader's comprehension doesn't have to dart around.

if(string.IsNullOrWhitespace(getAString()))

dances around the usual flow of thought: rather than saying "is this string blank," you're asking "is null or whitespace this string?" If you're a fan of Yoda conditions this may be intuitive, but I perceive this to be much more easily comprehensible:

if(getAString().IsBlank())

IsNotBlank

public static bool IsNotBlank(this string input)
{
    return !input.IsBlank()
}

Since one of the goals of IsBlank() is immediate readablilty, it makes sense to have another method which is just a thin logical NOT wrapper. In my mind, it's much easier to miss the bang in !input.IsBlank() than it is to miss the intent of input.IsNotBlank().

Picture

2013-09-20 8:29 AM

sl_rn.jpg

Landis's Law

2013-09-13 9:37 AM

I hereby declare Landis's Law:

If a software/internet concept contains "Simple" in its title, it is, by nature, not simple.

For instance:

  • RSS (Really Simple Syndication): Not simple
  • SOAP (Simple Object Access Protocol): Not simple

Photoblog

2013-09-13 9:02 AM

Yesterday's sunset was amazing.

1233067<em>841385311344</em>128839.jpg

Images!

2013-09-07 12:11 PM

I finally got around to creating a resource management system using Azure Storage as my content provider!

015<em>DSC</em>5134_small.jpg

Pattern: Loop Decoupling in C# with Linq

2013-09-01 6:37 PM

Back in college, we all learned about loop unrolling in computer architecture/compiler classes. Though the loop decoupling pattern is not really related, the techniques are both different ways to look at loops and improve them; however, the decoupling attacks modularity, composability and testability rather than execution time.

Problem Statement

When presented with a loop that satisfies the following conditions, loop decoupling becomes an applicable pattern:

  • The enumeration of data is programmatic (not data driven) and nontrivial
  • The filtration process is nontrivial and composable
  • Bonus points if ordering or grouping is necessary

Pattern Outline

Loop decoupling essentially involves three parts:

  1. Encapsulate the data generation in a method which returns an IEnumerable<T> and performs no filtration
  2. Encapsulate the filtration logic into a method or methods which take in T and return bool
  3. Use these composable bits to write a single Linq statement, optionally grouping or ordering afterward

This pattern yields several benefits:

  • Since the data and filtration logic are separated into their own methods, they
    • Each have a single responsibility
    • Are easily understandable on their own
    • Are easily testable
  • The final composed Linq query is easy to understand, and makes the intention of the code extremely clear

Example

Since this concept is incredibly abstract, we'll need to cement it in with a good example.

For a given date d and a given day of the week m, find the date nearest to d which is day of the week m.

Since we need the nearest date rather than the next date, the enumeration operation is nontrivial. Though the filtration method is fairly simple in this example, we'll charge forth with the assumption that the real world business filtration requirement would be more complex.

So, let's go through the steps!

1. Encapsulate the data generation

We need a method that takes in a DateTime (the parameter d from the problem statement) and returns IEnumerable<DateTime>. Our strategy will be to search out from the given date in both directions and emit all dates we encounter in the process.

IEnumerable<DateTime> SearchDates(DateTime input, int max)
{
    yield return input;
    for(var i = 0; i < max; ++i)
    {
        yield return input.AddDays(i);
        yield return input.AddDays(-i);
    }
}

Some notes:

  • We take in a max value so that the loop doesn't execute into infinity
  • The input date is returned first because it may be the one we're looking for
  • We move forward and backwards at the same time, one more day each way on every iteration

2. Encapsulate the filtration logic

Next, we need a method that takes in a DateTime and a day of the week (parameter m from the problem statement) and returns a bool.

bool IsValid(DateTime date, DayOfWeek target)
{
    return date.DayOfWeek == target;
}

3. Compose a Linq statement

Now it's really easy to extract the first matching date!

DateTime GetNearestDay(DateTime target, DayOfWeek day)
{
    var results = from d in SearchDates(target, 3)
                  where IsValid(d, day)
                  select d;
    return results.FirstOrDefault();
}

Freebie: Query modification

Now that we have a composed query, we get a lot of functionality for free! When business requirements come through to add more filtration, order results differently or alter the return type to include a grouping, we can really easily modify the query without having to touch either the generation or filtration logic!

object ThisDoesntMakeSense(DateTime target, DayOfWeek day)
{
    return from d in SearchDates(target, 365)
           where IsValid(d, day)
                 && SomethingElse(target)
           group d by d.DayOfMonth into d
           order by d.Key descending
           select d;
}

RSS Feed

2013-09-01 9:42 AM

Blogs on this site now have RSS support! Just add /feed to any blog URL (auto-link pending) and add it to your favorite feed reader!

Helpful Extension Methods

2013-08-24 8:32 PM

Having done a lot of writing in C# in the past several years, I've wound up with a fairly extensive personal library of helpful extension methods.

Introduction

In case you're unfamiliar, Extension Methods are a compiler trick that allow you to seemingly add functionality to existing types by creating static methods within a static class, and specifying the target type with the this keyword. For example, here's an extension method to determine if an int is even:

public static class Extensions
{
    public static bool IsEven(this int num)
    {
        return num % 2 == 0;
    }
}

Take note of the construction: - Class: the extension method is within a public, static class. Note that one extension-method-containing class may contain any number of extension methods. - Method: like the class, the method is public and static. - Type: the int argument is enhanced with the this keyword, which signals to the C# compiler that this is an extension method. Note that in a method with multiple arguments, the extended type must be the first one (this always comes first).

Past the special treatment of adding the this keyword to the first argument, the method is constructed in a perfectly normal way.

Calling the method is trivially simple:

var myInt = 2;
Console.WriteLine(myInt.IsEven());
myInt = 3;
Console.WriteLine(myInt.IsEven());

The first output will be "true," while the second one will be "false." Note that you are given the ability to call IsEven() as if it were an instance method of int.

As I mentioned before, this is a compiler trick: you're not actually modifying the int type in any way; you've just exposed a public method that the C# compiler turns into a faux-instance method which is callable as if it were part of the type. To demonstrate this, you can also call the method directly, in the following fashion:

var myInt = 2;
Console.WriteLine(Extensions.IsEven(myInt));
myInt = 3;
Console.WriteLine(Extensions.IsEven(myInt));

These two bits of code do the exact same thing.

Multiple Arguments

Additionally, adding more arguments to the method is very easy:

public static class Extensions
{
    public static bool IsDivisibleBy(this int num, int divisor)
    {
        return num % divisor == 0;
    }
}

And the following code will produce the same output as it did before:

var myInt = 2;
Console.WriteLine(myInt.IsDivisibleBy(2));
myInt = 3;
Console.WriteLine(myInt.IsDivisibleBy(2));

Benefits

Extension methods offer a number of benefits - they allow you to seemingly extend functionality for types which are out of your control, which is great; however, there are two points that make them particularly useful.

Any type

One huge benefit extension methods grant is the ability to add functionality to any type: you are not restricted to classes. This means that you can define an interface, then "add functionality" to it by creating extension methods.

This is most readily apparent in the Linq library, where the query operators extend functionality for IEnumerable<T> types. The declaration of the Where<T> operator looks like this

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

and allows you to call it on any IEnumerable<T> - even though the `IEnumerable interface only contains functionality for iterating over a series of objects.

I have taken advantage of this several times by defining an interface with no requirements, and then defining a few extension methods that add behavior to that interface. This has the effect of allowing a developer to add that functionality to their new class by simply declaring that it implements a particular interface.

Null arguments

While some might consider it annoying that extension methods don't work as actual instance methods (for instance, you do not have access to any non-public members of the target type), I have used this fact to my advantage many times, particularly in null-checking arguments.

For instance, consider the ubiquitous .ToString() method in C# which is a member of the base object type: the class which every reference type extends: this method is very useful for turning objects into strings; however, it starts failing if you are uncertain of whether or not your object is null.

string GetString(object myObject)
{
    return myObject.ToString();
}

This method will obviously blow up if you pass in null, and that's probably not the desired behavior. So, we could introduce a trivial change to null-armor it"

string GetString(object myObject)
{
    if (myObject == null)
    {
        return null;
    }
    return myObject.ToString();
}

That's all well and good: it will work. However, write that null check a couple of hundred times over the course of a few months and you'll quickly grow tired of those extra lines cluttering up your code. We can solve this with an extension method! And this brings me to my first Helpful Extension Method: NullableToString

NullableToString

public static class Extensions
{
    public static string NullableToString(this object obj)
    {
        if (obj == null)
        {
            return null;
        }
        return obj.ToString();
    }        
}

This functionality is still very simple; but suddenly it unlocks the ToString-ing of objects without caring whether or not they're set to an instance of an object! We can now seemingly call an instance method of the incoming object with complete immunity from null issues!

string GetString(object myObject)
{
    return myObject.NullableToString(); // Don't even care if it's null or not!
}

There is one more step to take here though: sometimes I expect an actual instance of a string to come out of the method, whether or not it's actually populated with anything. This typically occurs when I'm following the ToString() with a ToUpperInvariant() or some other method that expects an instance of a string to be passed in.

NullableToEmptyString

public static class Extensions
{
    public static string NullableToEmptyString(this object obj)
    {
        if (obj == null)
        {
            return string.Empty;
        }
        return obj.ToString();
    }        
}

We can now do whatever we want with the result with complete safety.

string GetString(object myObject)
{
    return myObject.NullableToEmptyString().ToUpperInvariant();
}

Trello Link

2013-03-13 5:06 PM

I've just added a link to the Trello board I'm be using to track the development of this site: both actual code development and content.

FizzBuzz (Code PoC)

2013-03-10 3:45 PM

Okay, let's test out some code styling. Here's a fizz-buzz implementation (with a couple of liberties taken to get it to smash down to one line):

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine
        (
            string.Join
            (
                Environment.Newline, 
                Enumerable.Range(1, 100)
                    .Select(a => 
                        a.ToString() + ": " +
                        (a % 3 == 0 ? "Fizz" : string.Empty) + 
                        (a % 5 == 0 ? "Buzz" : string.Empty)
                    )
            )
        );
        Console.Read();
    }
}

Initial Post

2013-03-10 3:30 PM

Hello world, this is my first post. There should be a bucket of links on the bottom of each page now, so check out the other stuff.

Next to come are:

  • Simple styling (kill the serif default, etc.)
  • Simple JS: Let code be prettified!