Category Archives: Java

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

Introduction To Hibernate

I’ve just published a new Pluralsight course, Introduction to Hibernate.

This course was definitely a difficult one to produce.  There is so much to cover in Hibernate, and there was no way I could cover it all.

Here is the course description:

In the world of Java one of the most popular and widely used frameworks is Hibernate.

Hibernate is an ORM or Object Relational Mapper that allows developers to map Java objects to relational database tables. It is a valuable tool that all Java developers should know how to use.The problem is, learning Hibernate can be difficult. Hibernate is a very large framework and there are many important concepts to understand to use it effectively.

Are you a developer who…

  • has been wanting to learn how to use Hibernate
  • struggles to use the application
  • has never really understood Hibernate

This course is designed to give you the knowledge you need to feel confident about how Hibernate works and how to use it.

What this course offers:

This course is designed to make getting started with Hibernate as easy as possible and focus on the most important things you need to know. John starts off this course by teaching you a bit about Hibernate and how it works.

Then you will see how to get it setup with a real MySQL database installation. After that you will learn the very basics of mapping, which is one of the most important things to understand about Hibernate.

John will show you how to create a basic mapping for a Java object to a relational table and explain to you how the mapping works. He also covers some of the complex mapping situations like mapping collections and different relational mappings like one-to-many and many-to-one.

Once you’ve learned how to map you objects, you’ll want to know how to query them, so he’ll show you how to do this using Hibernate’s built-in HQL and using a more object-oriented approach with the Criteria API.

Finally, he wraps things up by taking a brief tour of some of the more advanced features like caching and interceptors.

Introduction To Hibernate Introduction To Hibernate

OAuth and REST in Android: Part 2

In my last post we went over OAuth in general and we looked at how to use a Java library called Leeloo to authenticate with a service providing an OAuth 2 implementation.

Now that we are able to authenticate a service with OAuth, we need to be able to actually use that service to do something useful.

Many popular web service APIs like Facebook and Twitter provide a REST based implementation.

In this post I’ll show you how to easily connect to one of these web services from Android and parse any responses you get back.

androidrest thumb OAuth and REST in Android: Part 2

Should I use a REST library?

This is a valid question we should address before getting into the details.

My answer to this question is basically “no.”

I first tried the approach of using a REST library to make it easier to communicate to a REST based web service, but quickly found the overhead of the library was more than the benefit it provided.

If you come from a background of calling XML and SOAP based web services, you might be surprised by this answer.  With SOAP based web services it was a huge benefit to use a library to generate a proxy for you to call the web service and let you not have to worry about parsing XML and SOAP headers.

With REST it is completely different.  The whole point of moving to REST based web services is to simplify the process of calling web services.

Most REST based web service interfaces are extremely simple to use.  The idea is that the URL itself contains as much of the data as possible and additional data is included in the POST body.

By adding the complexity of learning a REST library and implementing the proper interfaces required to make it work seamlessly, we can easily add more complexity and overhead than just creating a HTTP request ourselves and parsing the responses.

For this approach I am going to show you how to do just that.

Calling the REST service

In order to call a REST service in Android we are going to first have to discover and understand the REST API provided to us, then make the appropriate calls with the OAuth token we got from authenticating.  Finally, we will parse the result of the call and get back our response.

Discovering the API

Because REST is not really a standard, but rather an ideal, there is not a standard way REST APIs are implemented.

You’ll have to take a look at the documentation for the REST API you want to call to figure out exactly what a call should look like.

In general though a REST API will involve making some kind of HTTP GET, POST, PUT or DELETE request and passing data through the URL or in the request body.

Here is an example of the API which I have been recently integrating my app to use.

You can see the full API documentation here.

For this API, I am going to show you how I am creating a workout entry using a post.

Making the REST call

In order to make a REST call in Android, we are going to use a HttpClient object and the appropriate http request class.

In this example we are going to use the JSONObject class to create some data in JSON format that we can pass to the REST call by embedding it in the post.

I looked at the API for posting a workout entry to Dailymile, and the format of the request should look like this:<token>

The API also indicates that it expects the post body to contain some JSON and gives us a list of required and optional entries that need to be in that JSON object.

Let’s take a look at how I am making this call and then we’ll break it down some.

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
    + token);

httpPost.setHeader(&quot;content-type&quot;, &quot;application/json&quot;);
JSONObject data = new JSONObject();

data.put(&quot;message&quot;, dailyMilePost.getMessage());
JSONObject workoutData = new JSONObject();
data.put(&quot;workout&quot;, workoutData);
workoutData.put(&quot;activity_type&quot;, dailyMilePost.getActivityType());
workoutData.put(&quot;completed_at&quot;, dailyMilePost.getCompletedAt());
JSONObject distanceData = new JSONObject();
workoutData.put(&quot;distance&quot;, distanceData);
distanceData.put(&quot;value&quot;, dailyMilePost.getDistanceValue());
distanceData.put(&quot;units&quot;, dailyMilePost.getDistanceUnits());
workoutData.put(&quot;duration&quot;, dailyMilePost.getDurationInSeconds());
workoutData.put(&quot;title&quot;, dailyMilePost.getTitle());
workoutData.put(&quot;felt&quot;, dailyMilePost.getFelt());

StringEntity entity = new StringEntity(data.toString());

HttpResponse response = httpClient.execute(httpPost);


You can see that I am first creating an HttpClient object and an HttpPost object.  The HttpPost has its URL set to the URL for the API call and I am adding a query string parameter to provide the OAuth token we got when when authenticated in my previous post.

I set the content type to be JSON so that we can get back a JSON object from the API call and so it knows that we are passing JSON data.

Then I construct a JSON object in the format specified by the API.  The way to construct the JSON object is to basically create a set of keys and values that are specified by the API you are calling.  In this instance I have a “message” key which I put the message data into. 

The only tricky part is that JSON objects can be nested.  So if you look at the key “workout” in the example above, I am creating a brand new JSON object to use as the value for that key which has its own subkeys which could contain more JSON objects.

Doing it this way is much more simple than trying to construct the string yourself.  The string we end up constructing will look something like this:

Finally, I put the JSON data into a StringEntity class and set it as the entity on the HTTP Post.  Then we can call execute on the HttpClient to execute the HTTP POST.
Handling the response
Now that we have actually made the call to the REST service method we can handle the response by creating another JSONObject from the HttpResponse that is returned.
Let’s look at that code and then we can go over what is happening.
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject responseJSON = new JSONObject(responseString);
int workoutId = responseJSON.getInt(&quot;id&quot;);

All we are doing in this case is getting the response from the execute call on the HttpClient object, then using EntityUtils.toString to convert the response’s entity to a string representation.  Finally, we construct a new JSONObject from that string.

We can then easily extract any data out of the JSON object by using the methods on that JSON object that let us get typed values out of it.  For this example, I know that I am getting back some JSON that has a key “id” which is the id of the workout I created with my POST.

It is really that simple

The example I am showing you here is one of the more complex examples of calling a REST based API, because we are having to POST and parse JSON data.

In many API calls, you can just use an HTTP GET or a POST without any data to accomplish what you need to in the API.

Some REST based APIs will allow or require data to be passed in a different format, but most of them use JSON notation, which I find the easiest to work with.

Hopefully with these series of posts you can now authenticate against an OAuth 2 based service and make calls to the API to get and manipulate data in Android.

If you have any questions, feel free to drop me a line or post in the comments below.

As always, you can subscribe to this RSS feed to follow my posts on Making the Complex Simple.  Feel free to check out where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter here.

Android Presenter To Activity Using Guice

In a prior post I talked about how to unit test android applications.  I made some references to wiring up an Activity with a presenter, but I didn’t really show how I was doing that.

I got some requests to show some sample code, so I thought I would explain what I was doing here and see if anyone had better suggestions.


To make it easier to unit test and to decouple my system as much as possible, I am using a dependency injection framework called Roboguice.  It is basically the Google Guice framework that is ported to Android and adds some Android specific functionality.

One challenge you will most likely first encounter when working with Roboguice is that a presenter is going to need a reference to the Activity class that is going to represent its view.  Since the Activity class has to create the presenter, this presents a dependency injection challenge.

We can’t just ask for a presenter from our container and have it auto-resolve the dependency on the Activity.  (That is we can’t rely on constructor injection in this case.)

Setter injection to the rescue

One thing we can do, is use setter injection instead of constructor injection to inject the other references our presenter will need.

Guice provides us with an easy way to perform setter injection after we have created the object.  I use this technique to make sure that I can pass my activity into the presenter and still have the benefits of having the other dependencies injected into the presenter.

Here is some code showing my OnCreate method inside my activity.

public void onCreate(Bundle savedInstanceState)


    this.presenter = new MainPresenter(this);
    Injector injector = Guice.createInjector(new PaceMakerModule());

This code is creating an instance of my presenter which holds a reference to the Activity, or view, it is manipulating.  Then Guice injects dependencies using the module I created into any properties that are annotated with @Inject.

Here is what some of those presenter set methods look like:

public void setSystemClock(ISystemClock systemClock)
     this.systemClock = systemClock;

public void setRunSerializer(IRunSerializer serializer)
     this.runSerializer = serializer;

You can see that they are declared in the module like so:

public class PaceMakerModule extends AbstractAndroidModule
   protected void configure()


It’s not exactly pretty, but Android applications are really a loosely coupled sets of Activities which are the entry point into your code.  It makes it very difficult to create a MVP type of framework that we might be used to.

If you know of a better way than what I am doing please let me know, and if you have any questions or suggestions, I’m always glad to hear them or help if I can.

The Best Way to Unit Test in Android: Part 2

In my last post I presented two choices for unit testing in Android.

  • Unit test on the real device or emulator using the real android framework
  • Unit test on our PC using the JVM

Each choice has some pros and cons, but for me it came down to the speed and flexibility allowed by running in a real JVM.  I actually tried to create an Android unit testing project using the scaffolding provided by Google but it turned out to be very restrictive, especially since I couldn’t use JMock.

There is also something to be said for being able to execute the unit tests extremely quickly.  If you have to wait for an emulator to come up, or try to run them on a real device, it is less likely the unit tests will be run.

How to do it

The basic idea of this approach is fairly simple.

We are going to try and abstract away any Android specific calls from our application and then unit test the plain Java logic in the application just like we would any other Java project.

Step 1:  Create a JUnit project

Create a new JUnit project just like you would for unit testing any Java application.

newjavaproject thumb The Best Way to Unit Test in Android: Part 2

Make sure you chose Java Project rather than Android Test Project.

From here you can add your JUnit references to your build path.  I would also recommend adding Instinct for doing BDD style testing.  Instinct uses JMock internally to create mocks for you using a declarative approach.

The only other thing you will want to do with this project is to add the android.jar to the build path.  The android.jar can be found in your Android SDK directory under the platform directory that corresponds to the API version you are targeting with your application.

For example, on my machine, I am targeting Android 1.6, so my android.jar is at:  C:\Android\android-sdk-windows\platforms\android-4.

Now remember, you are including the android.jar in the project only so your classes can understand what types exist in the Android framework.  If you even try to call a constructor on a class in android.jar, you will get an exception.

Step 2: Pull all the code you can out of the Activity.

The next thing we need to do is clean up our Activity class to make sure that it has the smallest amount of logic in it as possible.

Since we can’t actually instantiate any types that exist in the Android framework, we are not going to be able to create an instance of our Activity in the test project.  So we are not going to be able to unit test our Activity.  This isn’t a problem if most of the logic we care about testing exists in other layers in our system.

You can design the lower layers however you want.  I am still not quite sure the best approach here, but what I did was put a presentation layer directly below the Activity.  I have a Presenter class directly below the Activity that tells my activity what to do.  The Activity passes on any interesting events or information to the Presenter.

You should leave the Activity with the responsibility of setting the text on its own view objects, but create methods for your lower layers to tell the Activity what text to set the objects to and so forth.  Activity is going to act as an adapter to a large portion of the Android framework for your application.

Because the entrance point into your application is going to be the Activity, you will need to wire up the rest of your layers from the Activity.  This is a little strange, but it works.  In my application, I create a new Presenter and pass this into it on the constructor.

When you are done, your Activity should look pretty thin.  It should delegate all its event handler logic down to the lower layers and act as a pass through for manipulating the view.

Step 3: Wrap remaining Android object calls.

You’re going to find that some of the remaining Android API will need to be called from lower down than the Activity.  This is not as big of a problem as it seems.

In my application I needed to make some calls to android.os.SystemClock.  I needed to make those calls lower down than the activity because it is part of the heart of the logic of my application.

I created a simple SystemClockWrapper class that wraps system clock and delegates any calls to the real SystemClock class.  Then I extracted an interface from that class called ISystemClock (hey, I like the C# convention for interfaces.)

Finally, in my application logic, I allowed the ISystemClock reference to be passed in or “injected” through the constructor of the class that used it.

public class SystemClockWrapper implements ISystemClock
     public long getElapsedRealTime()
          return SystemClock.elapsedRealtime();


public interface ISystemClock
     public abstract long getElapsedRealTime();


In my unit test I just pass in a mock version of the ISystemClock interface.

One hint here is to use the refactor tool in your IDE to extract an interface.  This can save you some time of trying to manually create interfaces for large pieces of functionality you are wrapping.

Putting it all together

Now you should be able to create your unit tests against most of your application logic and run them just like any other unit test project.

The only thing you won’t be able to do is unit test the logic in your Activity classes.  This shouldn’t be much of a problem if you have made them into views, because they should only contain view logic.

If you really want to be able to write some tests for the Activity though, you can create another actual Android Test Project and use Google’s framework to write unit tests from there.

The Best Way to Unit Test in Android: Part 1

I’ve been doing some development in Android lately on a top secret project, one that hopefully will change the way you run with your phone.

In the course of building this app, in a previous post I mentioned that I wanted to find the right, or perfect way, to build an Android application.

I haven’t found the best way to build an Android application into a nice clean design pattern, but have found a way that seems to work, and makes the application testable and easy to maintain.

I do believe though, that I have found the optimal way to unit test in Android right now.  Yes, a bold statement, but I have looked high and low for a better solution, and can’t find one.

htcandroid thumb The Best Way to Unit Test in Android: Part 1

The problems

So first a little bit of background on the problem with unit testing in Android.  Take what I say with a grain of salt here, because I am not an Android platform expert, and feel free to correct me if I misstate something.


If you download the Android SDK from google, you will find that the android.jar you get with the SDK is much like a C++ header file; it doesn’t actually contain any working code.  As a matter of fact, all the methods are stubbed out to throw an exception with the message “Stub!” when you call them.  How cute.

The real android.jar implementations live on the emulator, or your real Android device.  So, if you want to actually run any code that is going to call any methods or try to construct real Android framework classes, you must run that code inside the emulator or a real device.

Dalvik VM

When you’re working with Android, it sure feels like you are writing regular old standard Java SE code, but you are not. You probably won’t notice the difference, as almost everything that you need is there in the Dalvik VM implementation of Java.

Dalvik is not even a Java Virtual Machine at all.  That is right, it runs on cross-complied .class files which are converted to a .dex format.  Yes, it does not use java byte code.

Why do I mention all this?  Because you might want to use something like JMock to mock your dependencies when writing your unit tests.

Well, you can’t.  It just isn’t going to work, because the Dalvik VM doesn’t use java byte code, so the reflective coolness that mocking frameworks like JMock use doesn’t work the same.

Be aware that any external library you try to use in your Android project may not work because Android does not support the full Java SE implementation.  It actually is a subset of the Apache Harmony Java implementation.

There is no main()

Where does an Android application start running?  From the activity.  Which is basically the view.  (Some people will argue this is the controller or presenter.  And yes, I agree in respect to the Android framework it is, but in regard to your application framework it is the view.)

Android applications define a starting activity and launch from there.  Activities can even be launched from other applications.

This tends to disrupt most of our MVC, MVP, MVVP pattern architectures, as the view is going to be the entry point and will have to be responsible for initializing the rest of the application.  (That is not entirely true, as there is an class that gets called the first time your app is run, to launch the main activity, but for the most part you can’t do much here.)

Essentially though, you have to build your architecture based on each Activity being its own separate little application, with the entry point being in the activity.  This puts some serious constraints on unit testing.

Putting it all together

So if I can sum up the problems briefly, I would say:

  • Android framework code has to run in the emulator or on a device.
  • Dalvik VM doesn’t allow us to use our standard mocking frameworks.
  • Entry points for our applications are in the views.

The first problem, combined with the second, lead us to an interesting choice.  Should we run our unit tests on an actual emulator or device using the Dalvik VM, or should we run them in a JVM?

It is probably not an obvious question, but let me explain why it is the most relevant.

In writing an application, we are going to have application logic that has nothing specifically to do with the Android platform, and we are going to have Android platform specific logic (drawing views, handling Android OS events, interacting with Android APIs etc.)

If we want to write true unit tests, we need to isolate our classes and test them individually.  We should be able to do this for our application logic, without relying on the Android framework.  If we don’t rely on the Android framework, we don’t need to run on a real or emulated device, thus we are not constrained to the Dalvik VM.

If we choose to run our unit test code on a real or emulated device:

  • We will be able to use the Android framework APIs in our testing efforts.  For example, we can create new location objects instead of mocking them up.
  • We will be completely true to the real execution of our code since we will be using the real VM the code will run on.
  • Since we are running our tests on a device or emulator, they will run much slower.
  • We won’t be able to use JMock, EasyMock, or Mockito, we’ll either have to roll our own mocks or use a fledgling Android mocking framework.

If we chose to run our unit test code in a JVM on our PC:

  • We will have the full power of the JVM available to our test code, so we can use mocking frameworks like JMock, and BDD frameworks like Instinct.
  • We will run our unit tests much faster, since they will be using our PC instead of a device.
  • We can use standard unit testing practices and not have to inherit from special Android classes, or use special Android test runners.
  • We will have to wrap any calls to the actual Android framework if we need to use any Android classes or services deeper down in our application.
  • We have a small risk of having different behavior between running the tests and the real application because we will be running the code on different VMs.

In my next post, I’ll detail which option I chose and why and also give some detailed steps of how to get setup and running.

Do We Need If Blocks?

I’ve been contemplating this for a while now.  I thought I would finally write on the subject and see what other people thought.

Do you really need blocks after if statements?

It has always been a best practice, in my opinion, to put opening and closing brackets after an if statement.  Even if it has only one statement following.


The reasoning behind this best practice goes something like this: If someone later modifies this code and adds a line inside the if, having the block will prevent them from doing something like this:


Which, of course, will result in way too much love making, even on stormy days when the sky is mostly gray.

All those { } in if blocks add up to a lot of overhead

I’m not sure it is worth it anymore.

Most of the code I write now has one statement after an if block.

If I have some code like:


It is pretty much always going to get refactored to:


So, what is the real value of the { } here?  If someone modifies this code, they are most likely going to modify the method DanceALittleDance; they really shouldn’t be adding anything to the if block.  Even if they do, I think I’m paying a pretty high curly bracket tax all over my code to prevent someone from doing something stupid later on.

Is this really that bad?


Perhaps there is a better best practice?

How about if we forgo all the extra curly braces and instead say:

Whenever possible replace an if block with a single statement.

Hmm, I think I like that better.  We won’t run the risk anymore of accidentally adding a statement after the if block if we are used to thinking of an if block itself as a code smell.

Almost always you can describe what is being done in an if block with a better name and encapsulate it in a method.

Of course there are exceptions here.  In a method with a void return type when you early return in an if block you can’t really replace that with a single statement.  (Although sometimes you can avoid the early return by using an if else statement instead.)

We can apply the same thinking to anything that has a block statement.

Strangely though, try and catch require block statements to follow.  You cannot have a single statement following a try.

Anyway, at this point I am pretty well convinced that including the { } “just because” is a pretty archaic practice and is unnecessarily cluttering up our code.  If I am wrong, tell me why I am wrong, but as far as I can tell, if we prefer to extract statement blocks into methods, we can avoid the curly bracket tax everywhere.

So You Want to Become a Better Programmer? (TopCoder)

Let me ask you a question.

If you drive your car every day, do you think you are becoming a better driver?

Now, let me ask you another question.

If you competed in races with your car, frequently, do you think you would be becoming a better driver?

Let’s reflect that paradigm at programming.  Many of us, if we are fortunate, get to write code every day.  Unfortunately, a large amount of the code we write is fairly mundane.  We are rarely writing code in any form of competition.  When you are first starting out, writing code makes you better at writing code.  After time, when you have been writing code for a while, just like driving, you stop making gains.

You may have heard someone say there is a difference between a programmer with 10 years of experience and a programmer with 1 year of experience 10 times.

How to start making gains again

What I want to talk about today is just one of the ways you can start making gains again in your programming skills.  There are many others, and I have talked about some of them before.  But, today I want to talk about a very specific way I have found to break through the barriers and really improve your programming skills.  Specifically, I want to talk to you about a programming competition that I really enjoy called TopCoder.

TopCoder is a website that has a nice little competition arena that allows you to compete against other programmers solving some pretty difficult problems.  They have built a web launcher that opens up an IDE where you can view a programming problem and write your code to solve it.  You can solve the problem in any one of their supported languages and get immediate feedback through their system tests.  You can also view other people’s solutions to the problem and challenge their solutions with your own input.

There are other kinds of competitions on the site, but for what I am talking about you’ll want to go to the site, then click on develop, then click on algorithm, and launch arena.

ss 2010 04 02 08 00 03 So You Want to Become a Better Programmer? (TopCoder)

Once you are in the competition arena, you are brought to a chat lobby, where you can switch to a competition room (if one is currently underway), or to a practice room, where you can practice some of the past competitions.

ss 2010 04 02 07 39 47 So You Want to Become a Better Programmer? (TopCoder)

Once you are in one of the rooms that has problems, you can select a problem to launch the IDE.

ss 2010 04 02 07 40 18 So You Want to Become a Better Programmer? (TopCoder)

There you can type your solution to the problem right there and compile or test your code.  I’m not going to go into all of the details of how the competition and scoring works here, because I want to focus more one why TopCoder, and other types of training like this are so beneficial.

Why will this make me a better programmer?

It is kind of hard to explain why this works so well.  I think one of the major reasons is because we are challenged to solve much more difficult problems than what we usually solve in our day jobs.  When you start solving those problems, the easier problems you encounter on a day-to-day basis seem to get a lot easier.

One thing that really helped me was the ability to see other people’s solutions to the problem.  When I would finish coding my problem, and look at the other solutions to the problem, I would always find new ways of using some of the base language or library features that had never occurred to me.

When you try to challenge someone else’s problem, you are forced to read some code that can be very obscure and quickly understand it.

You can also use some plugins to code in your favorite IDE and then have the code mirrored in the TopCoder IDE, but there is a nice gain in mastery of the language that can be had if you choose to use the TopCoder IDE which does not have auto-complete.  (Especially if you ever have to write code on a white-board during an interview.  It can be pretty embarrassing when you are unable to produce the syntax for a simple statement because you are so used to relying on auto-complete.)

You don’t have to do the competition, you can just do the practice rooms on the site, but I encourage you to try a competition or two.  There is just something about competition that seems to make us better.

Post me some comments if you try this and it helps you.

Book Review: Implementation Patterns

implementationpatterns Book Review: Implementation Patterns

I finally finished “Implementation Patterns” by Kent Beck and I have to be honest.  I am a little disappointed.  Let me preface this by saying my review of this book is not a reflection of my view of Kent Beck.  Kent Beck is a programming hero.  He pioneered the adoption of Test Driven Development, invented Extreme Programming and was one of the creators of JUnit.  With that said, I will be honest about the book.

This book is about the low level construction of software and algorithms.  Implementation Patterns looks at the patterns which are applied to programming when creating even the simplest of designs.

The book covers patterns relating to classes, state, behavior, methods and collections.


  • Excellent introduction on implementation patterns
  • Good reference for knowing how to call the thing you know is right, but can’t explain.
  • Section on collections is very good for understanding trade-offs between collection types.


  • Doesn’t read much like a book.  It is a bunch of little pieces on each topic, but they don’t really tie together smoothly.
  • Some of the patterns I disagree with, especially the ones involving using inheritance over a different solution.  (I am not a fan of concrete inheritance.)
  • The book feels like it was not fun to write, like it was a labor of filling up pages.
  • The treatment of collections perhaps belongs in a different book.  The appendix which talks about performance measurement definitely does.  A large amount of the book are these two topics.
  • The framework section seemed a little strange in this book and it didn’t really have enough information to be useful.

What I learned:

There is always something still to learn, and I did learn one very important concept from this book.  Kent talks about Values and Principles in the 3rd chapter of the book.  This concept has been something that I haven’t been able to put into words, but I have known it is there.  Kent very clearly describes the differences between values of programming and principles, and how principles are built on top of values.  Often, I have a hard time in my mind accepting the need for making trade-offs between one or more principles.  He very clearly addresses this issue, leading back to the values for ultimately making the decision.

I learned many names for things I was doing, but without knowing what to call them.

I also learned quite a bit about Java collections which I did not know before.  I found out some good considerations when writing code to determine performance, which I would probably have not considered until reading this book.

C# vs Java Part 4: The Tools (Final)

This is my final installment of the C# vs Java series, but I think this is one of the most important.  Tools make or break a development environment.  Good tools can make a hard job seem easy and bad tools can make an easy job seem hard.  My definition of a tool is: anything that helps you work.  This could include IDEs, external libraries, frameworks, testing tools, etc.


A good place to start looking at tools is IDEs.  You have heard it said that you should buy a good mattress because you spend 1/3rd of your life in bed.  If you are a programmer, you spend 1/3rd of your life in an IDE.  (If you are a bad programmer you spend 1/3rd of your life in the debugger in the IDE, but that is another story.)  For that reason, an IDE is very important, perhaps one of the most critical choices when choosing a programming environment.  Fortunately, both Java and C# have good choices here.

As far as IDEs go, C# basically has Visual Studio.  There are some open source and other strange things out there claiming to be a C# IDE, but as far as I have seen, they are not serious considerations.  (Correct me if I am wrong here.)  Being the only game in town means that Visual Studio had better be really good.  It is good; there are many things it does automatically for you.  For the most part Visual Studio does everything you would want it to do, but it is missing some things that the Java world has.

In Visual Studio, classes are not auto imported when you start to type.  This is kind of hard to explain, but in Eclipse, I can start typing the name of some class and the IDE will search all the code I am linked to and try to find any matches for it.  If I select that class, Eclipse will automatically import that namespace for me.  Visual Studio requires you to know the namespace of the thing you are looking to use.  Not a huge deal, but if you start using Eclipse and then switch back to Visual Studio, you will certainly feel the pain in that area.  Now, most of the ails of Visual Studio can all be remedied by the use of a plug-in that I highly recommend, Resharper.  Resharper makes Visual Studio awesome.  It is not free, but it is money well spent.  It adds many automatic refactoring options and many of the features that are available in Java IDEs that are missing from Visual Studio.

In the Java world, there are 3 major choices: Eclipse, IntelliJ and Netbeans.  I have mainly used Eclipse, so I do not have as much of an idea about the others.  I have heard many good things about IntelliJ, and considering it is made by the same company that makes ReSharper, it is probably pretty good.  The reason I like Eclipse though is because of all the plug-ins.  It is also the reason I don’t like Eclipse.  The Eclipse community is thriving with plug-ins; as a result there isn’t much you can’t do from that IDE.  There are so many plug-ins for Eclipse that entire companies exist just to bundle them together.  Think about that for a minute.  This is both good and bad.  It is good because you can do just about anything you want to do in Eclipse.  It is bad because too many choices are confusing and you always wonder if you are doing the right thing since there is no clear-cut answer.  Visual Studio doesn’t have very many plug-ins at all, but Eclipse thrives on them.  Eclipse is also very good at searching code.  There are many hot keys in Eclipse which will allow for searching for classes or files and finding methods in classes.

The IDEs in both environment are similar, offering much of the same basic functionality, but overall Eclipse is more powerful than Visual Studio.  One the flip side though, Visual Studio is much easier to use.

The Rest

There are far too many other tools to handle in direct comparison.  Instead, I can make some generalizations about the tools available in general.  A large amount of the tools available to C# are direct ports of the same tools which were first created in Java.  In this respect C# and Java have a pretty equivalent tool set for unit testing, logging, builds, and dependency injection.  This is very helpful in transitioning from one language to the other, as knowing one of the tools in one language gives a benefit of knowing how to use the tool in the other language.

The big difference I see here though is open source versus commercial software and tools.  In the C# world, there are plenty of open source tools, but a good majority are tools that are not free.  Contrast this to the Java world, where most of the tools are open source.  This aspect can be quite deceiving.  It seems like free tools are good, and they can be, but often the cost of free tools is overlooked.  There are several companies that do nothing but sell support contracts for free software.  Often the support contracts are more expensive than equivalent commercial software on the C# side.

Another common issue I face when working in the Java world and trying to get or find tools is the road of dead software.  There are tons of open source projects which no one has been actively working on for several years.  Often, I find it extremely difficult to figure out which tool is being used and actively worked on the most.  Even when I am able to sort through the hundreds of options, only some of which are still alive, it is often very difficult to find information about how to use the tool or framework.  On the C# and .NET side, there are much fewer projects and much fewer dead projects.  I find it much easier to find the tool most people are using and to get it up and running quickly.


In general, I feel like I can find a tool for a job much more quickly in the .NET/C# world than I can in the Java world.  I can also quickly find out how to use a tool instead of hunting through documentation.  I would say it is just more simple.  On the other hand, Java has a much larger selection of tools that can typically do more, at a cost of increased complexity and difficulty in finding the right tool.  My personal preference is C# and .NET tools because I don’t like to waste a large amount of time trying to figure out what to use and how to use it.

Well, that is it for my coverage of C# vs. Java for now.  I am actually getting kind of tired comparing the two.  Hopefully I have done a good job of presenting a fair picture from the perspective of a developer currently using both technologies.  Now… on to more exciting stuff!

C# vs Java Part 1: Language

C# vs Java Part 2: Platforms

C# vs Java Part 3: Frameworks