Why use strong and em over b and i?

One question I see around the interwebs a lot is why strong and em should be used over b and i. If we look at the HTML 4 spec, it lists b and i under the Font style section, and notes:

The following HTML elements specify font information. Although they are not all deprecated, their use is discouraged in favor of style sheets.

The strong and em tags are listed under the Phrase elements section and note:

Phrase elements add structural information to text fragments.

Now that’s all well and good, but what does it mean?

Among other things:

b and i are visual.

What this means is that in a web browser, when the html parser encounters a <b> tag, it knows to bold the font. It’s a physical property, meaning “use thicker ink when displaying this word.” Same with <i> – “skew this so it looks like it’s going really fast” (or something like that). These are tags whose sole purpose is to physically change the display of the text.

Okay. Great.

Well, maybe not. What about when a blind person views a page? The visual properties mean nothing to them. That’s where em and strong come in.

em and strong are semantic

The em tag indicates emphasis and the strong tag indicates stronger emphasis. This could (and usually does) mean italics and bold on a web page. But it also could alert a text-to-speech program to use a different tone of voice when encountering the text. They have meaning behind them, and that meaning means different things to different interpreters.

As noted by the HTML 4 spec, b and i, although not deprecated, should be avoided because not only are they style properties that should be handled in CSS, they don’t have any semantic meaning. Use strong and em in their place.

Building the Castle Windsor Dependency Injection Populator for ASP.NET vNext

As I blogged about previously, I built a Castle Windsor populator for ASP.NET vNext. For this post, I’ll walk through some of the more interesting pieces of it.

Installer

In Castle Windsor, an installer is a class that implements IWindsorInstaller and is used to register all components. It’s not necessary, but it encapsulates the registrations and allows for more organization if you have a ton of services to register. For the Castle Windsor populator, I set up a KServiceInstaller to register the components.

The KServiceInstaller has a constructor that takes IEnumerable<IServiceDescriptor>, which is the list of services to be registered.

public KServiceInstaller(IEnumerable<IServiceDescriptor> services)

When Install is called on the installer, it loops through each service and registers it with Windsor, using either an ImplementationType or ImplementationInstance.

ImplementationType vs ImplementationInstance

The IServiceDescriptor interface exposes ImplementationType and ImplementationInstance properties. If the type being registered is a singleton and has a specific instance that is already instantiated then the service descriptor include an ImplementationInstance. If the type will be instantiated by the DI container, then the service descriptor includes an ImplementationType. Performing a null check will allow you to figure out which one to use, and they should be registered with the Windsor Instance or ImplementedBy registration methods, respectively.

if (service.ImplementationType != null)
{
    container.Register(Component.For(service.ServiceType)
                                .ImplementedBy(service.ImplementationType)
                                .ConfigureLifeCycle(service.Lifecycle));
}
else
{
    container.Register(Component.For(service.ServiceType)
                                .Instance(service.ImplementationInstance)
                                .ConfigureLifeCycle(service.Lifecycle));
}

Lifestyle

There are 3 LifeCycles specified in the vNext DI framework:

public enum LifecycleKind
{
    Singleton,
    Scoped,
    Transient
}

These map to the LifestyleSingleton, LifestyleScoped and LifestyleTransient life cycles in Windsor. Singleton, obviously, means we have one and only one, use it everywhere. Transient means give me a new one every time I ask for one and Scoped means give me a new one per scope, and inside that scope use the same one everywhere. The scope set up here is per web request, so it creates a new one on each request and it is used for the life of the request.

A simple extension method makes it easy to configure lifecycles:

internal static ComponentRegistration<object> ConfigureLifeCycle(
    this ComponentRegistration<object> registration, LifecycleKind kind)
{
    switch (kind)
    {
        case LifecycleKind.Scoped:
            registration.LifestyleScoped();
            break;
        case LifecycleKind.Singleton:
            registration.LifestyleSingleton();
            break;
        case LifecycleKind.Transient:
            registration.LifestyleTransient();
            break;
    }

    return registration;
}

And it’s used as such:

container.Register(Component.For(service.ServiceType)
                            .ImplementedBy(service.ImplementationType)
                            .ConfigureLifeCycle(service.Lifecycle));

FallbackLazyComponentLoader

There are many services in the vNext framework that are instantiated and registered prior to registration of the MVC services and any custom services you use in your app. These aren’t known and won’t be registered by Windsor, so we’ll need to fallback to another IServiceProvider if a request comes in for the service. That’s where the FallbackLazyComponentLoader comes in.

Castle Windsor includes the ability to acquire components as they’re needed, on the spot without registering them first. This is exposed via the ILazyComponentLoader interface, which is what FallbackLazyComponentLoader implements. It exposes a single constructor taking an IServiceProvider:

public FallbackLazyComponentLoader(IServiceProvider provider)

If Windsor encounters a request for a service that is not registered, it will fallback and attempt to resolve it using this fallback service provider:

public IRegistration Load(string name, Type service, IDictionary arguments)
{
    var serviceFromFallback = _fallbackProvider.GetService(service);

    if (serviceFromFallback != null)
    {
        return Component.For(service).Instance(serviceFromFallback);
    }

    return null;
}

WindsorServiceProvider

To use a custom DI framework, you must register a new IServiceProvider. The Windsor populator returns a WindsorServiceProvider which can be registered with the framework:

private class WindsorServiceProvider : IServiceProvider
{
    private IWindsorContainer _container;

    public WindsorServiceProvider(IWindsorContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
         return _container.Resolve(serviceType);
    }
}

When a request for a service comes in, Windsor will attempt to resolve it. If it isn’t explicitly registered it checks the fallback service provider, and if that fails it returns null.

Discourse V1 has been released

As promised by the team, Discourse has just hit V1.0. As Jeff Atwood says the version number is mostly arbitrary, but it shows that the software is ready for rapid adoption in communities everywhere.

Version numbers are arbitrary, yes, but V1 does signify something in public. We believe Discourse is now ready for wide public use.

That’s not to say Discourse can’t be improved – I have a mile-long list of things we still want to do. But products that are in perpetual beta are a cop-out. Eventually you have to ditch the crutch of the word “beta” and be brave enough to say, yes, we’re ready.

They have also unveiled their hosting service, which (I’m assuming) makes it stupidly easy to set up and use Discourse.

I set up Discourse as my comment system and I have been nothing but impressed with it. I would recommend Discourse to anyone needing some sort of discussion community.

Congrats to the Discourse team on the accomplishment!

Progress Indicators are Always a Good Idea

Progress bars. You know them. You love them. They tell you when the computer is going to be done with a task, or when you are going to be done with a task. Sometimes they’re accurate, sometimes not so much. Regardless of accuracy, studies have shown that humans like to know progress:

A friend tries to encourage you by observing “There’s light at the end of the tunnel.” The comment may help you persevere because, with the end in sight, the remainder of the task becomes more pleasant or the prospect of abandoning it more unpleasant. In either case, your friend is trying to influence how you perceive the task to help you complete it. The belief seems to be that long, boring tasks will be experienced as shorter and more interesting, or at least more tolerable, when we can tell we are making progress. This appears to be the rationale of designers who provide feedback to users about their progress.

The light at the end of the tunnel is a powerful force and is one that helps drive most of us to complete our goals. But as the nights get darker and the days get longer, how do we persevere through and not just see the light, but make it out of the tunnel to feel the light too?

For that, we turn to science. Task completion is a feel-good activity, and we become more and more happy as we complete a task. Hugo Liu describes why here:

Because completion is intrinsically rewarding. Neuroscience backs this up. It turns out that when you finish a complex task, your brain releases massive quantities of endorphins. Through the magic of classical conditioning, you come to associate present acts of completion and progress with the pleasure and satisfaction of your past completion-induced endorphin rushes.

The more tasks you complete the more and more you become addicted to that feeling.

Along with completions, we get the same reward from seeing plain ‘ol progress. Even if the end result is far away or even unattainable, feeling like we’re making progress is all that is needed to keep us happy:

penrosestairsShown above is a depiction of the Penrose Stairs, also known as the endless staircase or the impossible staircase. We can see from this vantage point that the stairs really lead to nowhere. However, for the man on the stairs, he may feel like he is getting somewhere. After all, the personal experience would be that of moving forward and upward — the very definition of progress.

In the context of the work environment, you are happier when you feel like you are moving forward and upward.

So what does this have to do with computers?

Well, we can’t physically see progress in a computer – if we start a file copy, we can’t open up the side of the computer and watch it copy. Developers have to build the indicators into the UI so end users know the computer is performing the task. And that’s the important part. Whenever possible, display progress to the user. Whether it’s a file copy, or the number of experience points they need to gain to level up, or a set of steps that needs to be completed users will thank you for knowing when they’ll be done. It will help them complete whatever goal they are trying to accomplish with your software.

Don’t be a Tweek Tweak Programmer

My previous post, Please learn to ask questions, asks developers to start asking more questions and try to understand the code behind many framework tools they use. A sibling of this topic is programming by coincidence. PbC (as it will henceforth be referenced as in this post)* is programming by luck, tweaks and accidental success until perceived correctness is achieved. The Pragmatic Programmer has 2 great examples:

Do you ever watch old black-and-white war movies? The weary soldier advances cautiously out of the brush. There’s a clearing ahead: are there any land mines, or is it safe to cross? There aren’t any indications that it’s a minefield—no signs, barbed wire, or craters. The soldier pokes the ground ahead of him with his bayonet and winces, expecting an explosion. There isn’t one. So he proceeds painstakingly through the field for a while, prodding and poking as he goes. Eventually, convinced that the field is safe, he straightens up and marches proudly forward, only to be blown to pieces.

And an example directly related to software development (emphasis mine):

Suppose Fred is given a programming assignment. Fred types in some code, tries it, and it seems to work. Fred types in some more code, tries it, and it still seems to work. After several weeks of coding this way, the program suddenly stops working, and after hours of trying to fix it, he still doesn’t know why. Fred may well spend a significant amount of time chasing this piece of code around without ever being able to fix it. No matter what he does, it just doesn’t ever seem to work right.

Fred doesn’t know why the code is failing because he didn’t know why it worked in the first place. It seemed to work, given the limited “testing” that Fred did, but that was just a coincidence. Buoyed by false confidence, Fred charged ahead into oblivion. Now, most intelligent people may know someone like Fred, but we know better. We don’t rely on coincidences—do we?

We don’t. Or, at least, we shouldn’t. The worst way to program is to program by tweaking values until something appears to work. I’m calling it Tweek Tweak programming**:

var name = "DaveZych"
var firstName = name.Split(0, 4);
var lastName = name.Split(4, name.Length);

Nope, didn’t work.

var name = "DaveZych"
var firstName = name.Split(0, 4);
var lastName = name.Split(4, name.Length - 4);

Eh, still no.

var name = "DaveZych"
var firstName = name.Split(0, 4);
var lastName = name.Split(3, name.Length - 4);

Yeaaaahhhhh, it worked once. Nailed it.

How many times have you seen a developer fumble their way through code like this? Too many? Yeah, me too. Chances are the code happened to work for that one test run but will fail the other 95% of the time and especially when the test data changes. This is a direct path to a very unmaintainable codebase.

The Pragmatic Programmer has tips on how to not program by coincidence and instead program deliberately:

  • Always be aware of what you are doing
    • Know the requirements. Know the tools. Know the goal. Know when to take a step back and think about what you’re doing
  • Don’t code blindfolded
    • Don’t be a Tweek Tweak programmer. Make sure you understand your requirements and the technology you’re using
  • Proceed from a plan, whether that plan is in your head, on the back of a cocktail napkin, or on a wall-sized printout from a CASE tool
    • Before starting, think about what you’re doing. Write it down if it helps (it almost always does)
  • Rely only on reliable things
    • Make sure that code doesn’t work just because the circumstances were correct
  • Document your assumptions
    • If you assume that all dates coming back from an API are in EST, document that so anyone having to maintain the software knows why it’s expecting that. Just watch out how many comments you use
  • Don’t just test your code, but test your assumptions as well
    • Run a ton of queries against the above mentioned API and confirm the dates comes back as you expect all the time, every time
  • Prioritize your effort
    • Focus on the important parts because those are generally the hardest and will take the most time
  • Don’t be a slave to history
    • Just because something was done a certain way before does not mean you should also do that, nor does it mean it was correct in the first place

Keep these in mind as you make your way through the programming minefield. Don’t be a Tweek Tweak Programmer! And, as always, THINK!


* Apparently that was the last time it was referenced.
** Both because of the act of tweaking values as well as the paranoia the developer feels regarding the stability of the code afterwards

Learn to ask more questions

I recently installed sod in my backyard along with an automatic sprinkler system. I performed all the work myself (with the help of some friends and family when necessary, of course) and that included laying the sprinkler pipe and hooking it up to the copper mainline.

I didn’t know much about sprinklers at the time I started – I new it was PVC, and you used the glue and stuck ‘em together and water was carried through them to the sprinkler heads. But installing a system requires a bit more knowledge, so I researched all of it until I felt comfortable enough to do it. I learned about valves, timers, how to sweat copper and test for leaks. I installed the system on my own and it’s been running perfectly since. All of this was done because I wasn’t afraid to ask a question and figure out the answer myself.

All too often I see young developers take abstraction at face value. They have no idea what’s going on under the hood of a framework and have no idea why their code works. Abstraction is great until it starts to hinder your maturation as a developer. So many problems I see people run into can be solved by a better understanding of the underlying issue at hand. This applies from technical challenges to business rules to life itself.

You don’t solve this by just gazing into the stars and wondering. You take that wonder a step further by investigating and applying it towards gaining knowledge. I wondered how to install a sprinkler system, and now I have a lawn that gets automatically watered once a week.

Don’t just assume. Don’t be blind. Wonder why things work the way they do. Ask. Research. Learn. As Pragmatic Programmer Tip #8 says:

Invest Regularly in Your Knowledge Portfolio

When you see something you don’t know, question what it is and how it works. I’m calling on all people to ask more questions. Combating nescience is how you advance your skills and suck less every year. Please, don’t just walk on top of abstraction, dig a little and uncover the mystery.

The investigation of a site crash

When I woke up this morning I noticed by site had crashed with the following error:

Error establishing a database connection.

Awesome. What a helpful error message. WordPress is basically saying:

shrug

Thanks WordPress. I ssh’d into the server to see if I could figure out what was wrong myself. Since this was complaining about a database connection, my first step was to check the status of mysql:

$ sudo netstat -tap | grep mysql

Nothing. Ruh Roh! Time to attempt a restart…

$ sudo /etc/init.d/mysql restart

… and the site came back up. Phew! That was easy.

But why did it crash in the first place?

Since MySql was the cause it made sense to me to first check the sql logs. I opened those up and found nothing. Based on the recommendation of Google I then searched the syslogs, specifically for memory:

$ sudo grep memory /var/logs/syslog
  Aug 19 10:56:12 localhost kernel: [10664646.817182]  [] out_of_memory+0x414/0x450
  Aug 19 10:56:12 localhost kernel: [10664646.819979] Out of memory: Kill process 4803 (mysqld) score 104 or sacrifice child
  Aug 19 10:56:12 localhost kernel: [10664646.831686]  [] out_of_memory+0x414/0x450
  Aug 19 10:56:12 localhost kernel: [10664646.833365] Out of memory: Kill process 4826 (mysqld) score 104 or sacrifice child

Aha! It looks like MySql ran out of memory and the server killed it. Okay, now on to the next question… Why?

Well… it ran out of memory, that’s why. (Duh.) One way to alleviate this is to create a swap file, which it turns out I forgot to do when I originally configured this server. Without that swapfile MySql had nowhere to overflow excess data to and subsequently crashed. I created and enabled a swap file:

$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
$ sudo mkswap /swapfile
    Setting up swapspace version 1, size = 262140 KiB
    no label, UUID=XXXXX
$ sudo swapon /swapfile

After creating the file everything has been running great (so far).

Next Steps

Had I not been a narcissist and checked my own website I probably wouldn’t have noticed it was down for hours, perhaps encroaching on days. My next steps are to look into monitoring software – something that alerts me when there’s a problem, or even a potential problem before it’s even there. One I have found that does just that is Nagois, or it’s stepchild Icinga.

Discourse: The way software should be

As you may have heard, I recently set up Discourse as my blog commenting system:

I have to say I could not be more impressed with it.

Setup

The setup of Discourse is ridiculously easy. Like, stupid easy. I’m pretty sure my 9 month old daughter could do it and she smashes bananas in her ear. Using the Docker setup, they say you can set up Discourse in 30 minutes – I think they’re underestimating us users. From scratch it took me about 20 minutes, and that includes setting up a Mandrill account and the Digital Ocean droplet (this is also a credit to Digital Ocean’s ridiculously easy droplet setup). Other than doing some minor configuration the docker image basically runs itself.

You can also do everything manually if you’re crazy enough to not use the Docker setup. I haven’t tried it so I can’t comment on that setup, but it doesn’t seem like it’s that big of a deal.

Updates

The update process is even better. The system continuously checks for updates, and it sends an email and alerts you in the admin section when an update is available. The updates are all one-click-installs and are painless.

The best part is that they come straight from Github. When a new release is ready, they create a tag in Git which signals that there is an update available. Just think about that for a second. All they have to do is run git tag -a vX.X.X* and that signals to all Discourse installations that an update is available. They don’t have to generate patches or release packages or self host downloadable binaries. Just a tag. It’s an ingenious way of providing updates that is incredibly effective.

Usage

There’s not a whole lot to cover here. The whole user experience of Discourse is fantastic – everything’s async and even though it’s still beta software I haven’t run into any bugs. Their description of the application is (emphasis mine):

Discourse is a JavaScript application designed for the next 10 years of the Internet…

and that’s the way the web should be.

Open Source

I was debating on whether or not to include this section but (obviously) ultimately decided to. I’m a rather big proponent of OSS but saying that it’s the way software should be would be a little presumptious of me. There are many great systems that are not only closed source but need to be closed source. Github is a great example – they’re system’s goal is to help developers share code yet the system itself is closed source because it’s easier to sell when closed.

But Discourse’s goal and mission statement are different.

Use the principles of open source software and “let’s make the fabric of the web better for everyone” ideals. Like WordPress, we plan to be the best possible host and service provider for our own software, and grow into an entire ecosystem.

OSS is engrained in their existence and the benefits of this are numerous:

  • Developer ecosystem – Creating a strong developer community is almost essential to the life of software, and that includes both accepting pull requests for fixes and having a strong plugin system. Instead of exposing a plugin API with some shoddy documentation, the code is the API.
  • Bug reports – What better place for users to file bugs than right alongside the code?
  • Living, breathing system – Having your code repository out in the open allows people to monitor progress and see the software come together. They see life.

If you look at those points, overall it’s the accessibility that open source gives that really drives the software. Accessibility to users and developers.

I have to say that I’m thoroughly impressed with Discourse. It’s the WordPress of forum software and that’s a great thing. In my eyes, it sets the standard of what web software should be and I think we should all follow in their footsteps.


* It looks like they don’t used signed tags which surprises me a little bit.

Specifying package dependency versions in ASP.NET vNext

This post was inspired by this question on StackOverflow. Noel asks:

At the company I work at we do the following when we need references to third party dlls in our projects:

  • Use nuget to get package
  • Pull dll’s out and create a “lib” folder and add the references here
  • this lib folder is added to git so other team members have all references when they do a pull from git
  • Reference dll’s stored in lib folder in our project
  • We do this to have full control and know exactly what references we are using.

My question is how is this achieved when using vnext and can we continue to do it this way?

Have watched “INTRODUCING: The Future of .NET on the Server” and it seems you list all dependencies in project.json file and when you do k restore it will go and download all based on feeds in nuget config file

New to ASP.NET vNext is the project.json file. That is the new configuration file which (as far as I know) is replacing the current web.config and .csproj files. Among other things you specify your dependencies in that file, and they are resolved by Nuget and the K Package Manager. The K Package Manager is run either automatically by Visual Studio or manually at the command line by running kpm restore.

Name/Value Pairs

The project.json file is just a json file, meaning you specify everything in Name/Value pairs. Dependencies are specified by the Package: version syntax, where the version can be a:

  • Specific Version
  • Latest Version of a specific set
  • Latest Version

Examples

In my fork of the Dependency Injection repository I have a specific version of Castle.Windsor specified:


"dependencies": {
    "Castle.Windsor": "3.2.1"
  },

If I wanted, I could specify the latest version by specifying no version at all:


"dependencies": {
    "Castle.Windsor": ""
  },

Or, if I wanted the latest patch of version 3.2 I could use a wildcard (*):


"dependencies": {
    "Castle.Windsor": "3.2.*"
  },

No more lib folder!

There is no more reason to have a special lib folder in your repository! During active development of your project you can specify a wildcard to always stay up to date. Once it’s time to release, you can lock down the version to a subset or a specific patch to ensure your application is using a known commodity.

This is also very helpful with your own libraries as well. If you have some class libraries that your applications reference, you can set up a custom Nuget feed and automatically have your applications get the latest versions of your own code. Neat!

Simplicity requires complexity

A major goal of a programmer is to try to map a complex analog world in a digital form. It’d be easy to follow in complexity’s footsteps and provide shoddy solutions to these problems. We have to remember, though, that simplicity is essential to the success of an application.

Jack Dorsey, founder of Twitter, also founded Square, which is a service that allows anyone to take credit card payments via their phones. The problem is complex – allow anyone, anywhere to take digital payment from someone else. He took that complex problem and provided a simple, elegant solution:

So we have built the simplest way to accept credit cards. It’s a little tiny device that we give away for free, and you just download some so wars from the app store and plug it in to your mobile phone or iPad and suddenly you can take credit cards. So if you’re a tax accountant or a lawyer or doctor or even a hair stylist, you can now accept credit cards.

Square has ballooned into a massive company and it’s all due to the ease of use of their app. You plug a free device into your phone and start swiping cards. That’s it. Had they charged for the device and had complex billing rules the company would be no where near as big as it is today. Simplicity fuels them.

Enter the Laws of Simplicity

The Laws of Simplicity

John Maeda wrote about the 10 Laws of Simplicity which are a fantastic intro to simplifying design and are relevant in many more markets than just computer science. Although all 10 laws are good, my favorite is definitely Law #5: Differences:

Simplicity and complexity need each other. The more complexity there is in the market, the more that something simpler stands out.

Which he follows up by saying:

Nobody wants to eat only dessert. Even a child that is allowed to eat ice cream three meals a day will eventually tire his sweet tooth.

I have this same argument with my wife (although not about dessert (okay, also about dessert)). She always says how she would love to live in Hawaii; my response is always But where would we vacation? Too much of a good thing is a bad thing, and simplicity is a good thing.

Humans need contrast in order to realize what’s good and what’s bad. My mom once told me that not everyday can be a good day. You need the bad ones to truly appreciate and acknowledge the good ones. The same goes for complexity and simplicity.

Employing simplicity with complexity

John implies that you have to compare your solution to complexity in the market and I agree with him that it is important. I would argue, though, that complexity within your application is equally important. One way to do this is to make things you want your users to do easy and things you don’t want them to do hard.

GitHub employs this technique very effectively. For instance, to render a nice readme about your repository you just include a readme markdown file in the root of the repo. Simple. To delete a repository, however, you must go through the settings find the delete option and type in the full name of the repo. Much more complex than the readme.

Always strive for simplicity, but remember to always pepper in a little complexity with it. It will help users remember why they use your app in the first place.