Showing posts with label Best Practices. Show all posts
Showing posts with label Best Practices. Show all posts

Sunday, December 13, 2015

Lazy vs. Careless

I am a lazy developer. I have no trouble admitting that because laziness is what drives me to automate tedious processes. It's what compels me to let my tools do as much work as possible. It's what pushes me to use unit testing for easy regressions.

I try to avoid being careless. Carelessness is what tempts us to cut corners when we know we should be doing something differently. And carelessness often comes back to haunt us.

I made a careless decision 6 years ago that is still causing me problems. Let's see where things went wrong, and hopefully others can learn from my mistake.

But before we do that, let's take a closer look at the differences between lazy programming and careless programming.

Lazy Programming
Laziness can be a virtue as a developer. Over the years, I've learned lots of shortcuts in Visual Studio (my primary development environment). This includes keyboard shortcuts as well as code snippets and code completion.

Visual Studio Helpers
In Visual Studio 2013 (and earlier), it wasn't always obvious where Visual Studio could offer us help. I always tell people to look for the little purple rectangle:


Here we have a class that declares that it implements an interface (IPersonRepository), but it doesn't yet have any of the required methods. The little purple rectangle under the "I" tells us that Visual Studio wants to help us out. (This does have a name, but I always forget what it's called -- and it's very difficult to search online for that.)

Whenever we see this, we can press "Ctrl" + "." to get a popup:


Then if we choose "Implement interface 'IPersonRepository'", it does all the hard work for us:


Now all 6 methods are stubbed out for us. This saves us the hassle of having to copy/paste method signatures whenever we implement an interface.

In Visual Studio 2015, the purple underline has been replaced with a more prominent light bulb:


When we click on the light bulb (or press "Ctrl" + "."), we get a similar popup that allows us to implement the interface. Plus, we get a bit of a preview to show what Visual Studio plans to do for us.


This is just one example of how Visual Studio fills in code for us that would otherwise be tedious to type in.

Keyboard Shortcuts
Another thing I love are keyboard shortcuts. Unfortunately (or fortunately), there are tons of them. I've picked a few that have been most useful in my coding:
  • Ctrl+K, Ctrl+C : Comment current line/selected block
  • Ctrl+K, Ctrl+U : Uncomment current line/selected block
  • Ctrl+K, Ctrl+D : Reformat document
  • Ctrl+K, Ctrl+S : "Surround with" - wraps a selected block in a code snippet
  • Ctrl+Shift+B : Build project
  • Ctrl+Space : Show code completion options
  • Ctrl+Shift+Space : When inside method parens, this pops up the list of parameters
These are the default key mappings when using Visual Studio with the C# settings. Resharper has its own set of keyboard shortcuts.

The point is that we can get a productivity boost when we learn how our tools can make development faster.

Snippets and Completion
I love code snippets. I use them to quickly create properties and "for" loops. I also love the "Surround with" keyboard shortcut in conjunction with the "try" snippet to wrap a block of code in a try/catch block (or the "tryf" snipped to wrap a block of code in a try/finally block).

And when hooking up event handlers, let's let Visual Studio create the methods for us. After typing an event and then "+=", we get some help:


When we press tab, we get a chance to rename the method:


And when we hit tab again, the event handler is stubbed out for us:


This example is from Visual Studio 2013. Visual Studio 2015 handles things a little bit differently; it stubs out the method first and then uses the new rename functionality to give us a chance to pick a new name.

Lazy is Good
So when we look at laziness in this sense, it's good. It gives us motivation to learn our tools so that we can write code quickly and easily. In addition, it's changed the way that I test code. I'm heavily into unit testing, and that's primarily because it's faster and easier for me -- especially when it comes to regression testing.

Probably the best thing about laziness is that it drives us to automate tedious tasks. Let's write a script rather than checking values manually. Let's put together a small application so we don't have to verify values every day. Let's automate deployment -- 1 click to build, test, deploy.

Careless Programming
What we really need to watch out for is carelessness in our programming. This is where we cut corners when we're putting things together. It could be global variable that we put in because it's faster to write than trying to figure out a more appropriate way to handle the functionality.

A global variable doesn't sound like it could cause a ton of problems, but it can. I worked on an application where I used a global variable to hold some shared data. The problems came about when reliance on the global variable meant that a single class kept getting bigger and bigger (because it needed that variable) rather than things getting split up into more appropriate chunks. That made things harder to support as time went on.

But that's not the carelessness that is still causing me problems. For that, we'll need to look at my sample applications.

A Simple Data Set
Way back at the end of 2009, I was working on some sample applications for my first outing as a speaker. Those first presentations were in January 2010, and I put together some simple data to use with them. Here's the output from a Silverlight example on how to use data templates and value converters:

from Intro to Data Templates and Value Converters in Silverlight

This shows a set of 7 records. (And in case you're curious, they are "television outer space commanders".) For this Silverlight application, I needed a web service, and ended up with a method that hard-coded the data:


This looks harmless enough, but I made a careless decision to cut a corner. And that was getting the dates into the data:


I decided to use a DateTime.Parse because I was copying the dates in from somewhere else, and it was a lot easier than splitting the components up with a proper call.

Carelessness
At the time I did this, I knew that I was not doing it the "right" way. But it was a way that would work fine. I justified this by telling myself that the data wasn't the point of the demo (the point was to show data templates and value converters). I told myself that no one who downloaded the code would care about this.

But I wasn't thinking ahead.

Carelessness Compounded by Laziness
Over the next 6 years, I would write many more demo applications. And because I'm a lazy developer, I used exactly the same data set for all of them. This was great for me because regardless of the presentation I was giving, the data would look familiar.

from I'll Get Back to You: Task, Await, and Asynchronous Methods

The look of my applications has changed, but the data has not.

The laziness is good. That means that I didn't need to come up with a new data set for each new demo. I could use what I already had. The bad part was that I was re-using careless code, and that would come back to bite me.

Going International
I think another reason I didn't worry about my careless code is because I never dreamed that my demos would leave the US. But those demos did start to go international -- primarily through Pluralsight and my YouTube channel. That's when things started breaking down.

My code:


Only works if someone is using the US date/time format: MM/dd/yyyy. And that's a problem because most of the world uses a format that makes much more sense: dd/MM/yyyy or yyyy/MM/dd.

The code above will throw an exception in either of these scenarios because it will be treating "17" as the month -- and there is no 17th month.

Some options to fix this include setting a specific culture or date format. But it was better to get rid of the ambiguity by using the constructor for DateTime:


This will work regardless of culture because the constructor parameters are clearly defined as year, month, day.

The updated GetPeople method looks like this:


Tendrils Everywhere
So the fix is pretty easy, but by this time, the bad code was *everywhere* -- in my samples for generics, delegates, lambda expressions, interfaces, design patterns, dependency injection, ugh. When I put my code samples together, I have to goal of someone being able to unzip the download and then build and run the code without having to do anything special.
This means that a copy of the careless code is included in pretty much every single downloadable project that I have.
I have been slowly updating the projects as I can. And I make sure that any new projects have the good code. But the fixes are tedious, and I'm still working on getting code updated.

Most of my code on GitHub is good, but there are still a lot of zip files on my website that are not. I'll get there eventually.

Watch Out for Carelessness
I cut a corner 6 years ago. I knew I was cutting a corner. I knew that there was a better way of doing things. But I made a careless decision that was short-sighted. I wish I could go back and fix it. It would save me a lot of work if I could. But that's how we learn.

I embrace my laziness as a developer. I let my tools do most of the work for me. I embrace unit testing. I look for ways to automate tedious work. These are all ultimately good results.

But I need to watch out for carelessness. I don't want to cut corners that will cause me pain in the future. If the solution feels "wrong", it probably is.

Embrace laziness, but watch out for carelessness.

Happy Coding!

Tuesday, August 18, 2015

Reconciling Clean Code and the Startup Mentality

Last week, I was at That Conference, and it was an awesome week (more on that later). But it was also a bit awkward. On Wednesday, the keynote by Max Lynch (co-founder of Ionic) was about startups and getting functionality to the users (or potential users) as quickly as possible. It was a great talk about some key features of successful projects.

A big theme to this was "It doesn't matter what your code looks like." The awkward part is that I was speaking about Clean Code and the importance of caring about the readability of code later that day.

Fortunately, a lot of people showed up for my presentation, and we had a really great time together. But I did get an interesting question afterward from someone who worked at a startup:
How do I reconcile "It doesn't matter what the code looks like" with the principles of craftsmanship?
The developer believed in craftsmanship and readable code, and he was a bit distressed that his boss was saying that they had to do things fast and dirty. As a bit of a surprise to myself, I actually had a good answer to give (at least I thought it was a good answer):
Treat the version 1 product like a prototype.
Let's explore this a bit more.

The Importance of Moving Quickly in Multiple Directions
I understand the startup mentality of "it doesn't matter what the code looks like" -- but with full understanding of the consequences of that approach.

The problem is that we only have an idea to start with, and we're not even sure if anyone will be interested in it yet. So we put together just enough code to get things working. And a lot of times, we don't even get that far; we just create a landing page to see if anyone is interested in the product before we even write a single line of code.

And once we start coding, we cannot invest too much time or effort into this. If it is a complete flop, we discard the code and move on to the next idea. We don't know what we need at this point. We're really just exploring. Ultimately, we're working toward a minimum viable product, which is just enough functionality to be useful to someone.

Even then, we don't know what feature will really resonate with our users, so we have to be ready for unexpected responses and to move quickly in another direction.

Just a Prototype
The only way we can use this approach is if we treat this code as prototype code -- even if we are releasing it to the users. This is our exploratory code -- where we figure out what excites our users and differentiates us from the rest of the pack.

There Will Be Problems
When we write code like this, there will be problems. We will have bugs that are hiding in the code. We will have issues scaling for more users. We will reach a point where it is difficult to add a new key feature.

And this is the point were "it doesn't matter what the code looks like" really starts to cause us pain. The best thing to do is discard what we have and write the code for our real product based on the prototype.

Clean Code Does Matter
It's really easy to fall into the trap of thinking that clean, readable code doesn't matter. After all, if we can be successful without it, who cares?

This works short term, but things fall over in the long term.

Once we have our viable product, and we start coding "for real", we need to pay attention to craftsmanship principles. We have to make sure that we don't introduce bugs in our code. And we do this through automated testing (the proof that our code does what we think it does) and through readable code (if the code is easily readable, then the bugs have nowhere to hide).

In addition, since we now know what features make our application successful, we can leave spots for abstractions and extensibility points so we can easily add new features.

And this is where we start to think about the long-term viability of our product. If we treat our version 1 as the real version rather than the prototype, we're just setting ourselves up for a lot of pain. But if we take the learnings from the prototype to then create the actual product, we can reap the benefits of our quick, maneuverable process and use them to create a sustainable product.

Final Words
In the Wednesday keynote with Max Lynch, the focus was really on starting many companies (one after the other, and sometimes several at the same time) based on ideas that we don't know will work. We need to figure out what resonates with our users quickly so that we can focus our efforts.

So, my advice to people who are coding "fast and dirty" and don't feel right about the process: think about this as a prototype. It is an exploration of what might be useful. And just because we release that product to our users does not make it any less of a prototype. Expect to discard this code once we have gotten what we need to know from it.

It Does Matter What Code Looks Like
Ultimately, it *does* matter what the code looks like. Having readable code is what makes it easier for us as developers to make changes to meet our users needs. If we can't quickly meet our users needs, then we've failed. If we don't go back to replace that prototype code, then we'll end up falling over at some point.

If we create a mess so that we can get some learnings out of it, that's fine. But we can't leave things that way. For long-term viability, we need to think about the quality of our code which ultimately impacts the quality of the product.

Happy Coding!

Friday, August 7, 2015

When Does DRY Become ARID?

The DRY Principle is a great thing to keep in mind:
The DRY Principle
Don't Repeat Yourself
But like all principles, we need balance. Otherwise we might find we've gone from DRY to ARID:
ARID Code
All Readability Is Dead
To me, readability is king. Sometimes I will pick a not-completely-optimized way of writing code so that it is more understandable. (Obviously, if I really need speed optimized code -- such as tight loops or other processes -- then that will get prioritized.) Let's see why we need to watch out for over-doing DRY and straying into ARID code.

Challenged By a Friend
I'm a big fan of the DRY principle, and that's because it's caused me a lot of grief in code I've dealt with. And this is one of the reasons I spend time sharing my stories with other developers (see "Clean Code" and "Abstract Art").

One of my friends -- a developer I worked with for many years -- recently watched my Clean Code presentation, and he made a comment about the refactoring part.

"I don't think you went far enough... You're violating DRY."

I'm always up for some exploration, so let's take a look at the code.

The Original Refactoring
If you want to watch the refactoring in video, here's a link to the right spot in the recorded presentation: YouTube - Clean Code 46:03.

In the sample, we start with a simple (but a bit difficult to approach) method:


Then we extract a couple of methods to hide some details and add some good method names to let us know what's going on:


This makes our "Initialize" method much easier to understand. If we need to know how we "get the service from the container", we can drill into that method. Otherwise, we can simply move on.

A Bit Drier
My friend pointed out that there is duplicated code in the two extracted methods. So this is where we should concentrate our efforts.


When we look at these a bit closer, we see a lot of similarity. We have conditions based on "IsRegistered" to see if an item is in the dependency injection container. Note that these are not *exactly* the same. The first method has a "CurrentOrder" string as a parameter; the second method has no parameter.

If the object is not in the container, then we throw a MissingFieldException (same exception with a slightly different message).

Then we resolve the actual item from the container. Again, one of the methods takes a string parameter, and the other does not.

To help us get rid of some of this duplication, we can combine them into a single method with the help of a generic type parameter. Here's a first stab at this:


Now we have a single method that returns a generic type ("T"). But we really haven't eliminated the duplication. We simply have 2 conditional blocks based on whether we have that optional string parameter. If we have a string parameter (like "CurrentOrder"), then it is passed to the "IsRegistered" and "Resolve" methods. And it is also used in the message of our exception.

If there is no parameter, then we use the name of the type itself in the exception message.

With a little more understanding of how the underlying methods work, we can eliminate some duplication:


This takes advantage of the fact that if we call "IsRegistered" with a "null" parameter, it works the same as if we had no parameter. The same is true of "Resolve". It was very easy for me to verify this functionality because I have unit tests in place that test both the success state and the error state for this.

We still need to use the right string for our exception message. So for that, we create a variable ("missingObject") that we can populate with the parameter or the type name as applicable.

Using the Drier Method
Now that we have our drier method, we need to actually use it in our code. Let's update our "Initialize" method:


All of our unit tests still pass, so we know that this code is functionally the same as we had before, but have we made the readability better or worse?

This exposes some details that we don't have in the other version. For example, we see that the model is of type "CatalogOrder" (which we could tell from inspecting the "_model" variable as well). But it also tells us that the model is referred to as the "CurrentOrder". Is this important? Or does it just get in the way?

Let's put the methods side by side:

Original

A Bit Drier

Personally, I prefer the original version in this case. We don't need the details here; that's the reason we extracted the methods to start with. In addition, I know the environment that this code came from. It's based on real code and a real situation. Based on my understanding, the original refactoring is a better fit for the developers who would be maintaining the code.

As with all of our best practices, this is a matter of balance. For a bit more, see Beware of "Never" and "Always".

Truly ARID
I would not consider either version above to be unreadable, but readability is always at the top of my mind. The primary reason for this is that in addition to seeing violations of the DRY principle, I've seen people take this much too far. The result was something completely unreadable.

Here's an example. I was working on a WPF project, and we had several value converters to get our UI working the way that we needed for our users. (Value converters are one of the great things about data binding in WPF -- it let's us do cool things like bind a color in our UI to a date property in our data.)

Someone got tired of the proliferation of value converters, so they decided to create "one converter to rule them all". The idea was to have one value converter that had all sorts of options that could be provided as parameters. We'll look at just a little bit of this code (unfortunately, there was much, much more).


This is the main "Convert" method. And we can see that there are a couple of properties used in this method: StringFormat and FalseText. And there are a couple of methods called as well: IsStringFormatConversion and Match.

Let's take a look at the Match method:


Yikes. This contains more properties: ConditionalText, IsNullCompare, IsStringCompare, and IncludeEmpty. The mixture of "&&" and "||" also makes the logic extremely difficult to follow.

But worse that this is that the converter was confusing to use. Here are a couple basic examples:


These only use two of the possible parameters: ConditionalText and IsStringCompare. But there were examples that used many more.

The big question is "What do these converters actually do?" And that's the problem. Just by looking at the usage, I have no idea what's going on. I would need to dig deeper.

This code has definitely crossed the line into ARID.

Balance in Everything
As developers, we have to constantly find the right balance. This could be weighing the pros and cons of a particular tool. It could be finding the balance between readability and testability. Sometimes it is finding the sweet spot between speed and memory footprint.

Sometimes these choices are clear cut. But often, they are subjective -- especially when we're talking about readability. Because we always have to ask, "Readable by whom?" Readable by a senior developer? Readable by a new developer? Readable by our users?

In the example we looked at today, I could see arguments being made either way. I have a bit more insight since this is based on real code, and I know the developers who needed to understand the code. Because of this, I erred on the side of simplicity. These projects had a lot of new concepts to this team (DI, XAML, delegates, and a few more), so I would simplify wherever possible.

The decisions aren't always easy. But that's part of the fun of this type of work.

Happy Coding!

Thursday, May 28, 2015

Beware of "Never" and "Always"

If I hear someone say "Always do this" or "Never do that", I generally run the other way (but there are exceptions, of course ☺).

I am a big fan of best practices. The reason for this is that I spent a lot of time in my career doing things in a "could be a lot better" way and finding out the hard way that my approach had some issues that I didn't think about.

Eventually, I came to my senses and started looking at recommendations from people who have been programming way longer than I have. They've already made those mistakes and come up with better solutions. These get described with the general term "best practices".

A Good Place to Start
I treat advice that I get from other developers (and the developer gurus) as a good place to start. This means that I will generally follow the advice unless I come up with a really good reason not to.

Here's an example that I like to show in my presentations:


"Hikers and bikers move to the side of the road when a vehicle approaches." This sounds like a great piece of advice. We don't want to get run over. But we also need to consider our surroundings.

But Don't Follow Blindly
Sometimes when we look at our surroundings, we find out that following the best practice may not be a good idea after all:


So even though following this advice is generally a good idea, it would actually cause us more problems in this particular environment. I'd prefer to take my chances with the cars than the alligators.

BTW, I found out that this picture is from Shark Valley -- part of the Everglades National Park in Florida. (And I'd love a better quality image of this if anyone has one.)

User Input is Evil
Here's something we all need to be aware of:
Fact: All input is evil.
I don't think anyone disagrees with this. Anyone who has an open form on a website knows this first hand. And if you don't want to believe me, just ask little Bobby Tables (xkcd: Exploits of a Mom):


And this leads us to a good piece of advice:
Best Practice: Verify input before using it.
It's really hard to argue with this. When we're talking about input, we're not just referring to things that users type in, we're also referring to input that we get from other developers when we create APIs or library methods.

Implementing a Best Practice...
I've spent several articles exploring guard clauses on a particular method. This is the method that we've been looking at when exploring TDD and Conway's Game of Life. Here's the original method:


We don't validate the parameters. And we saw why this was a problem in the last article: Testing for Exceptions with NUnit. It's possible to pass in an invalid "currentState" parameter and get a seemingly-valid value out of the method.

At the same time, the "liveNeighbors" parameter is really only valid for values between 0 and 8 -- the number of neighbors that a square-shaped item can have in a grid.

So, we spent some time adding guard clauses at the top of the method:


And we also saw a couple different ways to write unit tests to make sure these guard clauses work as expected: both using NUnit and letting Smart Unit Tests check them.

But after going through the exercise of adding the guard clauses and creating tests for them, I promptly removed them.

...And Then Ignoring It
Yes, I just admitted to actively ignoring a best practice of validating input. But there is a specific reason for that. In the application where this method is used, speed is important. This method gets called thousands of times for each generation when we run our Conway's Game of Life application. And we could end up running through hundreds of generations during that process. That means this method gets called hundreds of thousands of times.

In fact, in an effort to parallelize the method calls, I ran through several experiments to see what is most efficient: Optimizing Conway's Game of Life.

Here's the method (and level of parallelism) that worked best for this scenario:


The "GetNewState" method (the one we've been looking at) is called in a nested "for" loop. And because this method is called so often, we need it to run quickly.

Guard Clauses Slow Things Down
To keep this method running quickly, we want to trim as much code as possible. The guard clauses may not seem like they add a lot of work (just 2 "if" conditions), we see a big difference if we actually check some metrics.

Here's the performance of our method *without* the guard clauses (the same as we saw in the optimization article):


The 10,000 iterations is the number of times the entire grid is updated. Since we have a 25x70 grid, each iteration runs this method 1,750 times. And we can see our result is about 1-1/2 seconds.

Here's the performance with our guard clauses added:


This is 4 times slower -- definitely not acceptable when speed is an important feature.

Have a Good Reason
I recommend best practices to developers as much as possible. What I've found is that they are good advice to follow the vast majority of times (probably in the 95% range). It's really those exceptional cases (like when alligators are resting on the side of the road) that we decide to ignore the practice.

But we're not really ignoring the best practice at that point. "Ignore" implies that we don't care about it. We do care about it, but we've determined that it's not appropriate for this particular scenario. And we also understand the consequences of our decision.

In our example, I understand the consequence of not having the guard clauses: it is possible for someone to call this method with invalid parameters, and the method will return an invalid response. But *in this scenario*, this method is not published to the outside world. Instead, it is called by another class in the application (which I have full control over). And the way that class is set up, I know that the method will not be called with invalid parameters.

So I understand the risk, and I'm willing to take that on because performance is a very high priority here.

Best Practices are Awesome
I really like learning about best practices. I want to understand the problems that other developers have run into. I want to understand the solutions that they have come up with. And I want to steal as much of that experience as possible so that I can skip over the painful part of the process.

And that's why I like to show best practices to other folks, whether it has to do with abstraction, dependency injection, design patterns, or general coding style. They can save us all sorts of time. But we shouldn't follow them blindly. We should take time to understand the benefits and consequences. This way, we know that we're using the right tool for the job.

So rather than thinking of these as "always" or "never" items, we need to think of them as a great place to start. Most of the time, they are the right answer. But we have the option of choosing another path if that's what makes most sense.

Happy Coding!

Sunday, March 29, 2015

Looking for Answers: Origin of the Homicidal Developer

In my presentation "Clean Code: Homicidal Maniacs Read Code, Too!" (video & downloads), the homicidal maniac developer plays a key role (and leads to the best joke in the presentation):


I have this rule marked as "Unknown" because I'm not sure where it originated. I first heard the concept on a podcast a while back (sorry, I don't remember which one). I've been hoping to track down the originator of this because I would love to give him/her credit for it.

The Joy of the Internet
Shortly after I published my video last week, I saw my name come up in a Twitter thread that started here (just click on the photo to see the full thread):

Cesar took motivation from my Clean Code talk to include in his presentation on Agile Testing. This kicked off a discussion among Cesar and some other folks in Brazil about the origin of this concept (and thanks to Google Translate, I was able to follow the conversation -- the internet is pretty awesome).

Origins
That brings up the question of where this phrase originated. There's even a question that was posted on StackOverflow regarding this: Who wrote this programming saying?

Unfortunately, this was closed as being "not constructive". But through various sources (including my new friends in Brazil), I've found a couple of usages.

Usage: Damian Conway
Perl Best Practices, 2005
Damian Conway uses the following version in his book Perl Best Practices (on Page 5):
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
He does not give an attribution here (unfortunately). You can find this quote with a Google Books search.

Usage: John F. Woods
comp.lang.c++, 1991
John F. Woods uses the following version in a post in 1991:
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.  Code for readability.
From Google Groups

Variations
Another variation that I've seen (without attribution) is this one:
Always write code as though it will be maintained by a homicidal, axe-wielding maniac who knows where you live.
And, of course, there is the mutation that I use in my presentation:
Imagine the developer who comes after you is a homicidal maniac who knows where you live.
So there's lots of stuff out there that points to this concept.

Update 08/26/2015
Someone forwarded me this tweet. I haven't seen this one before:

A little bit of digging says this is from an unattributed sig that Martin Golding used in 1994. So similar to John Woods' sig above but a few years later.

Update 10/27/2015
Another attribution to Martin Golding. Can anyone confirm this? Martin?



OK Internet, Now It's Your Turn
I would love to give proper attribution to the concept of the axe-wielding, homicidal, violent, psychopath, maniac developer.

If you know the origins of this concept (or you have some references that point in the right direction), leave them in the comments. And if you'd like to claim credit yourself, that's fine with me. Just make sure that you provide some references that we can check out.

In the meantime, write code to keep the homicidal maniac happy.

Happy Coding!

Wednesday, March 25, 2015

Clean Code Presentation Recorded Live at Nebraska.Code()

I've been traveling quite a bit recently. Last week, I had the opportunity to go to Nebraska.Code() -- previously the Nebraska Code Camp now expanded into a larger event. A big thanks to Adam Barney and Ken Versaw for organizing a great event.

Clean Code Video
I made a recording of my presentation at the event: "Clean Code: Homicidal Maniacs Read Code, Too!" Watch the video on YouTube (or here): Clean Code



If you watch the presentation, you'll see that I have way too much fun doing this. I want to thank everyone who came because you are the people who give me this opportunity. I hope that you get some good information and are inspired to think about things is a bit of a different way.

Publishing The Watcher
As part of the presentation, I show a little helper application that encourages me to write code that is readable and maintainable. This application is called The Watcher, and every five minutes, it gives a pop-up as a reminder:


This is the homicidal maniac who takes over support for the code I write (and he knows where I live). I want to keep him happy. (BTW, there's a thread on Twitter talking about who originated the idea of the homicidal maniac developer. I'm trying to hunt down the origin so that I can give credit where it is due.)

Lots of folks have asked if they could have a copy of this application. I've been a bit embarrassed to publish it, though: the code is in pretty bad shape. I took an existing application (that showed a marquee on the screen) and modified it for the new functionality. In doing that, I didn't clean it up as I went (not a good example for a Clean Code presentation).

Well, I'm publishing it anyway. You can treat this as an exercise -- download the code and clean it up yourself to practice your new skills. And if you want to contribute back, feel free to make a pull request on the GitHub repo.

The code is available on GitHub, so check it out here: https://github.com/jeremybytes/the-watcher. (If you aren't a "git" person, just click the "Download ZIP" button on the right side of the screen.)

Meeting New People
I had a really awesome time at Nebraska.Code(). This is my first time speaking in the Midwest, so I got to meet a lot of new people, and spend some time with folks who I've only met in passing. I formed a lot of great relationships, and I'm looking forward to building on them in the future.

I can't emphasize enough how valuable talking to other developers has been for me. (And yes, I did meet new people in the lunch line at the event.) Just at this one event, I talked to people from Nebraska, Michigan, Missouri, Illinois, Kentucky, Iowa, Connecticut, Arizona, British Columbia, and several other places.

If you need some encouragement to talk to strangers at events, check out my article: Becoming a Social Developer: A Guide for Introverts.

I'll look forward to going to this event again next year, and I also look forward to speaking at a bunch of new events. It's a great opportunity to travel to new places and meet lots of new people.

Happy Coding!

Wednesday, February 11, 2015

YAGNI - Reaping the Benefits

People take different approaches to software, and we find that some of these work better for us than others. I'm a big fan of the YAGNI principle ("You Ain't Gonna Need It"), but historically it hasn't been much of a problem for me. But I came across an example of how it helped me recently -- even though I wasn't conscious of it at the time.

YAGNI: You Ain't Gonna Need It
The basic idea behind YAGNI is that we shouldn't code based on speculation of what we might need in the future. Business processes change, user needs change, and our software needs to change with it. If we build what we think we *might* need, odds are that we'll be wrong and that part of the software will remain unused. And that leaves us with code that is more difficult to navigate and debug without giving any benefit.

Historically, this has not been a big problem for me. My nature is as an under-abstractor. This means that I tend to lean away from abstraction. I add abstractions as I need them (and generally not before) because I've been burned by badly implemented abstractions that were put into an application "just in case".

So when we think about YAGNI, we think about the requirements that we have *now*. This doesn't mean that we don't think about the future; it just means that we don't build it yet. We should be thinking about the possibilities of our applications, and we should make sure that we don't code ourselves into a corner when we're writing them. But rather than adding the full abstraction (such as a plug-in architecture), we think about where we would put it if we needed it. Then we make sure that we leave a spot where we can add it later.

Making Things Easier
Old Application
One thing that I've been writing about recently is an application rewrite of my home automation software. Articles are collected here: Rewriting a Legacy Application. This is software that I've wanted to rewrite for a really long time, but I was too wrapped up in the complexities of the old application. There were a lot of features that had grown over the years, and it seemed like a daunting task to rewrite the whole thing.

So, I took a more practical approach: distilling things down to just the features that I actually needed -- the features that I used on a daily basis. This helped me create the requirements for a minimum viable product (MVP).

This process let me distill the entire application down to 3 features that I actually used. The other things (like UI, network access, and schedule editor) were all nice to have, but the more I thought about it, the more I figured that I didn't need them. For example, there's not much need for a UI. This application is always running on a machine in my house that's plugged into my TV, but I rarely look at the screen on that machine (it primarily just plays music and runs the lights while my TV does other things).

Rather than a huge, daunting task, this became fairly simple. In fact, I implemented the entire replacement in just a few days. Since then I've been refining it and adding new features, but that base replacement functionality went very quickly.

Leaving Room for Changing Priorities
So, I really took the YAGNI approach to most of the features in the old application. And that has turned out to be true. I've been running the software in production for a little over a month, and I haven't missed the features that I left out.

More importantly, I've been free to go in a different direction. The biggest example of that was when I added the ability to create schedule items relative to the current sunset or sunrise times. That original ugly code is in a much better state now (and it keeps getting better).

This code has been in production for a few weeks now. I currently have 2 items that are scheduled relative to sunset. A light in the living room goes on 30 minutes prior to sunset (when it's just starting to get dark), and a light in the bedroom goes on 1 hour after sunset. These are both ambient lights, and I've enjoyed watching them come on at different times as the days get longer. When I put the code in, the first light came on around 4:45 p.m., and now it comes on a little after 5:00 p.m.

But since the application is fairly "raw" as far as the architecture is concerned, I haven't committed to going in a particular direction. This has made it easy to implement this new feature (which had nothing to do with the old application). And I look forward to adding more features as I need them.

Wrap Up
So rather than getting bogged down in things I *might* need or I think I *should* need, I'm able to focus on the features that I *actually* need.

I do have some examples of where YAGNI has helped me in the past, but it's nice to see that the principle still helps me in my current coding activities -- even when I'm not consciously thinking about it.

For more information on YAGNI and other principles to help us with abstraction, check out the materials I have for Abstract Art: Getting Things "Just Right", including a Pluralsight course, slides, and a variety of blog articles.

Happy Coding!

Wednesday, January 28, 2015

Reviewing Options: Building on Experience of Other Developers

Yesterday, I took a look at a couple of options to fix a problem with a fluent API in an application: Fixing Problems with a (Specific) Fluent API. I got a couple of really good comments, so I'm going to explore things a little further.

Note: This probably won't make much sense unless you look at the previous article. To get an overview of the entire project, check here: Rewriting a Legacy Application.

Opinions of Other Developers
I elicited comments from other developers. As usual, this is a great chance to get other points of view and also learn about some tools or techniques that maybe I don't know about.

First, a comment from Mackenzie Zastrow:


This is actually the direction that I'm leaning. It's hard to argue about the utility (or lack of utility) in the custom types. I'm not totally attached the the fluent API; I put it in as more of an experiment. So, I wouldn't be sad to see it go.

But then I got a good comment from Cliff Chapman:


New to Me
I hadn't heard about Semantic Types. There is an article on CodePlex by Matt Perdeck that describes the concepts: Introducing Semantic Types in .NET. And he's also created a NuGet package with the base types so that you don't need to code it up yourself.

This is really interesting to me. I think it's probably too much for this particular application, but it will be good to explore the concepts a little more.

Let's take a quick run through the code, describe the general idea, and look at a simple implementation.

Original Custom Types
The custom types that we started with didn't have much functionality:


These types just hold a single string value. The advantage that we get from this is that we now have custom types that we can use for our extension methods. So instead of extending all strings, we can extend just these types.

But we also have a problem. There's nothing to prevent us from putting whatever string value we want in these objects. So even though we get a bit of safety in our extension methods, we have a lot of danger in the objects themselves.

If we create these objects with invalid strings, then our code would blow up further down the line.

Adding Validation
The primary idea behind Semantic Types is that we can have a class that contains a "string" value, but we can constrain that string value to make sure it conforms to a particular format or value.

For example, we can have an EmailAddress object that will only accept values that pass a regex check for email address formatting. In addition, the Semantic Types classes deal with the issues of equality, comparison, and even checking valid values without creating a custom object.

It's an interesting article; I'd recommend a read. Here's the link again: Introducing Semantic Types in .NET.

For my project, I decided I didn't want to go all the way with using the Semantic Types base classes (but I'll definitely keep this in mind for future projects). Instead, I just added some simple validation to the existing types.

The code for this is in the FluentAPI-Updated branch on GitHub. The custom types are in the "SunriseSunsetOrg.cs" file in the "HouseControl.Sunset" project. Direct link to the file: SunriseSunsetOrg.cs.

UTCTimeString
Let's start with the UTCTimeString object. Here's the updated code:


We've just added some parameter checks to the constructor. If the value is "null", then we throw an ArgumentNullException. Then we try to parse the string as a DateTime object. If the parse fails, we throw an ArgumentException. If it passes that parse, then we assign the value to our property.

ResponseContentString
The ResponseContentString object has been updated in a similar way:


This has the same "null" check, and then it tries to deserialize the string as a JSON object. If this fails, we throw an ArgumentException. If it does not fail, then we assign the value to our property.

Note: This will work with *any* JSON object; it's not looking for specific fields in the object (which we might want to do). But we get the general idea of how we can add validation here.

Testing Validation
The nice thing about these objects is that we can test the validation very easily. For this, there is a new "HouseControl.Sunset.Test" project. The "SunriseSunsetOrg.Test.cs" file contains our tests (direct link: SunriseSunsetOrg.Test.cs).

Here are the tests for the UTCTimeString class;


These are pretty straight-forward. The first test is the "success" state. We pass in a valid time string and check that it is reflected in the "Value" property of the object. (As a reminder, the "Value" property is a string, not a parsed DateTime.)

The second test checks a "null" parameter. And as we can see from the "ExpectedException" attribute, we expect that this will throw an ArgumentNullException.

And the third test checks an invalid string value. This expects to get an ArgumentException. When we set up "ExpectedException" like this, the test will *only* pass if that particular exception is thrown. If there is no exception (or a different exception is thrown), then the test will fail.

With these in place, we can see that all 3 of these pass:


Now, let's take a look at the tests for the ResponseContentString:


These are similar to the previous tests. They test a valid value, a "null" value, and an invalid value.

And we get similar results when we run the tests:


So we can see that our code is working as expected at this point.

[Update 1/29/2015: I just realized that the test names don't reflect what we're actually testing. This is left over from a previous iteration of the code which had an "IsValid" property that was checked by the tests (if you're curious, it's in this commit). I changed the code to throw an exception instead and updated the unit tests (but I forgot to update the names). Here are the better test names. These are in the FluentAPI-Updated branch:


The tests with valid parameters are now titled with "HasValue", and the tests with invalid parameters are now titled with "ThrowsException". This better reflects what's going on in the tests.]

Semantic Types
So this is very simple validation for the custom types. I didn't go with Semantic Types for this example. I'll be experimenting with it in other projects by using the base types provided in the NuGet package.

What makes me most interested in it is that it seems similar to what F# has built in with Units of Measure. This allows you to make a type distinction between an integer that holds a temperature and an integer that holds a distance in miles.

I'm very interested in functional programming and cool features offered by various functional languages (and I really should be spending more time with it). Several of the concepts jump out at me, and this is one of them.

Semantic Types isn't exactly the same thing as Units of Measure, but it does give us the custom types that are based on more primitive types but are still distinct from one another.

(And I know that the similarities between these two concepts breaks down pretty quickly, but it's something that came to mind as I was looking at this.)

Which Option?
After all of this, I'm still leaning toward Option #2 (which is to not use custom types and remove the fluent API). For this project, I think it is the right choice since we still don't get much utility from the custom types. It will be interesting to explore Semantic Types in other scenarios.

I still haven't merged back to the "master" branch yet. I'll probably be doing that in the next few days. If you have an opinion one way or the other, be sure to leave a comment.

I value opinions of other developers. We all have different experiences in different environments. It's really great when we can leverage that experience without having to fumble through things on our own.

Happy Coding!

Monday, January 26, 2015

Fixing Problems with a (Specific) Fluent API

I'm still working on my home automation project. Recently, I've been dealing with the code that gets data for sunrise and sunset times -- and it's been getting a lot better. But in my last update to the code, I put in some extension methods so that we code using a fluent API.

I've since thought about this, and based on the problems with the current implementation, it needs to be updated. There are 2 directions we can take with this, so I created some branches and coded up both of them. After further consideration, I'll make a decision on which one will be merged back into the master branch.

The code (and articles) for this project are collected here: Rewriting a Legacy Application. The code is on GitHub: jeremybytes/house-control. And we'll be looking at several branches here.

The Problem Code
The problem code is in the FluentAPI-Original branch (we're specifically looking at the "SunriseSunsetOrg.cs" file in the "HouseControl.Sunset" project). The main idea behind this code is that we have a set of extension methods on the "string" class:


If you're not familiar with extension methods, check out Quick Byte: Extension Methods.

We're paying attention to the first parameter here (the one with the "this" keyword). Because the "GetSunsetString" takes a string and returns a string, and the "GetLocalTime" takes a string and returns a DateTime, we can write code like this (where "cacheData" is a string):


I like this syntax (and I've always liked fluent APIs such as LINQ). And this code works fine in isolation. But if we step back and take a broader look at what we've done with this code, it starts to look a little less brilliant.

Specifically, the extension methods extend the "string" class. This means that the methods really should work with *any* string that we give them. But the reality is that they only work with very specific strings: a JSON object and a date/time string.

But because these are extension methods on "string", there's nothing to stop us from using them on other string objects:


This is really bad. If we have a string that contains "Hello", we can call "GetLocalTime" on that. And the code completion in Visual Studio is almost encouraging us to do that. But it would just result in an error.

Falling into the Pit of Success
I really don't like code that lets developers get themselves into trouble so easily. When I create a library, I really want the developers to fall into the pit of success. This means that I need to remove any dangers that I can. This code is too easy to use incorrectly.

And there are really 2 directions that we can go with this. First, we can create more specific types that we use for our extension methods. Instead of using "string", we would use a custom type that contains the JSON data or the date/time data as appropriate.

The other option is to remove the extension methods (and along with it the fluent API). We'll explore both of these options.

Option #1: An Updated Fluent API
If I decide that I really like the fluent API, then we can use the code that makes the API a bit safer. This code is in the FluentAPI-Updated branch.

The extension methods have been updated to work with custom types (instead of string):


We have 2 new types -- "ResponseContentString" and "UTCTimeString" -- which are designed to hold the JSON result of our service and a string that represents a UTC time, respectively.

Notice that "GetSunriseString" and "GetSunsetString" both take a "ResponseContentString" as a parameter and return a "UTCTimeString". Then we can use that "UTCTimeString" with the "GetLocalTime" method to return the local date/time.

The custom classes themselves are pretty simple. In fact, I just added them to the top of the same "SunriseSunsetOrg.cs" file.


These just have a single property to hold a string value. But because they are custom types, we can target our methods a bit better.

When we have these in place, we can still use the same fluent syntax:


But in order to do this, we've had to change a few of our variables. Notice that the "cacheData" field is now a "ResponseContentString".

And if we look at the methods on this type, we see that they are a bit more focused:


So we see that we have "GetSunriseString" and "GetSunsetString" available to us (but not "GetLocalTime").

And if we tried to make a call on a "Hello" string (like we did above), we would not see any of our extension methods since they now operate on these custom types.

Note: As another alternative, we could move the extension methods so that they are part of the custom classes themselves. But before doing that, we need to think about whether it confuses the responsibility of each class. I could argue either way in this case. We'll stick with the separate extension methods here.

Advantages & Disadvantages
The biggest advantage to this approach is that we get to keep the fluent API. The biggest disadvantage is that we now have more custom types floating around our code.

So, we're making our code a bit more complex in order to make using the API a bit simpler. Like everything else we deal with when making decisions about our code, everything is a bit of give and take.

Now let's take a look at another option.

Option #2: Remove the Fluent API
Our other option is to get rid of the fluent API by removing the extension methods. This code is in the FluentAPI-Removed branch.

We're not removing the functionality that was in the extension methods, we're just turning them into normal methods:


These methods are now in the "SunriseSunsetOrg" class instead of the "SunriseSunsetOrgHelpers" class. And they are now just static methods. Notice that the "this" keywords have been removed from the parameters.

These have the same functionality, but we end up calling them a bit differently. Here's our calling method:


Notice that our fluent syntax is gone. Now we're calling methods with parameters and passing results as parameters to the next method. We could tighten up this code a little bit (by removing some of the intermediate variables), but it gets more difficult to read and debug.

For a look at why we may or may not want the intermediate variables, check out I Can Write That Method with One Line of Code.

Advantages  & Disadvantages
The biggest advantage to this approach is that we keep things simple. We don't add any new custom types (notice that the "cacheData" field is just a "string" like it was before).

The biggest disadvantage is that we lose the fluent syntax. Again, I like fluent APIs (where they make sense). And I'm okay with losing access to the fluent nature of the API if it's not appropriate here.

Which Would You Choose (and Why)?
I am going to merge one of these options back into the master branch of this project. So the question is, which one should I choose? And is there a good reason to choose one over the other?

The branches are all on GitHub:


I'm planning on leaving these branches in the repository even after I've merged the branch that I want. That way, the code will stay there to go along with this article.

So, check out the FluentAPI-Original branch to see the code in its problem state (with the extension methods on "string").

The FluentAPI-Updated branch has the code for Option #1 where we maintain the fluent API by adding custom types.

The FluentAPI-Removed branch has the code for Option #2 where we remove the extension methods and do not add any custom types.

[Update 01/28/2015: Based on the comments on this article, I've explored some options a little further: Reviewing Options: Building on the Experience of Other Developers.]

Wrap Up
I'll be considering the pros and cons of these options over the next few days. Neither one of these affect the operation of the application (in fact, the "problem" code is running just fine in production). But I'm using this application to experiment with different techniques. This lets me practice my skills so that I can more readily use them in other environments.

Coding practice is important, and it's something that many developers never do. When we go through exercises like this one, we think through techniques and approaches, and we find out what works well for us and what doesn't. That way, when we get into "crunch time" in a real application, we know exactly what approach will work best for us.

Happy Coding!