Posted by: jsonmez | May 27, 2012

Types of Duplication in Code

One of the biggest reasons to refactor code is to eliminate duplication.  It is pretty easy to introduce duplication in our code either unintentionally or because we don’t know how to prevent or get rid of it.

The three types of duplication

I’ve found that there are three basic types of duplication that we can eliminate from our code that successfully build on each other.

  • Data
  • Type
  • Algorithm

Most developers tend to get stuck at the data level, but in this post, I will show you how to recognize type and algorithm duplication and refactor it out of your code.

duplicate-content

Data duplication

The most basic type of duplication is that of data.  It is also very easily recognizable.

Take a look at these methods:

public Position WalkNorth()
{
   var player = GetPlayer();
   player.Move("N");
   return player.NewPosition;
}

public Position WalkSouth()
{
   var player = GetPlayer();
   player.Move("S");
   return player.NewPosition;
}

public Position WalkEast()
{
   var player = GetPlayer();
   player.Move("E");
   return player.NewPosition;
}

public Position WalkWest()
{
   var player = GetPlayer();
   player.Move("W");
   return player.NewPosition;
}

 

Pretty easy to see here what needs to be refactored.

Most developers don’t need any help to realize that you should probably refactor this code to a method like the following:

public Position Walk(string direction)
{
   var player = GetPlayer();
   player.Move(direction);
   return player.NewPosition;
} 

 

In this example data is duplicated.  To be specific the string data of the direction passed into move is duplicated.  We can eliminate that duplication by creating a method that parameterizes the differences represented by that data.

Type duplication

Now, data duplication is where a majority of developers stop, but we can go much farther than that.  In many cases the difference between two methods is only the type in which they operate on.

With the use of generics in C#, we can refactor out type and parameterize this concept as well.

Look at this example:

public int FindIntMatch(int i)
{
   var match = (int)container.Get(i);
   return match;
}

public string FindStringMatch(string s)
{
   var match = (string)container.Get(s);
   return match;
}

 

Here we have two method that do pretty much the same thing, but they just differ on the type they operate on.  Generics gives us the ability to actually refactor out that type information just like we would with data.

public T FindMatch(T t)
{
   var match = (T)container.Get(t);
   return match;
}

 

By refactoring to the above method we have eliminated duplication. We have achieved this by refactoring out type.

Algorithm duplication

Without a good understanding of delegates and functional programming, few developers ever even consider refactoring out algorithm duplication, but it can be done fairly easily.

Take a look at this example:

public void GoForRun()
{
   GetDressed();
   Run();
   Shower();
}

public void LiftWeights()
{
   GetDressed();
   Lift();
   Shower();
}

 

It is a pretty basic example, but it highlights the kind of duplication that I often see left in many code bases.  Delegates in C# allow us to treat functions like data.  With this ability we can easily refactor out the commonality in these two method to get something like this:

public void DoFitnessActivity(Action activity)
{
   GetDressed();
   activity();
   Shower();
}

 

We could have also refactored out this duplication by using an abstract base class and having the inherited classes definite their own fitness activity, but using delegates creates a much simpler approach and casts the problem in the same light as refactoring any other type of data.

Combining them together

Often I find that several different types of duplication are present across several methods in a class.

When this is the case, it is often possible to apply data, type and algorithm duplication refactoring techniques to find the most simple and elegant solutions.

I’ve also found this is a skill that must be practiced.  When I first really started using generics and delegates in C#, I had a hard time finding uses for them, because I could not easily recognize the patterns of duplication that called for them.  But, I found over time that it became easier and easier to recognize where these techniques could be applied to reduce duplication in my methods.

I’ve also found the key to eliminating duplication is sometimes to first exaggerate it.  Often I will purposely take two methods that I know have some duplication and make them look even more duplicated in order to be able to clearly see where the duplication lies.  I may do several small refactoring steps to get to the point where it is easy to identify what data, type or algorithm is being repeated.

Posted by: jsonmez | May 6, 2012

Wrapping Callbacks

I’ve recently had the problem of trying to display a progress dialog when executing an asynchronous operation and to dismiss that progress dialog when the operation completes.

I wanted to build a way to do this that is generic to my application, so that it would work with any asynchronous operation in order to reduce duplication of writing progress dialog logic everywhere in the code.

11-290x300

Looking at the problem

So here is some basic pseudo-code of the problem.

public void DoCall()
{
   ShowProgressDialog();
   RemoteService.DoAsync(CallBackMethod);
}

public void CallBackMethod(Result result)
{
    HideProgressDialog();
    // Process result;
}

Now the problem with this code is that it would have to be repeated everywhere I want to make an asynchronous call and display a progress dialog.

If I want to do this in my application every time that I make an asynchronous call, I have to put this kind of code in many places in the application.

You can also see a mixing of responsibilities here.  We are handling UI related showing of a progress dialog split between an initial call and the callback.  It just seems a bit dirty to do things this way.

Breaking it down

So how can we solve this problem?

Go ahead and think of some way that you might be able to solve this.

One of the best ways that I have found to solve any problem like this is to work backwards.

Let us assume that any syntax we can think of is possible, and then only change the ideal syntax if it proves to not be possible.

What do I mean by this?

Simple, let’s come up with the way we want this code to look and we will worry about implementing it later.

It would be nice to be able to execute an asynchronous method and display a progress dialog with a one-liner, like so:

UIServiceCaller.ExecuteAsync(RemoteService.DoAsync, CallBackMethod);

If we could just do this wherever we want to make an asynchronous call and automatically have the progress dialog shown and dismissed, life would be wonderful.

Solving the problem

In order to solve this problem, we can do something very similar to a decorator pattern.

We can basically just wrap our callback method with a new callback that adds the functionality of dismissing our progress dialog.

So the idea will be that we will do the following steps in our ExecuteAsync method:

  1. Show the progress dialog
  2. Wrap our callback with one that dismisses our dialog and then executes the callback.
  3. Execute our asynchronous operation passing the new wrapped callback as the parameter.

gift-wrap-nature-lovers-easy-style-fabric-wrapping-1211-l

Here is what this looks like in code:

public static void ExecuteAsync(Action<Action<Result>> asyncMethod, Action callback)
{
   ShowProgressDialog();

   Action wrappedCallback = (r =>
   {
      DismissProgressDialog();
      callback(r);
   }

   asyncMethod(wrappedCallback);
}

This code actually looks more complicated than it really is.

You will need to understand how Action works though.  If you don’t, check out this post I did explaining Action and Func.

Understanding the solution

It can be a bit hard to wrap your head around Action of type Action of type Result.

Let me translate this to make it a bit easier.

The first parameter to ExecuteAsync is a method that takes another method as a parameter (the callback,) which takes a Result object as a parameter.

Go ahead and read that over until you get it.

So, the idea here is that we are passing in the method that is going to do the callback as the first parameter to your ExecuteAsync method.

Then we are passing in our actual callback as the 2nd parameter to ExecuteAsync.

The idea is that we are splitting apart the method and the callback it takes, so that we can insert our code to handle the dialog where we need to.

Now we can just call ExecuteAsync and pass it our method and its callback and progress dialog code will automatically be handled for us.

Building on the idea

We can expand upon this concept in several ways.

One thing we could do is also apply error handling logic to the callback wrapper method.  We could preprocess the result in some way before passing it to the callback.  This could allow us to display an error message or even retry a number of times before executing the callback.

Another thing we could do is to change the signature of the ExecuteAsync method so that it takes a type T instead of Result; this would allow us to handle any kind of return type and method, and the ExecuteAsync method would work with just about any asynchronous method call.

Posted by: jsonmez | April 23, 2012

Predicting the Mobile Future

Many people have been asking me about my predictions for the future as far as the mobile platforms go.

I thought I would take a moment to write up a blog post detailing out what I think we will see in the next couple of years for mobile phones and tablets.

gn-psychic

Windows 8 changes everything

Or at least it has the potential to.

There are quite a few game changers built into Windows 8 that have a huge potential to influence and disrupt the market.

One OS for mobile and desktop

The idea that Windows 8 will essentially run on mobile and desktop is going to force the hand of other platforms.

I really like my iPad, but it could never be a total PC replacement.

Now imagine what happens if I can have an iPad, but it can snap right into a keyboard to make it into a laptop and it is running an OS that can do everything I need.

Suddenly I have to question why I need a separate iPad.

PC manufacturers have been chomping at the bit to break into the tablet market for some time now.  It was a slap in the face for Apple to produce the first generally accepted “good” tablet after so many PC manufacturers had tried and failed for years earlier.

We can learn a lot from a tablet

What makes the iPad so good?

In my opinion, 4 things:

  1. Extremely portable and lightweight
  2. Good touchscreen input, so I don’t need a physical keyboard most of the time
  3. App store!
  4. Instant on

There isn’t even a need for a Windows 8 tablet.  Instead, I predict we are going to see Windows 8 Ultrabooks with removable keyboards.

As long as this new class of computers can hit the 4 items I like about the iPad, it could really cause some disruption in that market.

What about the cloud?

cloud_0

I see some big things changing and evolving on this front as well.

Apple introduced iCloud and my first real experience with it as a consumer was playing a game on my iPad, then switching to my iPhone and having the game restore me to the exact point I was on the iPad.

This will become the standard.

Regardless of how devices transform, I don’t see us getting away from having some kind of a phone.  We might merge tablet and laptop, but we are going to always have at least two devices.

It is going to be expected that data from one device is available on the other device.  Many applications already support this, but I predict that we will see this get more tightly integrated into the operating system.

Microsoft, Google and Apple are all heavily invested in this area with a few different twists, but I see all the paths eventually merging to cloud based OSes with full app virtualization that streams bits to be executed to the clients and has the clients cache the app code.

What does this mean?

It means your user experience changes so that you log into your phone or tablet and when you do, you see the same thing regardless of device.  You don’t even know you have two different devices, except for the form factor.

It also means that you don’t have the same concept of apps for your phone or tablet anymore.  Instead you purchase an app and it is streamed to you when you want to use it.  So as a user, you don’t need to worry about downloading the application or managing updates.

Think of it as the web, but instead of HTML you have binary executable code.  Spoon already does this.

How about development?

If you are reading this blog, you are probably more interested in what is going to happen in terms of developing applications for these platforms.

I have some predictions here as well.

Right now it is very difficult to develop an application that will run on multiple platforms.  Trying to target Android, iOS and Windows Phone is a bit of a challenge.

Even with great tools like MonoTouch and Mono for Android or PhoneGap, it is no easy task.

There is a big push to make everything web apps.  Some people believe HTML 5 will be the future, but I am not quite so sure.

I do think that the most successful platform, in the long run, will be the one easiest to develop for.  History tells me this is true.  (Why is Windows so successful?)

Microsoft again has a chance to change the future with Windows 8’s WinRT.  Suddenly web developers can write Javascript to program windows.  Not only that, but they can reuse much of that code to create a web application.

Think about where Windows 8 will run.  Desktop, laptop, tablet, phone.  Suddenly, you can create an application that can run on all of these devices, with pretty much the same code.

So what does this mean for iOS and Google?

I predict that this year Apple will announce a new programming model for iOS which will be based on Javascript.

I wouldn’t be surprised if Google did the same thing for Android.

It really makes sense on the iOS side though.  Apple is going to have to merge iOS with OSX to compete with Windows 8.  In addition, they need a better programming model.

Writing iOS apps in Objective-C is horrible!

Apple is going to have to do something to prevent web developers from flocking to Windows 8.

In the near future, I think we will be able to write applications with the code of the logic in Javascript or another language of choice, which binds against Javascript APIs for each platform.

Summarizing my predictions

So in short, here is what I think will happen within 2-3 years.

  1. Tablets and laptops merge as Window 8 targets both and iOS merges with OSX.
  2. Cloud based operating systems replace standard OSes and virtualize apps by streaming them to users.
  3. All surviving platforms natively support a Javascript based API.
  4. Decrease in need for web apps, since streaming binary apps replace that niche.

I could be wrong, I’ve been wrong many times before, but those are my predictions as of now.

Posted by: jsonmez | April 16, 2012

Validate User Input, Not Developer Input

I have a very simple rule, I like to follow that helps to simplify my code.

“Don’t validate developer input”

This rule simply means that we should not try and validate input that came from a source that is not a user or external system.

Another way to put it would be, don’t validate parameters you pass around in your own code.

γνῶθι σεαυτόν

(Know thyself)

knowthyself

While you can’t guarantee input from another source is valid, you can know that your own code’s input is valid.

When writing a method, we should really strive to know who is calling that method and put the onus on the caller of the method not to pass in junk.

I know this isn’t a popular opinion, because it seems to go against the idea of “defensive programming,” but the idea of defensive programming is misunderstood.

Chuck Norris himself once said:

They say the best defense is not to offend.

defense

That slogan applies well here.  Your strategy should be to make sure you always pass valid values into methods rather than trying to code methods to defensively do things with bad input.

(Let’s not be uncivilized!)

Let me give you an example:

var milkShakeMaker = new MilkShakeMaker();
var shake = milkShakeMaker.MakeShake(icecubes, milk, ingredients);

public class MileShakeMaker
{
   public Shake MakeShake(IEnumerable iceCubes,
             IMilk milk, 
             IEnumerable ingredients)
   {
      if(ice == null || milk == null || ingredient == null)
          throw new InvalidArgumentException("You passed in a null, duh");
      if(ice.Count < 1)
          throw new InvalidArgumentException("You need ice.");
      if(milk.IsSpoiled)
          throw new SpoiledMilkException();
      foreach(var ice in iceCubes)
      {
          if(ice.IsMelted())
             throw new MeltedIceException();
      }

     if(ingredients.Count < 1)
         throw new InvalidArgumentException("You need some ingredients.");

     ...

   }
}

 

Doesn’t that code look silly?

This is the exact opposite of what I am suggesting.

Rather than trying to decide which of these checks we should keep, and trying to follow some complex set of rules of when should we validate input like this, I am merely suggesting we get rid of all of it!

I’ve written about not checking nulls before, but I am convinced now that checking any input from code you control is a code smell.

What can you do?

Throw an exception at best, at worst, infer what was meant by the caller and corrupt data.

What purpose does throwing an exception there serve?  If you try and dereference a null object, you get an exception anyway.

Are you even going to catch an exception if you throw it?

If so, does that mean you are wrapping every method call you make in a try / catch block?

The big problem with trying to validate input that was passed to you by code you control is that you can’t really do anything useful.  You are just cluttering up your code.

Another question, if you are still gung-ho on validating input on all method calls… Do you even do it?

Do you actually check every parameter, or just when you remember.  Because, if you aren’t applying the checks uniformly, you cannot count on them.

Context

One major reason why I advocate validating what you pass into a method rather than what is passed into a method, is context.

If you are inside a method and someone passes you a null, you have no context.

What was going on that cause this parameter to be null?  I don’t know—I can’t know!

But—on the other hand, if I am about to call a method and I am about to pass that method a null, I know why.  I know that the list I got back was null and I could check for that and instead pass in an empty list to the method I was about to call.

Better yet, I can take it one more step further and not ever pass null back from the method that returns the list in the first place.

The point is that you have way more context before you call the method, than you do when you are in the method.  If you are going to validate the input, do it in a place where context will allow you to do something meaningful, rather than just throwing a random exception.

Better code

Thinking this way will force you to write better code.  I firmly believe it. 

Most of us don’t really think about what we are passing into methods or whether or we are returning nulls from methods, we instead tend to think about what we are being passed.

By changing things around, it leads us into better coding practices that are less error prone.

We are forced to think about standardizing and restricting ranges of values for parameters.

We are forced to start considering making our objects immutable, so that if we properly initialize them, they cannot contain null values.

Most importantly, our code becomes cleaner, because it isn’t littered with error checking.  Instead of checking for errors everywhere, we are coding in a way that prevents them from being possible.

So the next time you are thinking about validating parameters passed into your method, by another method you have control over, don’t do it!

If you can’t trust yourself, who can you trust?  (Chuck Norris perhaps?)

Posted by: jsonmez | April 1, 2012

Deployment Made Simple

Deploying software doesn’t have to be that complicated!

I’ve seen and built many software building and deployment solutions over my career, and I have come to find that most software deployment can be boiled down to a simple process.

I’m not trying to give you a solution for your software deployment automation, nor am I trying to perfectly model your exact process.

What I am trying to do in this post, is to help you to simplify your process.

If you can identify the parts of your deployment process that fit into the simple steps I am going to outline below, it should be much easier for you to automate your deployment process.

PROSTAGLANDIN_H2_SYNTHASE-1_COMPLEX

The process

Even though software build processes, infrastructure and components are unique, I have found that most software deployment processes can be simplified into the following steps.

  1. Build software without configuration
  2. Create environment specific configuration.
  3. Create a set of database changes.
  4. Bundle software, configuration and database changes.
  5. Apply new software
  6. Apply new configuration
  7. Apply new database changes
  8. Start it back up

You might read through these steps and think “well duh.”

You might be tempted to say “my process is more complicated than that.”

I’m not going to argue with you.  You are right, your process is probably more complicated than that.  But, does it need to be?

Can you simplify your process to fit into these steps?

Sure, the implementation of these steps is likely to be fairly complex and vary for each type of software, but if you can distill the process into these steps, you can much more easily automate that process.

Where people go wrong

The big key to my simple version of deployment is

Build software without configuration

You MUST do this!  Departing from this step causes all kinds of pain and complexity.  Please don’t try to build your software and the configuration for an environment at the same time.  These things must be pulled out from the get g or you will have the pain of trying to tease them apart later – or you will have to create separate builds for each environment.

It is also critical that the same bits that were built by your build server are what is deployed to each environment!

I will say that this isn’t the easiest problem to solve.  You may need to have a separate build process that builds up the configuration for an environment.

Separating the two will also force you down the path of building a process to apply that configuration to an environment.

But, if you are willing to accept that this is just a must and bite through this pain, you’ll come out on the other side clean (even though you had to crawl through tunnels of crap.)

redemption

The whole story

Now that I’ve hopefully convinced you to separate your configuration from the building of your software, let’s go over the big picture of a deployment using the simple process outlined above.

It all starts out when you build your software.  Perhaps you have a continuous integration build server setup that is automatically building software on each check-in; perhaps you are manually kicking off a script.

Once you have built your software, you have some bits that you should be able to apply to any environment.  Nothing that you built here should be machine or environment specific in any way.

Now, you kick off another process, or perhaps one was kicked off simultaneously by your continuous integration server. This builds up the configuration for the environment you are going to deploy to.

A similar process is kicked off—also could be simultaneous, for generating a list of database changes that need to be applied to the target environment.

Now that you have your bits, configuration and database changes, you are ready to deploy.

If you are smart, you’ve even built these ahead of time and they are just waiting for when you need them.

Next, gather up the artifacts and move them to the deployment target where you actually apply them.

First, unpack your bits and put the new bits into place.  (You may or may not need to take your application fully offline to do this.)

Then apply the new configuration on top of your newly installed bits for that environment.

Finally, apply database changes for that environment.

Now you should be completely deployed and can start up your application.

But how do I do it?

Perhaps you agree with me that the actual process should be what I have outlined and described, but now you are at the point of implementing a solution.

How do you actually automate this stuff?

Good question.  If you figure out a simple answer, let me know.

This is the point where you might be writing custom tools and scripts to get all this working.  The key is to take it one step at a time.

There are at least two tools out there that I know of that help you do this.  I can’t speak for either of these tools, since I haven’t used them myself, but I have heard good things about them.

One other thing to consider is how you are going to get the right stuff to the right server.  You will want to think about things like:

  • Promoting build products
  • Preloading promoted products to servers to make deployment faster
  • Getting through firewalls by having the software or some other process PULL the upgrade to your target, rather than you PUSHING it there.
  • Rollback, or some kind of mitigation strategy if things go wrong. (My recommendation here is not to get fancy.  I have NEVER seen a successful rollback, only a database restore followed by a manual code restore.  If you mess up bad, just count on restoring the machine and the database.)
Posted by: jsonmez | March 25, 2012

Are You Really Sure You Want to Make a Cancel Button?

Are you really sure you want to create the cancel button for your application?

You know, I might click it.

Not only might I click it, I might click it at the most inopportune time.

I might click it right in the middle of  that large file that you are copying, right after you spun up that 2nd thread.

exploding-earth

Cancel is a commitment

The next time you consider creating a cancel button, I suggest you think of it as a commitment.

In my world the cancel button has two promises.

  1. Stop what is currently happening in a non-destructive way.
  2. Stop RIGHT the F NOW!

I’ve been encountering a good deal of cancel button which don’t obey the basic laws of cancelling that any user would expect.

I have actually been randomly clicking “cancel” whenever I see it, much to my coworker’s dismay.

I started doing this, because I wanted to see how widespread the cancel cancer is.

And it is pretty widespread.  A majority of cancel buttons I have been testing neither stop right away or prevent destruction.

I found instead that clicking the “cancel” button in most programs is sure to hang that program for an extended period of time, ultimately causing you to kill the process, and it tends to leave processes half done without rolling them back.

Clearing things up

Let me be a bit clear here.  I am not talking about cancel buttons you see in an “Ok / Cancel” dialog.  Most of the time those cancel buttons actually work, because they are really operating as “back” buttons, they aren’t actually cancelling a process that is happening live.

I am talking mainly about cancel buttons that cancel an active ongoing activity.  For example, cancel buttons in an installer or during an SVN update.

We could call these kinds of cancel buttons “asynchronous cancel buttons.”

But, I need to provide a way for the user to cancel

Good, but don’t lie about it.

There are certain things that just can’t be cancelled.

When I get on a plane, I can cancel my trip when I am sitting there waiting for the door to close.  I can even cancel my trip while the plane is taxing to the runway, if I yell “I have been RAPED by a BOMB that is on FIRE!

But, I can’t cancel my trip, once the plane has lifted off the ground.  If I try to cancel it then… well, bad things would happen.  Very bad things.

So how come when I am installing your software, or your software is updating its database, I have this shiny little cancel button I can click at any time during that process?

Surely I cannot cancel just any time!

Surely there are parts of the process that cancelling would be fatal or it is too late to rollback.

My point is, if the user truly can’t cancel, don’t present a button that says they can.  More specifically, if you can’t obey the laws of cancel 1 and 2 from above, don’t even show a button.  Just say “sorry, you can’t cancel this process at this time.”

I don’t even need to know why I can’t cancel.  I mean, it will make me feel better if you tell me that the Unicorn Glitter Engine is in a critical state and any disruptions could end life as we know it, but I’ll settle for you just greying out that cancel button or not displaying it at all.

cancel-button

Putting back on the developer hat

I’m guilty of it myself.  I know I have created cancel buttons in the past that have caused pain and anguish.

But what can we do about it as developers?

First off, we should be thinking carefully about breaking a long running process into steps.  At each step of the way we should consider if it is conceivable to cancel that step without destroying data and hanging the application.

In any long running process, we should be able to identify certain parts which are cancellable and those which do not make sense to cancel.

It is your job as the developer to ensure that if you decide to allow for cancelling that the cancel undoes the existing process and work immediately.

I cannot stress this enough!

This is the behavior that most users expect and the very meaning of the word cancel.

To do this might take extra work.  You might have to think a bit more about the threading situation of your application.  You might have to think about rollback situations.  But, if you don’t do it, your cancel button will become just like the boy who cried wolf and no one will believe them.

And if you’re not willing to go through this effort, at the very least, be kind enough to your users to just remove the cancel button, because you can bet I’ll be clicking it!

Posted by: jsonmez | March 10, 2012

Switching Gears is Grinding Gears

Pay attention young programmers, this is the most important piece of programming advice you will ever hear.

Well perhaps not, but it might be the most important piece of programming advice you hear today.

“Switching gears is grinding gears.”

gear-intro

I’ve been doing this programming thing for quite a while now, and I have come to realize that the biggest thing that saps my productivity is switching gears.

What do I mean by switching gears?

Many different contexts

Switching gears can apply to a variety of different contexts, but it is basically whenever you are working on some task or technology and have to stop what you are doing and either do something else or change the type of thing you are doing.

This is really a bit different than multi-tasking.  Multi-tasking is really trying to do more than one thing at once.  It usually involves a large amount of rapid context switches, but for this post I am more concerned about the general idea of breaking rhythm.

I think it is easier to speak about this subject if we talk about some specific applications of the idea and why they are harmful.

Switching problems

In the Agile world of software development today, we often are required to switch from problem domain to problem domain as many of our iterations contain mixes of different features on different parts of the system and bugs to be fixed.

Have you ever been in the situation where you were just beginning to understand how some area of the code base worked, or how to work with a particular customer on a particular problem space and then had to switch to something else and start all over again?

Even when you switch back to the original context you were working with, if enough time goes by, it becomes new again.  You have to relearn much of what you had learned the last time and just when you begin to hit your groove, the cycle begins again.

This form of switching gears is at the very least frustrating, and at the most a complete demotivator and productivity sapper.

Unfortunately for most developers, this problem is out of your immediate control.  But, take note product owners and project managers, there is a reason why iterations should have a goal.

If you are in the precarious position of being a developer pinned against the ropes, try to make some noise and let your management and product owners know that your team will be much more efficient when you aren’t switching gears all the time.

In my experience, the results of replacing this constant context switching with the synergy of a common goal and related features in a segment of time has an astounding effect on productivity that is hard for any serious businessperson to ignore.  So speak up!

Clss_065

Switching technology

This is the primary reason why I have a distaste for JavaScript.  It is why even in this abundance of web development, I would still rather program a client application.

Switching technology is painful!

This is one of those things that is unavoidable in todays development environment.  If you are a web developer, you are going to be working with HTML, JavaScript, probably some sort of server side language, and most likely some form of SQL.

It really isn’t worth trying to fight this because you are going to be going against the technology grain to do so.  Although, I do suppose this may be one of the reasons for the recent popularity of Node.js.

What we can try to do is to minimize the context switch as much as possible.  We do this by sticking with a particular way of doing things and not chasing after each new technology of JavaScript framework that comes out each week.

I’m not saying to not learn new things.  It is very important to always be learning.

What I am saying, is to try to find some kind of rhythm with the technology stack you are working with and try not to switch that up.

Technology specific training can really help here as well.  I for one, need to learn JQuery better.  The problem is that when I am working on a web based feature, I am not forced to learn JQuery because I am not in that context long enough.

So what do I do instead?

I waste time Googling for answers.  I know that I have a short coming here and I need to just bite the bullet and spend some dedicated time to really thoroughly learn JQuery, because by Googling for little pieces of it at a time, I am not really making much headway and the context switch ends up stealing what I do learn from my memory.

One more aspect of this is the idea of focused teams.  Many software development groups do not like to specialize their developers onto one focus area.  I agree whole-heartily with the idea of non-specialization. 

But!  There is huge benefit to be gained by keeping the same group of developers working on a specific set of technology or part of the code base for a set period of time.  I’ll talk about this a bit more, towards the end of this post, but the basic idea is that it takes time for people to find their groove.

I think it is optimal to break any large team up into smaller technology area focused teams that regularly rotate every 3 months or so.  The idea here is that you give those teams enough time to get good at what they are doing and actually commit what they have learned to memory, but you rotate them often enough that they don’t end up becoming specialists which are unable to see the whole picture.

Switching teams

This one typically isn’t an issue, but it can be depending on the environment that you are working in.

Teams need enough time to go through that forming, storming, and norming set of phases.  If you are constantly interrupting this process by switching around team members, you are never going to get the team to act as an entity of its own.

Teams are generally more efficient than individuals, because they benefit from synergy, when 1 + 1 = more than 2.

But just like a big truck taking some time to get up speed, a team takes time to get going.  Also like a big truck, a team can gain momentum that individual developers seldom can achieve.

A smaller aspect of this is pair programming.  I suppose that many have been successful switching up programming pairs once a day or so, but I suppose that more teams have been successful switching up pairs at longer intervals.

For me, this interval varies.  Sometimes, I feel like I need to stay paired with a teammate for longer than 2 weeks, which is our regular interval, sometimes 2 weeks is fine.  It depends on what you are working on and how much momentum you have.

They key here is to make sure that you are giving teams enough time to take up their own flag and stake their territory.  Teams can take some time to find their common goal.  Self-direction can really help with this.

The groove

Ever tried to turn a flat head screw with a screwdriver, but it doesn’t quite turn, because you can’t seem to get the head of the screwdriver into the groove of the screw?

This Shutterstock image #2798630 was downloaded on 3-13-07 for HSW: QUICK FIXES FOR YOUR HOME, 730175.

You twist that screwdriver around a bit until finally it slips into the groove.  Then when you turn the screwdriver the screw turns with it.

As humans, we tend to be like screwdrivers, we have to find our groove.  We all have this adjustment period where we are fumbling through things. 

It is very important to make sure that we aren’t switching gears so often that we are not actually turning any screws once we are in the groove.

Regardless of what kind of context switching you are doing—whether it is problem domain, technology or teams—it is important to make sure that you are not spending 90% of your time finding the groove and only 10% of your time “in the groove.”

Depending on what you are doing and what the context switch is, the proper amount of time before switching contexts is going to vary, but I think it is very important be aware of this phenomenon and plan around it.  If you don’t you are going to end up spinning your wheels, which is unfulfilling to say the least.

Posted by: jsonmez | March 3, 2012

Small Refactorings are OK

Many programmers seems to get caught up on the idea of refactoring.

Most of us are familiar with the Boy Scout rule which says:

Always leave code better than when you found it

But do you actually apply it in your day to day work?

I’ve found that for myself the answer to this question is sometimes “no.”

boyscout

Why we don’t follow the rule

Personally, I know that there are many reasons why I have failed to follow the Boy Scout rule in my own day to day coding activities.

How often do you say to yourself something like:

“Yeah, I’ve just got to get this code checked in.  I don’t have time to clean it up.”

Or

“Refactoring this correctly would take too long, and I want to make sure I do it right.”

At first glance, these seem like perfectly valid excuses, but the problem is that the cumulative effect of this kind of thinking is exactly what causes code rot.

“Code rot” is when code from your application begins to become brittle and hard to maintain.

As software developers we should really strive to prevent code rot, and regularly refactoring and cleaning up code, is like brushing the teeth of our application.

There are definitely a large number of excuses I come up with for not refactoring code, but I would say that the number one mental block is this idea of perfection and needing to do it right.

Small refactorings are good!

One thing I try to tell myself is that small refactorings are good and I don’t need to solve the whole problem all at once.

We shouldn’t let the fact that we can’t completely clean up a section of code or refactor it to the final structure we want, prevent us from putting that code on a bus headed that direction.

Many programmers tend to have the perfect solution mindset which requires us to find the 100% best solution to a problem and think that the 95% effective one is no good.

This mindset can be a huge stumbling block to productivity and it can also be a big hindrance to keeping our campsite clean.

It is often helpful to embrace that a series of small changes can be more beneficial than one large change of the same resulting magnitude, even if the small changes end up requiring more total work.

The reason for this is two-fold:

  1. Big changes rarely actually get done, so they are put off
  2. Small changes usually are more natural and evolve the code in an organically correct direction.

Going backwards to go forwards

I even find that many times I take one step backwards in order to go two forwards.  Refactoring sometimes has to just progress naturally as you make something clearer, only to undue it a bit later with another change that ends up making more sense once you can actually see the problem being solved more clearly.

Think about solving a Rubix Cube.  If you have ever attempted to solve one of these things, you know that sometimes you have to wreck that perfect wall of green in order to start getting the white blocks in place.  Many times it is impossible to solve a Rubix Cube without traversing backwards in the solution first.

rubix

The point is, don’t be afraid to get out there and make something clearer, or go a direction that seems like it will at least improve the code.

You don’t have to find the perfect design pattern to refactor the code into in order to start making changes.

  • Start by changing this variable name to be a bit more clear.
  • Extract those lines of code into a method that makes that functionality more clear.
  • Get rid of some duplication here and there.

The active code reader

When I am in my “zone” and doing things right, I am even refactoring code while I am reading it.

There is no better way to understand some code than to refactor it.

Think about it, how do we learn?

We read something or are taught it and then we rephrase it differently to confirm understanding.

“Let me get this straight, are you saying… blah blah blah?”

“Oh, now I get it, if I do blah and blah then blah blah?”

Why shouldn’t we do this with code?

I know some of you are really scared by this idea, and you’re saying “nope, don’t just go touching code you don’t understand, John.  You are not getting anywhere near my code base.”

But, give it a shot, what is the worst that is going to happen?  You are going to refactor yourself into a dead end and have to revert your changes?

More likely than not, you will end up learning the code better and improving it.  Two for one!

One more analogy then I’m done

I promise!

Ever solved a crossword puzzle?

Did you sit there and immediately fill in all the answers one by one?

Perhaps you filled in some answers that you knew.  Perhaps the short ones first, then you went back over all the clues again and suddenly found that with some letters filled in you could better guess the clues.

Most likely you made several sweeps like this until you finally solved the puzzle or gave up in disgust wondering why you wasted an hour of your life and who the heck studies books on geography that could actually solve this puzzle.

Do you think it would be any different with code?  Making small refactorings is like filling in the clues you know the answer to in a crossword puzzle.  As you keep refactoring, the answers to other puzzles about the code and which way it should go become clearer and clearer.

Don’t try and solve the whole puzzle one by one in a single pass.

Posted by: jsonmez | February 21, 2012

Refactoring Switches to Classes

I’ve talked about refactoring switch statements several times before.

I’ve even created a defaultable dictionary for refactoring a switch statement into a dictionary of actions.

This time, I am going to talk about refactoring switches when you have switch statements operating on the same set of data, but have different actions in different circumstances.

switch

First let’s recap

When I talked about refactoring switches before, we were mainly dealing with a single switch statement somewhere in code.

In the case where you have only a single switch statement, or multiple switch statements that do the same thing based on the data, using a dictionary is still a great way to go.

However, there are going to be circumstances where you are going to be switching on the same data, but in different contexts.  In these cases, you will want to perform different actions.

Let’s look at an example.

// In fighting code
switch(classType)
{
    case WARRIOR:
          swingSword();
          break;
    case MAGE:
          castSpell();
          break;
    case THIEF:
          backstab():
          break;
}

// In wear armor code
switch(classType)
{
    case WARRIOR:
          return CAN_WEAR;
    case MAGE:
          return isConsideredLightArmor(armor);
    case THIEF:
          if(isSneaking)
              return NOT_NOW;
          return isConsideredLightArmor(armor);
}

In this example, we are switching on the same enumeration, but we are doing it in different locations of the code.

Using a dictionary would not work well here because we would need multiple dictionaries.

We still don’t want to leave this as it is though, because the code is pretty messy and fragile.

Mage

Separation of concerns

The problem is the code that contains these switch statements has too much responsibility.  It is being asked to handle logic for each one of our character class types.

What we need to do to improve this code is refactor the enumerations into their own classes.  Each switch statement will become a method that will be implemented by our enumeration based class.

If we are using Java, we can use Java’s enumeration implementation that allows for methods on an enumeration.  If we are using a language like C#, we still have to map the enumeration value to each class.

Let’s start by making our classes.

First we need a base class, or interface.

public interface CharacterClass
{
    void Attack();
    ArmorResponse WearArmor(armor);
}

Now we can create classes that implement this interface, that contain the logic that was in each switch statement.

public class Warrior : CharacterClass
{
    void Attack()
    {
       swingSword();
    }

    ArmorResponse WearArmor(armor)
    {
       return CAN_WEAR;
    }
}

public class Mage : CharacterClass
{
    void Attack()
    {
       castSpell();
    }

    ArmorResponse WearArmor(armor)
    {
       return isConsideredLightArmor(armor);
    }
}

public class Thief : CharacterClass
{
    void Attack()
    {
       backstab();
    }

    ArmorResponse WearArmor(armor)
    {
       if(isSneaking)
           return NOT_NOW;
       return isConsideredLightArmor(armor);
    }
}

Next we can map our enumeration to our class.

public Dictionary characterDictionary =
    new Dictionary {
    { WARRIOR, new Warrior() },
    { MAGE, new Mage() },
    { THIEF, new Thief() }
};

We could also get rid of the enumeration if we wanted, and just create the appropriate class.  It will depend on what your existing code looks like.

No more switches!

Now let’s take a look at what we end up with in the two locations where we had switches.

// In fighting code
myCharacter.Attack();

// In wear armor code
var armorResponse =  myCharacter.WearArmor(armor);

If we want to add a new character class type, we just add a new class that implements the CharacterClass interface and put a mapping in our dictionary, or in our character initialization code.

If we end up having other places in our logic where different character class types should have different behavior, we just add a method to our CharacterClass interface and implement it in any classes that implement CharacterClass.

Our code is much more maintainable, and easier to understand.

Posted by: jsonmez | February 16, 2012

Pushing Through the Pain

Life ain’t easy!

It ain’t meant to be easy.

Sometimes in life – if you want to achieve anything of worth – you have to just push through the pain.

Yes, this is another post about burnout.

unicorn3

There is no such thing as burnout!

Do I believe that people, and programmers especially, suffer from the symptoms of what is described as burnout?

Yes, absolutely!

The problem is that we tend to batch up these symptoms into one big classification we call burnout.  I’ve written about this topic before, I call it programming lethargy.

I think this topic is so important that it is worth talking about again.

Most advice out there will tell you to step away and refresh yourself.

I’m going to tell you the exact opposite!

Now, I’m not going to suggest you never go on vacation or step away from a problem, but I am going to tell you to…

Push on and push harder!

Greatness is just on the other side of that wall.  When you hit burnout, you are really hitting a wall.

This wall is caused by interest and motivation dropping when results are relatively flat.

chart

Imagine that when you first start an activity your interest is very high.  As your start doing that activity your motivation increases quickly.

You get some immediate feedback as you start to gain results.

Over time the new thing become mundane, so your interest starts to drop.  Your results are relatively flat so motivation follows as well.

This is where the wall exists.

You could call it the road to competency.

It is pretty hard to push beyond this point, because you have to do it without motivation or interest.

Few people do.  That is why greatness is hard to come by.

Searching for greatness

Let’s take a minute to dwell on that idea.

Why do some people achieve such great fame and fortune while others live fairly mediocre lives?

I’m going to pick on a person who I think is pretty famous in the developer community to make my point, Scott Hanselman.

You probably already know who he is.  I was on an episode of one of his Podcasts and that was a big deal for me.  So, if being on his show is a big deal, just imagine how big of a deal it is to be Scott Hanselman.

The question is, why is he so successful?

I think we can describe it in one word- consistent.

If I had two- persistent and consistent.

His podcast is on Show #305 at the time of this writing.  Every week Scott puts out a new podcast.  It is a large amount of work.

About 1 to 2 times a week he usually puts out a new blog post, also a large amount of work.

And I am sure he does countless other things that he doesn’t want to do, but he does because he has a goal in mind.

He’s got kids, he has a full time job, and he has the kind of diabetes where he has to give himself insulin shots everyday.

I am pretty sure he wakes up some mornings and says, “Holy Crapola! I don’t feel like writing a blog post and making a podcast.”

But guess what he does that makes him great?

He does it anyway!

He doesn’t change gears and go a different direction.

He doesn’t pursue some other interest or look for a new job.

He pushes on and pushes through and therein lies his success.

It can be yours as well.

Ask yourself how long he had to go on being consistent and persistent before he saw results?  I bet it took a pretty long time.  I bet he hit a wall at more than one point along the way.

Beyond the wall

dont-burn-out

The point is, most people lose their motivation and interest in something and decide to switch gears or take a break or leave a project half finished.

I am the worst of the worst of this kind of person naturally!  Really I am!  I am a “lazy, good for nothing, just hand me the world on a platter kind” of guy.

But somehow I’ve learned to grit my teeth, put one foot in front of the other and walk forward.

Earlier in my career, I switched jobs pretty frequently.  I started projects and left them unfinished.  I sapped away countless hours on things that distracted me from bigger goals and big rewards.  I often sought to cure my burnout by reeling away from the thing causing it.

What I have found recently is that by going directly against all my natural inclinations and pushing on to see things through to success, I have found much more success and much bigger rewards.

Don’t make excuses, don’t call it burnout, don’t give up early, instead push harder, see the bigger picture, and climb the !@#* over that wall!

On the other side of that wall lies success and renewed motivation and interest, you just have to get there.

Older Posts »

Categories

Follow

Get every new post delivered to your Inbox.

Join 620 other followers