My Obviously Perfect Code: An Attention-Seeking Post Title

Bombastic opening statement about the strength of the glorious code you're about to read. Further explanation that clearly you haven't seen anything as good as this yet.

Unimportant and overlong diatribe explaining why this forthcoming code snippet is critical to the world at large, including meaningless attempt at invoking "think of the children." Bluntly state that my fellow bloggers have it all wrong, that only I have the true solution. Immediately try to roll back that statement with phrases like "they have their good ideas," but subtly acknowledge that, yes, I am better than them, thanks for asking.

Dive into a story about how, in my early years, something bad happened and compelled me to think of the world differently. Clearly I was so traumatized by this experience that everyone else should be sad for me, hence why I am relating it to you, even though you didn't need or really want me to. Weakly try to link that unnecessary story to the potential improvements the world can harness from my code and fail miserably, but continue to insist that I'm right and that you all should thank me for deigning to spend my irreplaceable time on this God-given snippet.

Attempt to drum up excitement for my impressive snippet by using words like "magical" and "time-saving" and "microservice". Finally get around to introducing the code, but not before once again flatly stating how the world should be thanking me for creating this divinely inspired piece of code.

Final introduction statement, which will invariably include the phrase "and without further ado..."

public static string Truncate(this string input)  
{
    if (input.Length > 40) return input.Substring(0, 40) + "...";
    else return input;
}

Bluntly state that yes, it is as magical as it seems. And, yes, it is also just that simple. Subtly ask for praise while maintaining that you only do this to help your fellow programmers, but really, the praise would be accepted with dignity. And repeatedly. Preferably with Kickstarter donations.

Trite closing paragraph, with sweeping but hollow affirmations that I'm the best coder who ever lived, and everyone else should recognize that. Of course, I will accept all that praise humbly and with deference to my fellow man.

Suitably dull closing signoff statement, almost certainly including the word "coding."

Post image is obviously Simon looking Smug from Flickr, used under license. I mean, come on.

Code Is Ephemeral, Concepts Are Eternal

Lots of people ask me things like "should I learn MVC or Web API first?" "HTML or Javascript?" "Angular or React?" etc. After all, there's only so many hours in the day, and what time we have to spend learning is often limited by other factors (energy, work policies, etc.) This leads to the most common question I get from junior programmers: What framework, stack, or language should I spend my precious time learning?

I always tell them the same thing: It. Does. Not. Matter.

It doesn't matter if you pick Angular, or ASP.NET, or Ruby, or Java. It does not matter if you want to build web sites, or IOS apps, or Windows programs. It does not matter if you're a fresh-out-of-school graduate or a 30-year programming veteran. All of these technologies, all of these platforms, will ultimately help you learn the same things, the same tried-and-true best practices. Just pick one!

Remember: you will be obsolescent someday. That will happen, especially in a business where you must continually stay on top of your own learning in order to do your job. You have a finite number of keystrokes left. Therefore you should spend your limited time learning whatever will stave off that obsolescence for as long as possible.

Concepts fight obsolescence. Even when ASP.NET inevitably dies, the concepts I've learned from programming in it for ten plus years will still be useful. Concepts have a longer shelf life than details, because details change. Languages are born and die, frameworks become unpopular overnight, companies go out of business, support will end. But the thoughts, the ideas, the best practices? They live forever.

Learn about SOLID. Learn KISS, DRY, and YAGNI. Learn how important naming is. Learn about proper spacing, functional vs object-oriented, composition vs. inheritance, polymorphism, etc. Learn soft skills like communication and estimation. Learn all the ideas that result in good code, rather than the details (syntax, limitations, environment, etc.) of the code itself. Mastering the ideas leads to your mind being able to warn you when you are writing bad code (as you will inevitably do).

Don't fret about the how. How you learn the concepts is irrelevant. It doesn't matter what framework you like, what stack you use, what technology you're currently in love with. Just pick one, learn that, master that, and remember some of the pain you had to deal with for the next project. Write a small project, post it to GitHub, blog about it. Get some experience with it! Experience is king, and nothing can substitute for real-world experience.

Code is ephemeral, concepts are eternal. Code is static; it will die, fall apart, degrade. It may take a long time, years or decades, but it will happen. But the concepts which programming lives off of do not die; they live on.

So again I pose the question: what should you spend your precious time learning?

The ASP.NET Web API 2 HTTP Message Lifecycle in 43 Easy Steps

Anyone who works with ASP.NET Web API should check out this poster that Microsoft created to explain the Request/Response Pipeline that Web API utilizes. It's amazing, and if you do any work in Web API you should check it out! Right now. Yes, seriously. Go ahead, I'll wait.

I love this poster, but in my opinion it doesn't do a good job of explaining the decision logic and ideas behind each step in the pipeline. Further, it doesn't explicitly tell you exactly how many things happen during this pipeline (answer: a surprisingly large number of things). In short: it's awesome, but it can be made more awesome by incorporating just a little more detail.

Here's what we're going to do in this post: using that poster, we're going to enumerate every single step involved in processing a request and receiving a response using ASP.NET Web API 2, and explain a little more about each piece of the pipeline and where we programmers can extend, change, or otherwise make more awesome this complex lifecycle. So let's get going and step through the ASP.NET Web API 2 Request Lifecycle in just 43 easy steps!

The 43 Steps

It all starts with IIS:

  1. IIS (or OWIN self-hosting) receives a request.
  2. The request is then passed to an instance of HttpServer.

  3. HttpServer is responsible for dispatching HttpRequestMessage objects.

  4. HttpRequestMessage provides strongly-typed access to the request.

  5. If one or more global instances of DelegatingHandler exist on the pipeline, the request is passed to it. The request arrives at the instances of DelegatingHandler in the order said instances were added to the pipeline.

  6. If the HttpRequestMessage passes the DelegatingHandler instances (or no such handler exists), then the request proceeds to the HttpRoutingDispatcher instance.

    • HttpRoutingDispatcher chooses which routing handler to call based on the matching route. If no such route exists (e.g. Route.Handler is null, as seen in the diagram) then the request proceeds directly to Step 10.

  7. If a Route Handler exists for the given route, the HttpRequestMessage is sent to that handler.

  8. It is possible to have instances of DelegatingHandler attached to individual routes. If such handlers exist, the request goes to them (in the order they were added to the pipeline).
  9. An instance of HttpMessageHandler then handles the request. If you provide a custom HttpMessageHandler, said handler can optionally return the request to the "main" path or to a custom end point.

  10. The request is received by an instance of HttpControllerDispatcher, which will route the request to the appropriate route as determined by the request's URL.

  11. The HttpControllerDispatcher selects the appropriate controller to route the request to.

  12. An instance of IHttpControllerSelector selects the appropriate HttpControllerDescriptor for the given HttpMessage.
  13. The IHttpControllerSelector calls an instance of IHttpControllerTypeResolver, which will finally call...
  14. ...an instance of IAssembliesResolver, which ultimately selects the appropriate controller and returns it to the HttpControllerDispatcher from Step 11.
    • NOTE: If you implement Dependency Injection, the IAssembliesResolver will be replaced by whatever container you register.
  15. Once the HttpControllerDispatcher has a reference to the appropriate controller, it calls the Create() method on an IHttpControllerActivator...
  16. ...which creates the actual controller and returns it to the Dispatcher. The dispatcher then sends the request into the Select Controller Action routine, as shown below.

  17. We now have an instance of ApiController which represents the actual controller class the request is routed to. Said instance calls the SelectAction() method on IHttpActionSelector...

  18. ...which returns an instance of HttpActionDescriptor representing the action that needs to be called.

  19. Once the pipeline has determined which action to route the request to, it executes any Authentication Filters which are inserted into the pipeline (either globally or local to the invoked action).

    • These filters allow you to authenticate requests to either individual actions, entire controllers, or globally throughout the application. Any filters which exist are executed in the order they are added to the pipeline (global filters first, then controller-level filters, then action-level filters).
  20. The request then proceeds to the [Authorization Filters] layer, where any Authorization Filters which exist are applied to the request.

    • Authorization Filters can optionally create their own response and send that back, rather than allowing the request to proceed through the pipeline. These filters are applied in the same manner as Authentication Filters (globally, controller-level, action-level). Note that Authorization Filters can only be used on the Request, not the Response, as it is assumed that if a Response exists, the user had the authorization to generate it.
  21. The request now enters the Model Binding process, which is shown in the next part of the main poster. Each parameter needed by the action can be bound to its value by one of three separate paths. Which path the binding system uses depends on where the value needed exists within the request.

  22. If data needed for an action parameter value exists in the entity body, Web API reads the body of the request; an instance of FormatterParameterBinding will invoke the appropriate formatter classes...

  23. ...which bind the values to a media type (using MediaTypeFormatter)...

  24. ...which results in a new complex type.

  25. If data needed for a parameter value exists in the URL or query string, said URL is passed into an instance of IModelBinder, which uses an IValueProvider to map values to a model (see Phil Haack's post about this topic for more info)....

  26. ...which results in a simple type.

  27. If a custom HttpParameterBinding exists, the system uses that custom binding to build the value...

  28. ...which results in any kind (simple or complex) of object being mappable (see Mike Stall's wonderful series on this topic).

  29. Now that the request is bound to a model, it is passed through any Action Filters which may exist in the pipeline (either globally or just for the action being invoked).

  30. Once the action filters are passed, the action itself is invoked, and the system waits for a response from it.

  31. If the action produces an exception AND an exception filter exists, the exception filter receives and processes the exception.

  32. If no exception occurred, the action produces an instance of HttpResponseMessage by running the Result Conversion subroutine, shown in the next screenshot.

  33. If the return type is already an HttpResponseMessage, we don't need to do any conversion, so pass the return on through.

  34. If the return type is void, .NET will return an HttpResponseMessage with the status 204 No Content.

  35. If the return type is an IHttpActionResult, call the method ExecuteAsync to create an HttpResponseMessage.

    • In any Web API method in which you use return Ok(); or return BadRequest(); or something similar, that return statement follows this process, rather than any of the other processes, since the return type of those actions is IHttpActionResult.
  36. For all other types, .NET will create an HttpResponseMessage and place the serialized value of the return in the body of that message.

  37. Once the HttpResponseMessage has been created, return it to the main pipeline.

  38. Pass the newly-created HttpResponseMessage through any AuthenticationFilters which may exist.

    • Remember that Authorization Filters cannot be used on Responses.

  39. The HttpResponseMessage flows through the HttpControllerDispatcher, which at this point probably won't do anything with it.

  40. The Response also flows through the HttpRoutingDispatcher, which again won't do anything with it.

  41. The Response now proceeds through any DelegatingHandlers that are set up to handle it. At this point, the DelegatingHandler objects can really only change the response being sent (e.g. intercept certain responses and change to the appropriate HTTP status).

  42. The final HttpResponseMessage is given to the HttpServer instance...

  43. ...which returns an Http response to the invoking client.

Tada! We've successfully walked through the entire Web API 2 request/response pipeline, and in only 43 easy steps!

Let me know if this kind of deep dive has been helpful to you, and feel free to share in the comments! Microsoft people and other experts, please chime in to let me know if I got something wrong; I intend for this post to be the definitive guide to the Web API 2 Request/Response Lifecycle, and you can't be definitive without being correct.

Happy Coding!

15 Fundamental Laws of the Internet

(AKA How To Sound Smart In Your Next Online Rant)

Wiio's Law

What is the internet? The internet is, at heart, a communication tool, a way for disparate people across the globe to spread ideas, opinions, and generally communicate with each other more easily than has ever been possible. Unfortunately, communication is hard.

Finnish academic Osmo Antero Wiio formulated a serious of humorous laws that succinctly explain how communication works between humans; specifically, that it doesn't. The set of laws Wiio created are often summarized as Wiio's Law:

"Communication usually fails, except by accident."

So maybe, instead of being angry that people didn't get what we said, perhaps we should merely be pleased when, against all odds, they actually understand what we are saying.

Kranzburg's First Law of Technology

Melvin Kranzberg was a professor of history, specifically the history of technology (and, apparently, a WWII-era interrogator. Office hours must have been stressful for his students). Kransberg formulated a series of laws about technology and its place in history, most famous of which is his First Law of Technology:

"Technology is neither good nor bad; nor is it neutral."

In other words, technology is not inherently anything; it's value is imposed upon it by whomever uses it. Technology itself has no intrinsic value. Perhaps this is why Apple removed the headphone jack from the iPhone.

Sturgeon's Law

Ever wonder why the vast majority of things on the internet are terrible? So did Theodore Sturgeon, except for everything. Sturgeon was a science fiction and horror writer, and he was appalled that most science fiction of his day was utter trash. Hence he coined Sturgeon's Revelation, which is now more widely known as Sturgeon's Law.

"90% of everything is crap."

Yes, everything. Makes me wonder if he included his own work in that statement.

But it's not all tongue-in-cheek: Sturgeon's law has been cited by noted philosopher Daniel Dennett as one of his critical tools for thinking. So not only is 90% of everything crap, the awareness of this fact is important to be properly aware of critical thinking. Yay for not liking anything ever!

The 1% Rule

The 1% Rule is an adage which states:

"Only 1% of the users of a website actively create new content, while the other 99% of the participants only lurk."

In other words, most people just sit in the metaphorical shadows and read what the 1% write. This is particularly interesting to think about in the context of designing communities like reddit or Stack Overflow, since if only 1% of the people will create content, how do the site owners get the 99% to stick around and read things? Unless you get incredibly lucky, figuring out how to make both the 1% and the 99% happy is very tricky, and only a few sites get it right.

Dickwad Theory

If you don't like swearing, you'd best skip this section. The Dickwad theory was put forth in the online comic strip Penny Arcade, and states:

"Normal Person + Anonymity + Audience = Total Dickwad"

Ever wonder why trolls exist on the internet in exponentially greater numbers than in real life? Dickwad theory proposes the reason: when a normal person received total anonymity and an audience, s/he loses all their inhibitions and promptly starts to act like a total raging asshole. Anyone who has been on the internet long enough has encountered someone who proves this theory, and if they say they haven't, it's because they themselves are proving it.

Dickwad theory is apparently also known as online disinhibition effect, but that's not nearly as interesting a name for this phenomenon.

Godwin's Law

The next few laws relate to how people communicate on the Internet, specifically how they use text. This particular adage is the one law on this list that, most likely, everyone has heard of. Godwin's Law was written by attorney Mike Godwin on a Usenet group in 1990, and it states the following:

"As an online discussion grows longer, the probability of a comparison involving Nazis or Hitler approaches one."

What's particularly interesting about this law is that Godwin himself deliberately and repeatedly posted this law anywhere he could, according to a 1994 article written by him and published in Wired. He specifically calls it "meme engineering" (as he invented the idea of an "internet meme"), and it remains possibly the most successful case of this yet seen.

Poe's Law

There's an inherent problem in trying to communicate via text: the inflection and intonation that is so readily apparent in verbal speech is missing. Consequently, what would be obvious when spoken might be missed when written down.

Poe's Law (named after Nathan Poe, who wrote the original formulation of it in 2005) states the following:

"Without a clear indicator of the author's intent, parodies of extreme views will be mistaken by some readers or viewers as sincere expressions of the parodied views."

No matter how obvious it is that you are making fun of something, unless you explicitly state that you are doing so, someone somewhere will think you are being serious.

The original text of this law cited Creationism, but it has been repeatedly proven to be true for any sufficiently contentious topic (by which I mean: all of them).

Skitt's Law

One of the more obscure laws on this list is Skitt's Law, which states:

"Any post correcting an error in another post will contain at least one error itself."

I'm tempted to think of this as the Law of Glass Houses, after the famous proverb, "Those who live in glass houses should not throw stones." At any rate, Skitt's Law demonstrates an incontrovertible fact about the internet: if you feel the need to correct someone else, you'd best be prepared for someone to correct you.

Law of Exclamation

Punctuation can actually be a tip-off as to whether or not what you are reading is total crap. The Law of Exclamation says:

"The more exclamation points used in an email (or other posting), the more likely it is a complete lie."

An example of this law is found in the novel Reaper Man by Terry Pratchett, one of his Discworld series. In it, a character states that "five exclamation marks [are] the sure sign of an insane mind." Remember this next time you think you need more than one exclamation point (and are not a teenager).

Cunningham's Law

The modern internet owes a lot to Ward Cunningham, a programmer who among other things invented the wiki. He's also known for having his name attached to a particularly keen insight into how questions and answers work on the internet (though he didn't originate this law; his coworker Steven McGeady did). Cunningham's Law is usually written as follows:

"The best way to get the right answer on the Internet is not to ask a question, it's to post the wrong answer."

McGeady even cited a site that relies on Cunningham's invention as the best proof of the truth of this law: Wikipedia.

The Wiki Rule

Speaking of wikis, there's another theory that states that there is a wiki for anything. It's called The Wiki Rule:

"There's a wiki for that."

Yes, that. And that. And even that. If you can think of it, if it has at least one fan out there, there's probably a wiki for it, and some of these wikis can get astoundingly large.

Danth's Law

Ever get into an argument on the internet? Stop lying; of course you have. Have you ever been able to figure out who actually won said argument? Danth's Law gives you this handy tip:

"If you have to insist that you've won an Internet argument, you've probably lost badly."

Because if you'd actually won the argument, you wouldn't need to argue that you did.

Law of the Echo Chamber

Let's be real for a second: in a lot of ways, the Internet has made modern life easier and more accessible, but in some ways the promises of this great web of information simply haven't materialized.

The idealistic goal of the internet was to be democratic, to show us all sides of any possible argument in a non-biased way. Problem is, people are inherently biased, and the internet is run by people, so that bias leaks in. In fact, it leaks so much that more often than not your circle of internet friends is populated by people who subscribe to the same opinions you do.

I therefore propose something I've been calling the Law of the Echo Chamber:

"If you feel comfortable enough to post an opinion of any importance on any given Internet site, you are most likely delivering that opinion to people who already agree with you."

Munroe's Law

There is a corollary to the Law of the Echo Chamber, which I've taken to calling Munroe's Law after the cartoonist who draws and publishes the comic xkcd. A while back Randall Munroe posted the following cartoon, and it has since become something of a meme.

We've all been there. That comic is merely a funny way of stating the following:

"You will never change anyone's opinion on anything by making a post on the Internet. This will not stop you from trying."

Golden Rule of the Internet (AKA Wheaton's Law)

The traditional phrasing of the Golden Rule is "do unto others as you would have them do unto you." Actor and writer Wil Wheaton coined a slightly shorter version which has occasionally been referred to as Wheaton's Law:

"Don't be a dick"

Because sometimes it really is just that simple.

Summary

Many of the laws enumerated above don't apply to just the internet; they apply to life and behavior of humans in general. This is, of course, intentional. After all, the users of the internet are people, regardless of what they want you to think they are.

Did I miss any fundamental laws of the internet that you've found useful? Feel free to sound off in the comments!

Happy Coding!