Category Archives: Language

I Was Wrong About JavaScript and Responsive Design

Earlier this year I wrote a blog post about JavaScript and why I thought it was doomed; I also wrote a blog post about responsive design and why I thought it was a waste of time.

To be fair, I didn’t completely bash either technology, but I also didn’t have very many kind words to say about JavaScript or responsive design either.

It turns out that shortly after writing those articles, I found myself, ironically, working much more with JavaScript and having to use websites from my mobile device that were not created with responsive design techniques.

I consider myself to be pretty open-minded, especially when it comes to technology, but in both of these cases, I was being a bit narrow-minded and I think it is important to be willing to admit when you are wrong.

Fotolia 32796723 XS thumb I Was Wrong About JavaScript and Responsive Design

First let’s talk about JavaScript

Dear JavaScript, I’m sorry I said that you were ugly and that you would die soon.  I realize that you might not be the most attractive programming language ever created, but like troll dolls or the furby, you have a special kind of beauty that I’ve since learned to appreciate.  And, as for predicting your death, well, it does seem that you are still in the prime of your life, and while everything eventually dies, even programming languages, it isn’t nice to remind people of their mortality.  So, for both of those offenses, I am truly sorry.

On a more serious note, it seems that pretty soon after writing up that article I ended up creating several Pluralsight courses in which I was doing quite a bit of JavaScript development.

By doing this, I actually discovered that the ubiquity of JavaScript was actually very valuable and that it wasn’t as hard as I imagined to create fairly complex JavaScript based applications.

Let me explain a bit further.

After having created several applications using several different platforms and technologies with JavaScript, it became clear to me that the language itself was very flexible and JavaScript’s ability to easily treat data like code, through the use of JSON, was very useful.

At first, when I was just creating web applications with JavaScript, using it as a scripting language to do UI automation, this flexibility seemed to get in the way and make things more complicated than I liked.  I still think that JavaScript can be quite messy in a traditional web application that posts back to the server.

But, when I started using JavaScript to create Chrome plugins, and develop Single Page Applications, this flexibility became extremely useful, because I could basically create exactly what I wanted without a bunch of ceremony around it.  I started to see JavaScript as something I could use to build a more specific API that was specific to the problem domain I was solving.  I also saw that in many cases, for example Meteor, someone else was already doing this for me and I could just follow the conventions they laid out.

I still think there are some things about JavaScript that need to be improved.  But, overall, I have learned to stick to the good parts as much as possible. More importantly, I have learned that knowing the core concepts of JavaScript and programming with JavaScript has allowed me to build a good base which I can bring to many different platforms and environments.  Even though different programming environments may define their own conventions for using JavaScript to create an application or extend one, it is relatively easy to adapt to those conventions once you are familiar with some of the core parts of JavaScript that carryover everywhere.

I also have grown to like the prototypical nature of JavaScript and other prototypical languages like Lua.  I’ve always been a big fan of statically typed languages, and I still am, but I can also now appreciate some of the patterns that only a prototypical language allows which can really allow you to do quite a bit with just a little code.

Onto responsive design

I actually had a very enlightening conversation with a gentleman on Twitter, who really helped me take a second look at responsive design and why it was more useful than I thought.

One of the biggest ways that he shifted my thinking about responsive design was by helping me to realize that it isn’t just PC, mobile phone, tablet, but that there were all kinds of forms factors and kinds of devices that a web page should look good and function well on today.

mobile devices thumb I Was Wrong About JavaScript and Responsive Design

It also seems that right after I had written that article that I ended up having to use my phone for doing web based things much more than I had before then.  I quickly became frustrated with websites that did not implement some kind of responsive design and found myself smiling when I happened upon a website that was mobile friendly and altered the UI to make it much easier to use on a phone.

When I thought about it more, it turned out that I was responding instinctively to the fad of responsive design, but not realizing the actual value that was there.  I probably have a tendency to backlash hard against technology trends that seem to be fads or trendy.  Sometimes, I do get a bit overzealous in doing so and don’t realize that even though many people are ignorantly worshipping some new technology or trend, there are many others who are wearing the latest techno-fashion, because it really is good and useful.

By the way, I found this book, to be a good resource for learning about responsive web design, if you are looking to get a bit more understanding of it.

I still don’t think it is healthy or smart to jump all into responsive design without a good reason for doing so or having a good understanding of the value it will bring.  (Responsive design is not for everyone.)  But, I do think responsive design is a good solution and should be implemented in many more cases than what I had originally thought.  I can see a large amount of value in making an existing site responsive, because it can attract more business and make it easier for existing customers to give you money or use your product.

I even find myself wishing that my website was more responsive.  This blog has a default mobile theme, but I am wondering how much mobile traffic I am losing out on, or how many opportunities to convert that traffic to customers to one of my products I am also missing out on, because I am not presenting the information on this blog in the best way I can for a smaller device.

A good lesson

It turns out being wrong about these two technologies was a good lesson for me, because it helped me realize that even though I like to think that I have eliminated most of my technology biases, there are still plenty that exist.

One of the key things that I’ve always said about this blog is that I am not going to stop from saying something because I am not 100% sure of what I am saying.  What I mean by this is that I will give my view to the best of my knowledge, but that view is subject to revision.  There really is no need to hold onto a viewpoint that is wrong, once you realize it is wrong and it is ok to be wrong sometimes.  We all have to be willing to grow and learn along our journey.  If we want to be able to improve, we have to be willing to allow ourselves to be wrong and to be ok with that.

There are so many posts that I have written for this blog that I wouldn’t agree with 100% today and that is because my knowledge and experience is changing.  I really wouldn’t want it any other way.  If I agree 100% with what I wrote about last year or the year before, I would be 100% the same person I was back then, so I wouldn’t be growing and improving.  I’d rather be wrong sometimes and grow than think I am right all the time and stagnate.

What Programming Language Should I Learn?

I often get asked by beginner programmers what programming language they should learn.

This, of course, is a tough question to answer. There are so many different programming languages today that a new developer, or even a seasoned developer, wishing to retool his or her career, could learn.

I’ve actually tried to answer this question before in a YouTube video, but I want to revise and refine my answer a bit here, because some of my views have changed and I’d like to give a bit more detail as well.

112213 0123 WhatProgram1 What Programming Language Should I Learn?

The wrong question to begin with

It turns out that what programming language you choose to learn is not actually all that important

Things have changed quite a bit from back when I first started my career in software development. Back when I first started out, there were much fewer choices of programming languages and there were much fewer resources available for reference. As a result, the choice was much more important.

For example, I started out learning C and then C++. At that time, it took quite a bit of work to master the language itself and to understand all of the standard libraries that were available. A good C or C++ programmer back then had a very in-depth understanding of every nook and cranny of the language and they needed this knowledge, because of two main reasons.

  1. References were not as widely available, so figuring out a syntax or library available involved flipping through a huge book, rather than just typing some keywords into Google.
  2. Programming, in general, was done at a much lower level. There were far fewer libraries available to be able to work at higher levels, so we spent more time working with the language itself and less time working with APIs.

Contrast that with the programming environment of today, where not only is information widely available and can be accessed with ease, but also there are a large number of programming languages that we effectively use to program at a much higher level due to the vast amount of libraries and reusable components available to us today.

In today’s programming environment, you tend to not need to dive as deeply into a language to be effective with it. Sure, you can still become an expert in a particular programming language, and it is good to have some amount of depth in at least one language, but you can literally learn a new language in less than a week and be effective with it almost immediately.

Now, before your alarm bells go off and you write me off as crazy, let me explain that last sentence in a bit more detail.

What do you mean you can learn a programming language in a week?

What I mean by this is that once you understand the basic programming constructs available in just about all programming languages, things like conditionals, loops and how to use variables and methods, you can take that same knowledge to a different programming language and just learn how to do those same things in that language’s syntax. In fact, most IDEs today will even help you with the syntax part, making your job even easier.

If you are already fluent in multiple programming languages, you probably agree with what I am saying, but if you have only ever learned one programming language or none at all and are looking to learn your first programming language, you might be a little skeptical. But, take it from someone who has learned and taught programming languages which I have learned in a week, the basics are pretty much the same.

Check out this book which basically deals with this exact subject, Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages.

Now, if you are just starting out, it is pretty unlikely you’ll be able to learn a whole programming language in a week. This brings us to the question, you may be asking yourself…

So, what programming language should I learn then?

Hold up. I’m still not quite going to answer that question. Because, it still isn’t quite the right question.

Instead of getting hung up on what programming language you want to learn, you should instead ponder what you want to do.

Learning by doing is the most effective way to learn, especially if you are doing something you have an interest in or is fun to you.

So, I always start new want-to-be developer out by asking them what they want to build.

Do you want to build an Android application? How about an iOS application? A web page? A game?

First, figure out the answer to this question and then let that answer guide you to choose the technology and programming language you will use to achieve that goal.

Don’t worry so much about which programming language or technology is most valuable. You can’t make a wrong decision and regret it later, because it won’t take you much time to retool later if you need to. Once you have the basics down and have actually used a programming language to build something, you’ll find that doing it again will be much easier.

112213 0123 WhatProgram2 What Programming Language Should I Learn?

I like to encourage new developers to write a mobile application—especially an Android application.

Here are some reasons why:

  • A complete Android application can be built by a single person. Creating a complete application will really help you to feel confident about software development and is one of the best ways to really learn to code. I spent a good deal of my early career only being able to create bits and pieces of things, and it was frustrating, because I never knew if I could really “code.”
  • By learning Android, you learn Java and how to use libraries and APIs. This will give you a good programming language to start with and you’ll get some valuable experience with APIs.
  • Google gives you some free help and makes things pretty easy to learn. Since Google really wants you to create Android applications, they have put quite a bit of work into creating easy to use tools and tutorials to help you be successful quickly. (I’ve also created some tutorials, which you can watch at Pluralsight here as well.)
  • You can actually make money while learning and teach yourself a very valuable and upcoming skillset. Not only can you sell your Android application or monetize it in some other way, but you will be learning a complete set of software development skills for a platform that is in very high demand.

Aha! So Java it is then?

No, not exactly.

If you had to press me hard for a programming language suggestion for someone just starting out, I would actually suggest JavaScript.

It is no secret that I have a sort of love / hate relationship with JavaScript, but I would be a fool, and doing you a disservice, to tell you that it is not one of the most valuable programming languages to learn today.

JavaScript may not be the most pretty or elegant language, but it is everywhere and it appears that despite my best efforts to stop it, it will continue to grow and spread for at least quite some time.

If you learn JavaScript, you’ll be able to create applications in many different spaces. Mobile, web, and even robotics can be programmed using JavaScript. And, although I was quite skeptical at first, HTML5 game programming with JavaScript is actually quite good. I created a Pluralsight course on creating an HTML5 game using JavaScript, and I have to admit that I actually really enjoyed the experience.

Summing it up

So, just to be clear. My recommendation is that you focus on what you want to build and let that guide your technology choice, with a slight biased toward Android development, because of the reasons I outlined above. But, if you absolutely want to choose the most valuable programming language to learn, at least at the time of writing this post, it is definitely JavaScript. Like or hate it, it is used everywhere.

I’m actually working on some products to help developers manage their careers and lives better which will cover topics like this one a bit more in-depth. If you are interested in receiving some updates when I publish an interesting article or video, or when I launch some of those products, feel free to sign up here. Don’t worry, I won’t spam you. J

Practical IoC With ASP.NET MVC 4

Just published my latest Pluralsight course: (IoC MVC 4)

Practical IoC With ASP.NET MVC 4

I had many developers asking about a more practical IoC course that shows how to actually use IoC in a real application, so I created this course.

2013 08 27 10 19 08 thumb Practical IoC With ASP.NET MVC 4

Here is the course description:

At first, Inversion of Control (IoC) is a difficult concept to understand. Even after understanding what IoC is, a developer must learn to apply the concepts of IoC and IoC containers to a real application in order to use it effectively.

In this course, John will show you how to use the Unity IoC container in an ASP.NET MVC 4 application to use dependency injection on controllers, filters, views and more. You’ll start off by learning the basics of IoC containers, how they work and why they are important. As well as, learning about how internally ASP.NET MVC 4 creates controllers and views.

In order to understand practically how dependency injection works (the core function of IoC containers) John will walk you through manually doing dependency injection in ASP.NET MVC 4 using your own custom controller factory.

After you have done things manually, you’ll see how to add the Microsoft Unity IoC container to your MVC 4 application to do dependency injection automatically. Essentially you’ll see how it is able to give us more flexibility and reduce the custom code we need to write.

John then takes things even further by exploring some advanced dependency injection techniques using Unity to inject views and filters. He’ll also cover some of the advanced features of the Unity IoC container.

Finally, you’ll take a tour through some other popular .NET IoC containers and see how to get them working in our ASP.NET MVC 4 application. After taking this course you will be equipped with the skills and knowledge you need to build real applications using Inversion of Control and dependency injection.

How Religion Destroys Programmers

I discovered something about myself—I have an amazing gift to always make the very best technology choice.

Fotolia 53501567 XS thumb How Religion Destroys Programmers

No really, it is quite amazing.

When I look back at my development career, it seems to me that every programming language I was using at any given time was clearly the best one.

The same goes for frameworks and even operating systems.

Yes, I have this amazing ability to pick from the vast ocean of technologies, without even trying them all out, the very best one, and to vehemently defend my choice.

Perhaps as you’ve been reading this, you’ve discovered you have this uncanny ability as well?

Most developers are religious about technology

It’s true.

Don’t be ashamed, you are not alone.  Myself, and just about everyone else, is with you.

Fotolia 52594846 XS thumb How Religion Destroys Programmers

Some of use are recovering from our self-imposed brain washing.  Others of us are blissfully unaware of our predicament.  But most of us have at least one religion we’ve managed to craft ourselves.

It is perfectly natural because most programmers got into the field of software development because they were passionate about it.  Anything you are passionate about is likely to cause you to develop some highly charged opinions.

Take sports fans for instance.  I’m not really much of a sports fan myself, but I know many fans of all different kinds of sports that religiously believe their team is the best despite all the evidence to the contrary.

This defense of our own choices and ideas is core to human nature.  It is easy for us to adopt a new idea but we religiously defend the ones we have without needing much evidence to back it up. The problem is we tend to tie up our ideas about things with our identity and even our value as human beings.

It takes some deep soul searching, but it you look within yourself you’ll probably find that you can make a list of the best operating systems, programming languages, frameworks and so on.

Ignorance is not bliss

The problem with this self-imposed religion is that our technological religion blinds us from the truth.

I spent countless hours arguing about why Macs sucked so much before I had even really used one.  Ironically, I am writing this post on a Mac right now, but I am using Windows Live Writer which I am accessing through remote desktop.  Oh, and this blog post, well, it is actually hosted on an Ubuntu Linux server in the cloud on a PHP application you may have heard of called WordPress.

My point is, most of us vehemently will argue that our technology choice is the best without even having really tried the alternatives.

It seems ludicrous when you think about it clearly, but I still catch myself doing it even today.

When I look within myself to honestly ask the question “why,” I find that most of my motivations come from a combination of pride in what I have learned and accomplished and a fear of what I don’t know.

I find that it is much easier to dismiss a technology that I don’t know as “garbage” or “worthless” than it is to take the time to learn about it and see why others like it so much.  As they say, one man’s garbage is another man’s treasure.

The problem with thoughtless religion

I don’t need to tell you that mindless religious zealotry is a destructive force in our world.  You only need to go to your favorite national news web site or look in any history book to see that is the case.

Fotolia 53739553 XS thumb How Religion Destroys Programmers

But, while not too many programmers will draw swords over PHP vs C#—although I have been accused myself of throwing a chair in a similar dispute, a litigious and quite false accusation which I protest strongly to this day—many developers are quite willing to argue loudly about their opinions and even brashly tear down the works of others as I am sure you have seen if you have spent much time on the good ol’ interwebs.  I got a nice taste of this bitter water myself when I had the gall to actually post something negative about everyone’s bastard child of a language that was discovered to have royal blood after some years of abuse, JavaScript.

So, while we may think our ignorance isn’t harming anyone and that they deserve it anyway because they are clearly wrong, the truth is, there is quite a wake of destruction that our ignorance can leave behind us.

I look back on my own past and I am embarrassed that I harassed Perl developers to the degree that I did, completely discrediting their work and ignorantly pushing my holy statically typed C-based languages as their one and only savior who could cleanse them of their filth.

But more than anything, I realize that I hurt myself.

Stop hitting yourself, idiot!

The biggest growth in my career came when I was looking for a job doing C# development and found a really good opportunity to act as a technical architect for a project written in Java.

I was quite torn by the decision.  In my heart I knew that Java was bad and evil.  I knew that because Java lacked properties like C# and required the use of manually created getters and setters that everyone writing Java code was clearly an idiot.

I almost didn’t take the job, but I decided that the pay was too good to pass up and that I would suffer through this awful experience like a prisoner of war until one day my Microsoft would rescue me.  I thought I would at least get to apostatize some filthy Java writing scoundrels.

Well, it turned out that after a couple of years of mentoring developers on writing good Java code and unit testing, I realized that not only was Java not so bad, but there were some actual merits of the language and Java frameworks that could be appreciated.

More importantly though, I began to realize that my past code bigotry had closed quite a few doors on my face.  It began to occur to me that perhaps all of my technology choices in the past were not necessarily the best.  I began to start thinking that there wasn’t actually all the much difference between many of the most popular technologies.

I began to realize that understanding a wide range of technologies and programming languages made me much more valuable than ignorantly subscribing to my own religion about a particular technology that I happened to choose.

I found that my own understanding of individual technologies increased rapidly, because instead of just “eating what I was fed,” I could use my brain to compare and contrast differences between programming languages and technologies which left me with a deeper understanding of all of then.

I was rudely reminded of my own shortcomings that still exist in this area when I recently converted my blogs over to a Linux server in the cloud from Digital Ocean.

I was predisposed to choose Windows technologies for deploying web applications, but it was pretty hard to argue that a complete Linux server in the cloud that performed extremely well for $10 a month was not a good choice.

My point in all this is to say that being closed-minded about technology choices only hurts yourself in the end and severely limits your personal growth as a developer.

(Here are two good books to break down those barriers: Seven Languages in Seven Weeks and Seven Databases in Seven Weeks.)

There is no “best”

I’ll finish up this post by imploring you to believe me when I say “there is no best technology or programming language.”

I’m not going to insult your intelligence by saying that each language has a purpose for a different situation because the truth is much deeper than that.

After creating over 40 Pluralsight courses on a very wide range of technologies and programming languages, I’ve discovered a few truths.

The truth is that there are multiple great ways to do the same thing using different tools and different technologies.

The truth is that all programming languages and technologies have big mistakes and weaknesses in them.

The truth is the more you learn about different technologies, the more you will find that at the core most things are pretty similar.  What I mean by this is that most of the core concepts about writing software apply regardless of technology choice or programming language syntax.

You’ll also find, as I have, that if you are accepting about others technology choices and are able to admit your own ignorance and learn from it, you’ll find helpful friendly people willing to teach you what they know, everywhere you go.

If you found this post useful–or at the very least entertaining–sign up here and join the thousands of other Simple Programmers out there.  Also, I’m still preselling my complete package on How To Market Yourself as a Software Developer for a limited time.

(Side note: you may think that I am a big hypocrite with this post, since not too long ago I claimed that C++ was not back and JavaScript was doomed.  I believe what I said in those posts does hold true and I don’t think it is contrary to what I am saying in this post.  It is possible to have actual critical opinions of technologies you have actually used.  You don’t have to like everything.  My point is that, even though I dislike C++ for many of today’s programming problems and I feel that JavaScript is not the most elegant language for the web, I do recognize that both of these languages have their merits and that they are valid choices in many situations.)

Getting Started With Google’s Dart Language

I was a little skeptical of the Dart language when Google first announced it.

When I looked at the syntax of the language I thought that it didn’t really seem to offer anything new.

Why create another language that is not very different than what we already have?

How is this actually much better than JavaScript?

But after having worked with Dart now for quite awhile and producing a Pluralsight course on Dart, I’ve completely changed my mind.

The Dart language is awesome!

What makes the Dart language so awesome is all the little subtleties the language designers added to the language, not any major new concepts or ideas.

When I started writing Dart code it felt exactly right.  It felt like all the little annoyances that I had with languages like C#, Java and JavaScript were removed by the Dart language.

In fact, the real beauty of Dart is that if you already know C# or Java and JavaScript, you’ll probably be able to learn enough about the Dart language to be productive in Dart in less than an hour.

Before I show you just how easy it is to get started, let me briefly tell you what the Dart language is:

  • Object oriented.  Everything is an object including primitives and nulls
  • Optionally typed.  You can add type annotations which static checking tools can use to help you find errors in your code, but you don’t have to use them.
  • Interpreted.  Dart is run in a VM, but it is not compiled first.  Round-trip time for making changes is very short.
  • Compatible with JavaScript.  You can compile your Dart code to JavaScript and run Dart applications in any modern browser.
  • FAST!  Dart is very fast, much faster than JavaScript in just about every test.

Some cool language features that I like about the Dart language:

  • Mixins.  Instead of using inheritance, you can use a mixin to add functionality to a class without directly inheriting from another class.
  • Isolates.  Instead of threads, the Dart language uses isolates for concurrency.  Isolates can’t actually share any memory, they pass information though messages.  It is very hard to shoot yourself in the foot.
  • Simplified built-in types.  Numbers can be either int or double, and you can just use num, if you don’t care.  Lists and maps can be declared as literals.  An array is just a special case of a list.
  • Functions are first-class objects.  You can pass them around just like any other object.  There is even a lambda-like short-hand for creating a one-liner function.
  • Top level functions and variables.  Don’t want to put a function or variable in a class?  Good, you don’t have to.  In the Dart language, you can declare them anywhere you want.
  • Simplified classes.  There is short-hand for declaring constructors that assign parameters to class members.  Class members don’t have protected, private, public.  Member variables are automatically properties.
  • String interpolation.  No more string format methods, just use the $variableName in a string to have its value expanded.

Getting setup with the Dart language

Ready to get running in 5 minutes?

Ok, read on.

Step 1: Go to http://dartlang.org and click “Get started.”

2013 06 16 11 12 28 thumb Getting Started With Google’s Dart Language

Step 2: Download Dart (64-bit or 32-bit.)  Unzip the file and copy the “dart” folder to where you want Dart installed.

This folder will contain the Dart Editor, the Dart SDK and the Chromium web browser which has a built-in Dart VM.

Step 3: Run DartEditor.exe

Dart Editor 2013 06 16 11 18 01 thumb Getting Started With Google’s Dart Language

That is it, now you are ready to rock some Dart code!

Creating your first Dart language App

The Dart language can actually be used outside of a browser, just like you can use JavaScript with Node.js.  But, most developers will probably want to use Dart the same way we use JavaScript in a web application today.

I’m going to walk you through a real simple example that will show you how to create a basic Dart application that is able to respond to a button click and manipulate some DOM data.  For more advanced examples, you can check out my recently released Pluralsight course on Creating Web Applications with Dart. (I will plug this one more time before this post is over… wait for it…)

Step 1:

Go to File –> New Application.

Fill in your application name.  I’ll call mine HelloWorldDartWeb.

Leave “Generate sample content” checked.

Select “Web application.”

2013 06 16 11 24 03 thumb Getting Started With Google’s Dart Language

Step 2:

Open the helloworlddartweb.html file and clear out everything in the body element except for the two script tags at the bottom.

The first script tag imports our actual Dart file, just like you would use to add JavaScript to a page.

The second script adds Dart support to the browser.

Step 3:

Add the following HTML to the body tag in the helloworlddartweb.html file:

 <button id="theButton" >Press Me!</button>
 <div id="resultDiv"></div>

This will just create a button and a div.  We are going to add some Dart code to respond to a button click and populate the div with some text.

Step 4:

Open the helloworlddartweb.dart file and clear out everything in main() and delete the reverseText function.

Notice that there are only two things we really will need in our .dart file.  Just an import ‘dart:html’, to import that html library for Dart, and the main function, which executes as soon the DOM content is loaded on the page.

Step 5:

Edit the helloworldweb.dart file to make it look like this:

import 'dart:html';

void main() {
  var button = query("#theButton");
  button.onClick.listen(addResult);
}

void addResult(Event e) {
  var resultDiv = query("#resultDiv");
  resultDiv.text = "You clicked the button";
}

This code simply gets the button using a CSS selector.  It uses the query function to do this.

Then we register the addResult function as an event handler for the onClick event for the button.

In the addResult function, we simply query for the resultDiv and change its text.

After you run this example, you should see a result like this:

HelloWorldDartWeb   Chromium 2013 06 16 11 47 56 thumb Getting Started With Google’s Dart Language

Step 6:

Now change the Dart code to look like this:

import 'dart:html';

void main() {
  query("#theButton")
    .onClick.listen(
        (e) => query("#resultDiv").text = "You clicked the button!"
    );
}

Try running the code again and you should see it works exactly as before.  Here we just shortened the code to a single line by using the short-hand function syntax.

Going further with the Dart language

So, that is just the basics of Dart.  I wanted to show you how to get started really quickly, but I am sure there is more you will want to learn about Dart.

We can of course do much more with Dart, especially when building web applications.  There is a Dart Web UI library which can be used to do templating and data binding so we can simplify our Dart code even further.

The language itself is pretty simple.  Most C# and Java developers, as well as JavaScript developers, should be able to read and understand Dart code without any assistance.  But here is a link to an overview of the language.

If you are looking for a more in-depth coverage of the Dart language and want to see how to build a real application with Dart, check out my Introduction To Building Web Applications With Dart course on Pluralsight, where I go over the entire language and guide you through building a real application, as well as cover some of the more advanced features like mixins and isolates.

Also, I could only find two books on the Dart Language.

I don’t know if Dart will end up replacing JavaScript, but I do think Dart has the potential.  It really is an awesome language that is fun to develop in.

That is strong praise coming from me, since I really tend to dislike dynamic languages.  The creators of Dart have really done a good job of creating a language that is succinct, fast, easy to work with and has the best advantages of strongly typed languages with all the flexibility of dynamic languages like JavaScript.

Get Up and CODE and YouTube Videos

For those of you who frequent my blog and are looking for my latest Get Up and CODE podcast episode and YouTube video for the week, I have a bit of an announcement.

I am going to start posting these blog posts every Monday.

The YouTube videos will be going up every Wednesday.

The Get Up and CODE podcast will be coming on every Friday.

When my new website design is done, you’ll be able to find the latest episodes of each on the side bar, so I’ll stop including them in each weekly post.

But here is last week Get Up and CODE, where Iris and I talk about basic weight training.

Get Up And Code 006: Basic Weight Training

play audio Getting Started With Google’s Dart Language

Why JavaScript Is Doomed

Update: I posted an update to this post where I talk about why I was wrong about JavaScript here. We are all human, we all make mistakes. I’m leaving this post and not deleting it, because I think it is important to learn from our mistakes.

JavaScript is a bubble.

Just like the housing bubble.

Just like the .COM bubble.

bubble thumb Why JavaScript Is Doomed

And just like any bubble, the JavaScript bubble is bound to pop.

Sure, JavaScript is everywhere.  It appears to be growing at a rapid pace.  But I’m willing to bet that we are getting close to a complete reversal that will throw JavaScript down from its throne, shattering its JQuery scepter with it.

JavaScript never really made a comeback

Part of the problem with JavaScript is that it’s propped up on the back of another technology. See, JavaScript itself was rejected long ago. If JavaScript was a wonderful language to develop in, its wonders would have been praised years ago when it was first introduced. But I remember cursing JavaScript 15 years or so ago.  And I wasn’t alone.

Yes, I know it was a dark time, but recall, if you will, your pure hatred for JavaScript.  You know, before it was so cool.

Then how did this ugly wart of a language become so popular?

Well, you see, it was this little library called JQuery. JQuery solved a very real and annoying set of problems that wasn’t around when JavaScript was first invented: manipulating the DOM and making Ajax calls.

JQuery was basically designed to make JavaScript possible to work with. Before JQuery, DOM manipulation and Ajax calls were difficult. After JQuery, they were easy.band aid thumb Why JavaScript Is Doomed

So JQuery ended up being this big band-aid that covered up all the ugly JavaScript code you didn’t want to write and made doing what you wanted to do much easier.

You may disagree with me on this point, and you are welcome to do so, but even if JQuery isn’t the reason JavaScript is so hot right now, do you honestly think JavaScript would have become so popular if JQuery never existed?

The problem with JavaScript

I want to love JavaScript. I really do.

I know it doesn’t sound like I do, but just like I can’t make myself like sweet potatoes—even though I know how good they are for me—I can’t like JavaScript.sweetpotatoe thumb Why JavaScript Is Doomed

I’ve tried many things. I’ve put some butter and brown sugar on a freshly baked sweet potato. I’ve doused it with hot sauce. I’ve even pretended it was a regular potato and dressed it up like one. But, the fact remains, I just don’t like sweet potatoes. It’s something in their very nature that I despise.

I’ve tried the same thing with JavaScript. I’ve added libraries that make it much sweeter, like JQuery and Backbone.js. I’ve used tools like CoffeeScript and TypeScript to try and pretend it was a more palatable language. But the fact remains, JavaScript has some things that are fundamentally wrong with it that no amount of covering up or pretending will fix.

If JavaScript wasn’t so ugly at heart, then a book called “JavaScript, The Good Parts,” probably wouldn’t be the #1 best-selling book on Amazon for JavaScript, the #3 best-selling book on web development, and the #4 best-selling book on software development, would it? (Go ahead and check it out for yourself if you don’t believe me.)

I don’t really need to tell you again what is wrong with JavaScript. If you use JavaScript, you know. If you don’t use JavaScript, just search for “why JavaScript sucks” on Google and you’ll get plenty of answers.

The point is, unless we are going to be completely disillusioned about it, we can probably all agree that JavaScript is not the greatest programming language that was ever created, and that it has some glaring weaknesses.

My point is not to bash JavaScript

Before you pitchfork me, I want to clear a few things up.

I don’t hate JavaScript.

I don’t suggest you shun JavaScript and go off with me to a floating island in international waters where we will build a new internet, one that isn’t infected by JavaScript.

I actually use JavaScript.
Not only do I use JavaScript, but I have to use JavaScript and so do you.

And if you are smart and want to have a good career in software development, you’ll take everything I am saying with a grain of salt, knowing that I could be completely wrong.

If you are smart, you won’t just dump JavaScript out the window, betting that it will fail, because it might not. It might grow to become the one universal language that replaces all other programming languages. JSON sempiternus!

But, on the other hand, if you are smart, you won’t put all your eggs in the JavaScript basket either. Even though the world seems bright and cheery for JavaScript developers today, it also seemed equally bright and cheery for Blackberry devs not too long ago. And look how that turned out.

And if you are solely a JavaScript developer or you really like JavaScript, I sincerely don’t mean to offend you, but I offer this piece of advice: You are not the technology you happen to be using.

Trust me, if you’re a good developer, you’ll still be a good developer even if JavaScript goes away.

What is actually awesome about JavaScript has nothing to do with JavaScript

No one gets up in the morning and says, I want to have bamboo shoots shoved under my fingernails. (Ok, well maybe some people do, but those guys are still writing object-oriented Perl.)

Yet, at the same time so many developers get up in the morning, fire up their IDE—or excuse me, lightweight text editor which has 50 plugins installed to give the capabilities of an IDE, but is not an IDE—and write JavaScript code. Why do they do it, unless they think JavaScript really is awesome?

It’s because all the stuff around JavaScript and built with JavaScript and on top of JavaScript is actually pretty awesome.

As much as I loathe JavaScript itself, frameworks like JQuery, Durandel, Backbone, Angular, Knockout and more are pretty darn cool.

Not only that, but JavaScript is everywhere!

Every browser is a JavaScript interpreter. Every notebook, PC, tablet, and smartphone can run JavaScript.

There are even cool server technologies, like Node.js that are built with JavaScript.

JavaScript runs in the browser, it has plenty of hooks in it for manipulating the DOM, and it has tons of cool libraries that give you the power to do awesome things, what’s not to love?

This is the part where I tell you what is not to love

holding hands thumb Why JavaScript Is Doomed

What’s not to love, is that all of that stuff has nothing to do with JavaScript itself.

Take JavaScript away and replace it with another programming language and you don’t really miss anything.

Ever seen a movie star without her makeup? Makes you realize that any halfway decent looking woman could be a movie star, with the proper styling.

The same goes for JavaScript. It is a language that has been dressed up to look like something it is not. What we all love about JavaScript is not the language itself, but all that makeup that has been caked on, a little bit of mysterious seduction it infers, and the stylish clothes it wears.

But, what is starting to happen already, and what I believe will continue to happen, is that people will start to get sick of that caked-on makeup look and high maintenance personality of JavaScript.

All those frameworks were really useful at first, but they are becoming such a huge mental burden. Are you worried about what JavaScript framework you need to master and keeping up with what is the hot one to use on any given day? I am.

You can only build so much on top of something else, before you have to wipe the slate clean and start over.

I don’t know when this will happen with JavaScript, but I am pretty sure it will happen.

It is very likely that a language like Dart, that can do everything JavaScript can do and more, will likely someday dethrone our web development king.

JSON sempiternus!

By the way, check out my new experiment on YouTube, going to release a short video each week.  Let me know what you think.

Getting Started With a Programming Project

What Makes Readable Code: Not What You Think

You often hear about how important it is to write “readable code.”

Developers have pretty strong opinions about what makes code more readable. The more senior the developer, the stronger the opinion.

But have you ever stopped to think about what really makes code readable?

readable What Makes Readable Code: Not What You Think

The standard answer

You would probably agree that the following things, regardless of programming language, contribute to the readability of code:

  • Good variable, method and class names
  • Variables, classes and methods that have a single purpose
  • Consistent indentation and formatting style
  • Reduction of the nesting level in code

There are many more standard answers and pretty widely held beliefs about what makes code readable and I am not disagreeing with any of these.

(By the way, an excellent resource for this kind of information about “good code” is Robert Martin’s excellent book, Clean Code, or Steve McConnell’s book that all developers should read, Code Complete. *both of these are affiliate links, thanks for your support.)

Instead, I want to point you to a deeper insight about readability…

The vocabulary and experience of the reader

I can look at code and in 2 seconds tell if you it is well written and highly readable or not.  (At least my opinion.)

At the same time, I can take a sample of my best, well written, highly readable code and give it to a novice or beginner programmer, and they don’t spot how it is different from any other code they are looking at.

Even though my code has nice descriptive variable names, short well named methods with few parameters that do one thing and one thing only, and is structured in a way that clearly groups the sections of functionality together, they don’t find it any easier to read than they do code that has had no thought put into its structure whatsoever.

In fact, the complaint I get most often is that my code has too many methods, which makes it hard to follow, and the variable names are too long, which is confusing.

There is a fundamental difference in the way an experienced coder reads code versus how a beginner does

An experienced developer reading code doesn’t pay attention to the vocabulary of the programming language itself.  An experienced developer is more focused on the actual concept being expressed by the code—what the purpose of the code is, not how it is doing it.

A beginner or less experienced developer reads code much differently.

When a less experienced developer reads code, they are trying to understand the actual structure of the code.  A beginner is more focused on the actual vocabulary of the language than what the expression of that language is trying to convey.

To them, a long named variable isn’t descriptive, it’s deceptive, because it is hiding the fact that NumberOfCoins represents an integer value with its long name and personification of the variable, as something more than just an integer.  They’d rather see the variable named X or Number, because its confusing enough to remember what an integer is.

An experienced developer, doesn’t care about integers versus strings and other variable types.  An experienced developer wants to know what the variable represents in the logical context of the method or system, not what type the variable is or how it works.

Example: learning to read

Think about what it is like to learn to read.

When kids are learning to read, they start off by learning the phonetic sounds of letters.

When young kids are reading books for the first time, they start out by sounding out each word.  When they are reading, they are not focusing on the grammar or the thought being conveyed by the writing, so much as they are focusing on the very structure of the words themselves.

Imagine if this blog post was written in the form of an early reader.

Imagine if I constrained my vocabulary and sentence structure to that of a “See Spot Run” book.

Would you find my blog to be highly “readable?”  Probably not, but kindergarteners would probably find it much more digestible.  (Although they would most likely still snub the content.)

sheetmusic What Makes Readable Code: Not What You Think

You’d find the same scenario with experienced musicians, who can read sheet music easily versus beginners who would probably much prefer tablature.

An experienced musician would find sheet music much easier to read and understand than a musical description that said what keys on a piano to press or what strings on a guitar to pluck.

Readability constraints

Just like you are limited to the elegance with which you can express thoughts and ideas using the vocabulary and structure of an early reader book, you are also limited in the same way by both the programming language in which you program in and the context in which you program it.

This is better seen in an example though.  Let’s look at some assembly language.

.model small
.stack 100h

.data
msg     db      'Hello world!$'

.code
start:
        mov     ah, 09h   ; Display the message
        lea     dx, msg
        int     21h
        mov     ax, 4C00h  ; Terminate the executable
        int     21h

end start

This assembly code will print “Hello World!” to the screen in DOS.

With x86 assembly language, the vocabulary and grammar of the language is quite limited.  It isn’t easy to express complex code in the language and make it readable.

There is an upper limit on the readability of x86 assembly language, no matter how good of a programmer you are.

Now let’s look at Hello World in C#.

public class Hello1
{
   public static void Main()
   {
      System.Console.WriteLine(&quot;Hello, World!&quot;);
   }
}

It’s not a straight across the board comparison, because this version is using .NET framework in addition to the C# language, but for the purposes of this post we’ll consider C# to include the base class libraries as well.

The point though, is that with C#’s much larger vocabulary and more complicated grammar, comes the ability to express more complex ideas in a more succinct and readable way.

Want to know why Ruby got so popular for a while?  Here is Hello World in Ruby.

puts &quot;Hello, world&quot;

That’s it, pretty small.

I’m not a huge fan of Ruby myself, but if you understand the large vocabulary and grammar structure of the Ruby language, you’ll find that you can express things very clearly in the language.

Now, I realize I am not comparing apples to apples here and that Hello World is hardly a good representation of a programming language’s vocabulary or grammar.

My point is, the larger the vocabulary you have, the more succinctly ideas can be expressed, thus making them more readable, BUT only to those who have a mastery of that vocabulary and grammar.

What we can draw from all this?

So, you might be thinking “oh ok, that’s interesting… I’m not sure if I totally agree with you, but I kind of get what you’re saying, so what’s the point?”

Fair question.

There is quite a bit we can draw from understanding how vocabulary and experience affects readability.

First of all, we can target our code for our audience.

We have to think about who is going to be reading our code and what their vocabulary and experience level is.

In C#, it is commonly argued whether or not the conditional operator should be used.

Should we write code like this:

var nextAction = dogIsHungry ? Actions.Feed : Actions.Walk;

Or should we write code like this:

var nextAction = Actions.None
if(dogIsHungry)
{
   nextAction = Actions.Feed
}
else
{
   nextAction = Actions.Walk;
}

I used to be in the camp that said the second way was better, but now I find myself writing the first way more often.  And if someone asks me which is better, my answer will be “it depends.”

The reason why it depends is because if your audience isn’t used to the conditional operator, they’ll probably find code that uses it confusing.  (They’ll have to parse the vocabulary rather than focusing on the story.)  But, if your audience is familiar with the conditional operator, the long version with an if statement, will seem drawn out and like a complete waste of space.

The other piece of information to gather from this observation is the value of having a large vocabulary in a programming language and having a solid understanding of that vocabulary and grammar.

The English language is a large language with a very large vocabulary and a ridiculous number of grammatical rules.  Some people say that it should be easier and have a reduced vocabulary and grammar.

If we made the English language smaller, and reduced the complex rules of grammar to a more much simple structure, we’d make it much easier to learn, but we’d make it harder to convey information.

What we’d gain in reduction of time to mastery, we’d lose in its power of expressiveness.

One language to rule them all?

It’s hard to think of programming languages in the same way, because we typically don’t want to invest in a single programming language and framework with the same fervor as we do a spoken and written language, but as repugnant as it may be, the larger we make programming languages, and the more complex we make their grammars, the more expressive they become and ultimately—for those who achieve mastery of the vocabulary and grammar—the more readable they become. (At least the potential for higher readability is greater.)

Don’t worry though, I’m not advocating the creation of a huge complex programming language that we should all learn… at least not yet.

This type of thing has to evolve with the general knowledge of the population.

What we really need to focus on now is programming languages with small vocabularies that can be easily understood and learned, even though they might not be as expressive as more complicated languages.

Eventually when a larger base of the population understands how to code and programming concepts, I do believe there will be a need for a language as expressive to computers and humans alike, as English and other written languages of the world are.

What do you think?  Should we have more complicated programming languages that take longer to learn and master in order to get the benefit of an increased power of expression, or is it better to keep the language simple and have more complicated and longer code?

If you like this post don’t forget to Follow @jsonmez or subscribe to my RSS feed.

Implicit and Explicit Conversion Operators in C#

Recently I stumbled upon a pretty interesting feature of C# that I either neglected to really pay attention to before or just had entirely missed.

It is definitely debatable whether or not one should even use this feature, because it is likely to result in some confusing situations by someone reading your code even if they are aware of the feature’s existence.

Take a look at this code

Let’s look at an example that might look a bit strange.

What would you think if you stumbled upon this code?

Book book = new Book(&quot;Code Complete&quot;);
XDocument document = book;

 

book thumb Implicit and Explicit Conversion Operators in C#

What if I told you that Book does not inherit from XDocument?

In this case a custom implicit casting is happening because of an implicit conversion operator I created on Book.

Here is how it is defined:

public class Book
{
        private readonly string title;

        public Book(string title)
        {
            this.title = title;
        }

        public static implicit operator XDocument(Book b)
        {
            // Code to convert the book into an XML structure
            return new XDocument();
        }

        protected List&lt;Page&gt; Pages { private get; set; }
}

 

What is happening in this case is that the compiler is noticing that I am trying to assign a Book object to a variable of type XDocument and that I have defined an implicit operator to allow that conversion.

By defining this implicit conversion operator I can assign any Book to an XDocument and it will execute the code defined in my implicit operator method to return an XDocument.

Backwards as well

I can also make the conversion the other way.

XDocument document = new XDocument();
Book book = (Book)document;

 

You can see here that I am doing something a bit different though.  In this case I am explicitly casting the XDocument into a Book.

I could have used implicit conversion, like the previous example, but not all XDocuments can automatically be converted to Books, so I wanted to make it allowed only if someone explicitly used the casting operator to perform the cast.

Here is what that code looks like:

 public static explicit operator Book(XDocument d)
{
	 // Code to convert the XML document into a book
    return new Book(&quot;&quot;);
}

 

Limitations

You can only use the implicit and explicit operators on classes that you have defined.  You can’t use them to extend existing classes to add automatic conversions.

Also the conversions can’t chain automatically.  If you have a conversion to type a Dog to a Cat and a Cat to a Mouse, you can’t assign a Dog directly to a Mouse.

Should I use it?

Now that is a tough question.  I have some mixed thoughts on actually using this feature.

My biggest problem with it is the discoverability.  When I look at code that is assigning a Book to an XDocument, I don’t immediately know where to look for the code that is allowing that assignment.  The code could actually exist in either the Book class or the XDocument class.  (We happen to know in this case that XDocument is a .NET class, so it’s not going to be there, but where you have to user defined classes, you can’t be sure.)

If I didn’t know about implicit and explicit operator overloads, I would be even more puzzled.

My other reservation is that in most cases it is not immediately obvious what exactly is happening.

  • Are we getting a copy of Book that is representing an XML structure?
  • Are we getting a raw XML document that could be populated with Book data?
  • Are we losing data here?

I can look at the method to figure out what is going on, but that makes the code that is using the implicit or explicit conversion less readable by itself.

It seems to me in that case having a method off of Book called ToXDocument() would make things at least a bit more clear.

On the other hand, I can definitely see some benefits to using these operators to make code more succinct and to make types that have obvious conversion easier to work with.

Consider having classes that represent temperatures in Celsius and Fahrenheit.  In those cases implicit conversion operators between the two formats makes intuitive sense.  We can also be pretty confident that the conversion would not result in a data loss.

termo thumb Implicit and Explicit Conversion Operators in C#

General guidelines

In general, my recommendation would be to avoid defining implicit and explicit operators because it is likely that most developers reading your code will be confused by them and in most cases you are not adding much value.

I would say that you should only use implicit and explicit operators when the conversion between two types is very clear because they are just different ways of representing the same value.

Although I can see the cases for other uses of the operators, it seems like there the usage is more likely to cause confusion than bring clarity.

To me an equal sign means assignment, I do not often think of it to mean conversion.

I could of course be wrong about my thoughts on implicit and explicit operators, but as of yet I haven’t seen it in the wild, so if you have some good examples of where it makes sense to use this feature, please let me now.

If you like this post don’t forget to Follow @jsonmez or subscribe to my RSS feed.

So You Think You Can Polymorph?

In the true spirit of this blog I am going to take the complex idea of polymorphism and make it as simple as possible.

polymorph thumb So You Think You Can Polymorph?

Now you may already think you understand polymorphism—and perhaps you do—but I’ve found that most software developers don’t actually understand exactly what polymorphism is.

What is polymorphism?

How many times have you been asked this question during a job interview?

Do you actually know confidently what the right answer is?

Don’t worry, if you are like most developers out there in the world you probably have this feeling that you know what polymorphism is, but are unable to give a clear and concise definition of it.

Most developers understand examples of polymorphism or one particular type of polymorphism, but don’t understand the concept itself.

Allow me to clarify a bit.

What I mean by this is that many times when I ask about polymorphism in an interview, I get a response in the form of an example:

Most commonly a developer will describe how a shape base class can have a circle derived class and a square derived class and when you call the draw method on a reference to the shape base class, the correct derived class implementation of draw is called without you specifically having to know the type.

While this is technically a correct example of runtime polymorphism, it is not in any way concise, nor is it a definition of the actual term.

I myself have described polymorphism in a similar fashion in plenty of job interviews.

True understanding

The problem with just that example as an explanation is that it lacks true understanding of the concept.

It is like being able to read by memorizing words, while not understanding the concepts of phonetics that underlie the true concept of reading.

reading thumb So You Think You Can Polymorph?

A good test for understanding a concept is the ability to create a good analogy for that concept.

Oftentimes if a person cannot come up with an analogy to describe a concept, it is because they lack the true understanding of what the concept is.

Analogies are also an excellent way to teach concepts by relating things to another thing that is already understood.

If right now you can’t come up with a real world analogy of polymorphism, don’t worry you are not alone.

A basic definition

Now that we understand why most of us don’t truly understand polymorphism, let’s start with a very basic concise definition.

Polymorphism is sharing a common interface for multiple types, but having different implementations for different types.

This basically means that in any situation where you have the same interface for something but can have different behavior based on the type, you have polymorphism.

Think about a Blu-ray player.

When you put a regular DVD in the player what happens?

How about when you put a Blu-ray disc in the player?

The interface of the player is the same for both types of media, but the behavior is different.  Internally, there is a different implementation of the action of playing a disc depending on what the type is.

How about a vending machine?

Have you ever put change into a vending machine? vending thumb So You Think You Can Polymorph?

You probably put coins of various denominations or types in the same slot in the machine, but the behavior of the machine was different depending on the type.

If you put a quarter in the machine it registers 25 cents.  If you put in a dime it registers 10 cents.

And that is it, you now understand the actual concept of polymorphism.

Want to make sure you don’t forget it?  Try coming up with a few of your own real world analogies or examples of polymorphism.

Bringing it back to code

In code polymorphism can be exhibited in many different ways.

Most developers are familiar with runtime polymorphism that is common in many OO languages like C#, Java and C++, but many other kinds of polymorphism exist.

Consider method overloading.

If I create two methods with the same name, but they only differ in type, I have polymorphic behavior.

The interface for calling the method will be the same, but the type will determine which method actually gets called.

Add(int a, int b)
Add(decimal a, decimal b)

 

You might be shaking your head “no” thinking that this is not polymorphism, but give me the benefit of the doubt for a moment.

The most common argument against this example as polymorphism is that when you write this code the method that is going to be called is known at compile time.

While this is indeed true for statically typed and compiled languages, it is not true for all languages.

Consider Add being a message instead of a method.

What I mean by this is that if you consider that the actual determination of the method that is called in this situation could be differed until runtime, we would have a very similar situation to the common shape example.  (Late binding)

In many languages this is what happens.  In Objective-C or Smalltalk for example, messages are actually passed between objects and the receiver of the message determines what to do at runtime.

The point here is that polymorphism can be done at compile time or during execution, it doesn’t really matter.

Other polymorphic examples in code

Since the intent of this post is not to classify and explain each type of polymorphism that exists in code, but rather to provide a simplified understanding of the general concept, I won’t go into a detailed explanation of all the kinds of polymorphism we see in code today.  Instead I’ll give you a list of some common examples that you may not have realized were actually polymorphic.

  • Operator overloading (similar to method overloading.)
  • Generics and template programming. (Here you are reusing source code, but actual machine code executed by the computer is different for different types.)
  • Preprocessing (macros in C and C++)
  • Type conversions

Why understanding polymorphism is important

I may be wrong, but I predict that more and more development will move away from traditional OO as we tend to find other ways of modularizing code that is not so rooted in the concept of class hierarchies.

Part of making the transition requires understanding polymorphism as a general purpose and useful computer science concept rather than a very situational OO technique.

Regardless, I think you’ll agree that is it nice to be able to describe polymorphism itself rather than having to cite the commonly overused example of shapes.

If you like this post don’t forget to Follow @jsonmez or subscribe to my RSS feed.

Why C++ Is Not “Back”

I love C++.

C++ taught me how to really write code.

Back in the day I would study the intricacies of the language, Standard Template Library, and all the nuances of memory management and pointer arithmetic.

Those were some seriously good times.  I remember reading Scott Meyers Effective C++ book series over and over again.  Each time I would learn something new or grasp more of how to use C++.

I’m saying all this just to let you know that I don’t hate C++.  I love C++.

There are plenty of excellent developers I know today that still use C++ and teach others how to use it and there is nothing at all wrong with that.

So what is the problem then?

The new message is wrong

C++11 just came out recently and it seems like there is this big resurgence in interest in C++ development.

announcer thumb Why C++ Is Not “Back”

Now don’t get me wrong.  C++11 is fantastic!  I am in just about 100% agreement with all of the changes that have been made.  C++ has definitely become much easier to use and it has even become more powerful.

There is one thing it didn’t become though—and this is the most important—more simple.

It seems that many of the seasoned developers have forgotten why we stopped using C++ and moved on to Java, C# and other modern languages.

Many younger or newer developers don’t really know the history and are getting confused by the current C++ message and resurgence.

Everyone keeps asking me if they need to learn C++, but just like my answer was a few years ago, it is the same today—NO!

Ok, so “NO” in caps is a bit harsh.  A better answer is “why?”

Why do you want to learn C++?

There are only about three sensible reasons to learn C++ today that I can think of.

  • You absolutely need to eke out every bit of performance possible out of your software and you would like to do that with a language that will support OO abstractions.
  • You are writing code which will directly interface with raw hardware.  (Example: you are writing a low level driver.)
  • Memory control and timing is of absolute importance, so you must have completely deterministic behavior in your system and the ability to manually manage memory.  (Think real time embedded operating system controlling a moving piece of machinery.)

Now it is possible I missed a valid case, but chances are any other case is going to roughly fall into one of these three categories.

Wait! Wait!  What about portability?

banghead thumb Why C++ Is Not “Back”

No!  Please don’t learn C++ thinking that you will build software to work anywhere.  There are plenty of other options today for doing that and C++ is not nearly as portable as many people believe or tout.  The lower level the abstraction is the more different each operating system and platform is.

Also please don’t tell me C++ gives you more power and control to do exactly what you need.

Most software development is about managing complexity not about being able to twiddle bits at a lower level.  In almost all cases of modern large scale software development, higher abstractions, not lower abstractions, are what you want.

But, I want to learn C++ anyway

Ok look, I know you think Windows 8 is cool and all the cool kids are learning C++ to write their Windows 8 applications, but you should know what is in the Kool-aid before you drink it.

Writing C++ code is not a picnic.

Even with all the changes in C++11, C++ is still a very difficult language to learn and an even more difficult one to master.

You’ve probably heard this common quote about C++:

C makes it easy to shoot yourself in the foot. C++ makes it harder, but when you do, you blow away your whole leg!
— Bjarne Stroustrup

gun thumb Why C++ Is Not “Back”

And if you don’t know who Bjarne is, well,  he invented C++.  So if he says that about the language, I am sure you can draw your own conclusions.

I keep hearing that C++11 makes things so much easier now and that C++11 has fixed many of the problems of C++98.  I don’t doubt that it has.

What it hasn’t fixed is the size and scope of the language—it has actually increased it.

Sure, you can use a subset of C++.  Sure, you can use smart pointers in the new C++ to prevent you from having to manually manage memory.  You can utilize lambda expressions to declare functions in-line instead of passing function pointers.  Automatic type deduction is a much needed breath of fresh air.

The problem is you still have to know the old way of doing everything and you have to understand exactly what is really going on when you are debugging a C++ program which is easily capable of stomping memory (something you probably have never even heard of if you were born in a managed code world.)

You will encounter C++ code from 20 years ago and it will look like a different language entirely.

Here is a list of actual interview questions that I used to ask C++ developers interviewing for a job I was hiring for.

  1. How many ways are there to initialize a primitive data type in C++ and what are they?
  2. Why should you declare a destructor as virtual?
  3. What does it mean that C++ supports overloading?
  4. What are examples of overloading in C++?
  5. What is name mangling in C++ and why is it used?
  6. What is an abstract base class?
  7. What is RTTI?
  8. How can you access a variable that is “hidden” by another variable of the same name?
  9. What is a namespace and how is it used.
  10. What are the differences between a class and a struct in C++, and how does this compare to C?
  11. What are templates? How are they used?
  12. What is a copy constructor and when is it used, especially in comparison to the equal operator.
  13. What is the difference between a “shallow” and a “deep” copy?
  14. What is the const operator and how is it used?
  15. What are the differences between passing by reference, passing by value, and passing by pointer in C++?
  16. When is it and when is it not a good idea to return a value by reference in C++?
  17. What is the difference between a variable created on the stack and one created on the heap?
  18. How do you free memory allocated dynamically for an array? What are the implications of just using delete?
  19. What is multiple inheritance? When should it be used?
  20. What is a pure virtual function?
  21. What does the keyword mutable do?
  22. What does the keyword volatile do?
  23. What is the STL?
  24. What is a Vector?
  25. What is contained in the <algorithms> header?
  26. What is the difference between #include <iostream.h> and #include <iostream>?
  27. What’s the difference between “++i” and “i++”?
  28. What is short circuit evaluation? How can it be used? Why can is be dangerous?
  29. What is the ‘,’ operator?
  30. What is the only ternary operator? How is it used?
  31. What is the use of a const member function and how can it be used?
  32. How is try/catch used in C++?
  33. Why should you never throw an exception in a destructor?
  34. What is the explicit keyword?
  35. What is the proper way to perform a cast in C++?
  36. What does inline do?

Some of these questions have the same answers for C# or Java, but you can see from this list that C++ is very, very deep.  There is just a very large amount to know about the language itself.

C# and Java development are somewhat about learning the language, but much more about learning the libraries.

C++ development is more about learning every nook and cranny of the language.

C++ is the wrong direction for the future

The big problem is that programming languages really need to get simpler and increase the level of abstraction not reduce it.

There will always be a need for low level code, but a majority of the code that we write today is at a much higher level.

I first jumped off the C++ ship many years ago when I finally could no longer make the argument that I could develop apps faster in C++ than C#.

I held out for a long time trying to believe that all the investment I had made in C++ was not lost, but it turned out that C# simplified things to such a great degree that the extra power C++ gave me was not worth the extra responsibility.

Just as I was taking a break from writing this blog post, I happened to stumble across a newrevitalized project from Microsoft Research called touchdevelop.  This is the direction we need to go.  We need programming languages to be even simpler to use, not more complex.

Now don’t get me wrong, you are pretty severely constrained in touchdevelop, but I believe something similar to this is the future.

It seems that Microsoft is making a decent push for bringing C++ back to mainstream with C++ support in Window 8 and attempting to kill XNA, but I think there is a warped perception of the development community that seems to be entrenched in the minds of Windows OS developers about programmers wanting to use C++.

I just don’t ever see myself moving back to a more difficult language when I can write C# on just about every platform now.  C# is not the perfect language, but it is very elegant and simple.

Some parting words about C++

With all I said above, I still believe that there is some value in learning C++.

No, I’m not trying to contradict myself here.  Allow me to explain.

If you can program in C++, you can program in any programming language.  If you understand how stack and heap memory work, pointers and references and all the low level details that make C++ so tricky, it will help you when you are working at higher abstractions and in understanding how computers work in general.

My point of this post is not to bash C++ or bash people using C++ or teaching C++, but rather to blunt the message that seems to be being preached by an over eager C++ community.

Everyone is not going to become a C++ developer and they shouldn’t need to be.  While C++ may have the ability to make your program more efficient (in certain scenarios,) it is extremely unlikely to make you more efficient at creating your program (except in some extreme cases.)

So, I am glad C++ got a much needed overhaul, but I don’t think it is going to make a comeback any time soon, and that is a good thing.