Showing posts with label Clean Code. Show all posts
Showing posts with label Clean Code. Show all posts

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!

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, September 24, 2014

October 2014 Speaking Engagements

I'll be traveling a little bit in October. If you're in Silicon Valley or the Phoenix area, be sure to stop by. These events should be a lot of fun.

Thursday, October 9, 2014
South Bay .NET User Group
Mountain View, CA
Meetup Event
o Abstract Art: Getting Things "Just Right"

Saturday & Sunday, October 11 & 12, 2014
Silicon Valley Code Camp
Los Altos Hills, CA
My Sessions
o Clean Code: Homicidal Maniacs Read Code, Too!
o Learn to Love Lambdas
o Community, Career, and You: A Microsoft MVP Panel

This will be my third time going to the Silicon Valley Code Camp. It is an amazing experience. Tons of sessions on all different topics to choose from (there are about 25 sessions to choose from in each time slot). I've met a lot of great people over the last two years, and I'm looking forward to being there again this year.

Saturday, October 18, 2014
Desert Code Camp
Chandler, AZ
Code Camp Site
o Abstract Art: Getting Things "Just Right"
o Dependency Injection: A Practical Introduction
o Learn to Love Lambdas

Desert Code Camp is one of my favorite events (I know, I'm not supposed to have favorites). This will be my 9th time at this event. The Phoenix area has a great developer community, and I always have a lot of fun when I go out there. I'm looking forward to talking to some old friends and also meet a lot of new people.

Abstract Art: Getting Things "Just Right" (the movie)
You may be wondering about my latest Pluralsight course. It's currently going through the final production processes and should be released the week of October 6th.

[Update 10/06/2014: It's published! http://www.pluralsight.com/courses/abstract-art-getting-things-just-right]

In the course, we look at how abstraction is awesome and how abstraction is awful. If we have too much abstraction, then our applications are complex and hard to maintain. If we have too little abstraction, then our applications are rigid and hard to maintain. Our goal is to figure out how to get just the right amount of abstraction in our applications.

We'll do this by looking at ourselves and how our own nature as developers can get in the way of achieving this goal. And the course is chock full of practical advice -- real practices that we can use to help us get things "just right".

And of course, you can also see the live version (which is a bit condensed) at upcoming events. Hope to see you in person soon!

Happy Coding!

Monday, July 14, 2014

July 2014 Speaking Engagements

I've had a late addition to my speaking calendar (yes, it's for tomorrow).

Tuesday, July 15, 2014
San Diego .NET User Group - UI Developer SIG
MeetUp Link
Topic: Clean Code: Homicidal Maniacs Read Code, Too!

Clean Code is one of my favorite things to talk about with other developers. We all have different definitions for what we consider "clean". And what's "clean" varies depending on the environment. In the presentation, we'll look at several practical tips to make our code easier to read, maintain, extend, and test. And we'll spend quite a bit of time in code doing some practical refactoring.

Hope to see you there.

Happy Coding!

Tuesday, April 22, 2014

Education Day, San Francisco - May 3, 2014

My friend Theo Jungeblut and I are putting together a full day of awesome for Saturday, May 3, 2014 in San Francisco, CA.

Clean Code: Principles, Patterns, and Practices for Better Code
You already code. Now it's time to take the next steps to becoming a better developer. Those steps are not difficult; we just need to put them into practice. The end result is code that is easier to maintain, easier to test, and easier to extend. Through lots of examples and hands-on labs, we'll learn about software design principles and the patterns that help us implement them. We'll see how Dependency Injection helps us create loosely-coupled code. And we'll spend a bit of time looking at Software Craftsmanship: ensuring that our code is readable by humans while still easy to maintain and test.
This is a full day event. Cost is only $39, and that includes lunch. For full details and to register for the event, visit Eventbrite: Clean Code: Principles, Patterns, and Practices for Better Code.

A big thanks to Bay.NET and Mathias Brandewinder for setting this up. I'm looking forward to a great event. Hope to see you there.

Happy Coding!

Wednesday, December 18, 2013

I Can Write That Method with 1 Line of Code

I've worked with developers who prided themselves with terseness -- writing a function with the absolutely fewest lines of code possible.

Are fewer lines actually better?
I'll stick with my standard answer: "It depends." Unfortunately, many times, fewer lines of code comes at the cost of readability and maintainability -- and as you know, these are very big concerns of mine.

Let's take a look at some code to see if we can find a good balance. The code is taken from "IEnumerable, ISaveable, IDontGetIt: Interfaces in .NET". Now, I have a tendency to be a bit verbose when I'm starting an application. This helps with debugging, especially in the early stages.

Here's how the method stands in the downloaded code (from the RepositoryFactory.cs file). We'll refer to this as the 5-line version:


This method dynamically loads a type from an assembly based on configuration. In this case, it returns a concrete repository class that implements the IPersonRepository interface. Let's do a quick step through this method to see what each line does:
  1. We pull a value out of the configuration file. This value is the assembly-qualified name of the type we want to load.
  2. Based on the assembly-qualified name (from #1), we use the GetType method to generate a CLR Type object.
  3. With a Type object, we can use the Activator class to create an actual instance of that Type. The CreateInstance method returns an "object" that we stick into the "repoInstance" variable.
  4. Since we need something that implements the IPersonRepository interface, we cast our "object" to "IPersonRepository".
  5. Finally, we return the repository, which is an IPersonRepository.
That's a lot of steps, and it's okay if you don't understand exactly what's going on. What we want to focus on is the number of intermediate variables that we have in this method. We actually have 4 variables: repoTypeName, repoType, repoInstance, and repo.

Getting Rid of Intermediate Variables
We can eliminate some of these intermediate variables by inlining them -- basically, we just replace the variable usage with its assignment.

The easiest thing to do is to combine lines 3 and 4 to get rid of the intermediate "repoInstance" variable:


So, we immediately cast the return value from the CreateInstance method to an "IPersonRepository".

But then, do we really need the "repo" variable? All we do is return it in the next line. So, let's combine lines 3 and 4:


This gives us a fairly compact method.

But Why Stop There?
Let's keep going. We can get rid of the "repoTypeName" variable by combining lines 1 and 2:


We just take the "AppSettings" statement and use it directly as a parameter for the "GetType" method. Now we're down to 2 lines of code, and we only have 1 intermediate variable.

Can we get this down to just 1 line?


Of course we can. But it's a little difficult to read since it's stretched out. Let's add a few line breaks:


This is still a single line of code (at least in the source -- what it gets compiled to is a different issue). Now, it's easier to see everything. And the terseness-obsessed developer would be proud.

Is This a Good Idea?
Now that we've whittled things down to 1 line of code, we need to stop and ask ourselves if this is a good idea. Let's look at this code from a couple different perspectives.

Readability
The number one problem I have with the terse code is readability. The degree of readability will depend on the experience of our developers. If our developers have not worked much with reflection, then this code is nearly indecipherable. The advantage with the intermediate variables is that we get some clues as to what is going on in each step based on the variable names (even if we disregard the variable types themselves).

"repoTypeName" lets us know that the value coming out of configuration is the name of a Type. "repoType" lets us know that this is a CLR Type object. "repoInstance" lets us know that we now have an instance of a particular type. And so on...

Maintainability
What if something goes wrong with this code? Let's set a breakpoint:


Uh oh. It doesn't look like this breakpoint is going to do us much good. At least with the intermediate variables, we'll be able to set good breakpoints, and we can see the values that are produced during each step.

Performance
The 1 line version has a small performance benefit. We can see this by looking at the IL that is generated.

Here's the IL for the 1-line version:


And here's the IL for the 5-line version:


If we look at the "meat", we see that the same instructions are run in each version:
  1. call to "get_AppSettings". This gets the AppSettings property from the ConfigurationManager.
  2. ldstr for "RepositoryType". This is the string literal for the setting we want to load.
  3. callvirt to "get_Item(string)". This gets the value that we're looking for from configuration.
  4. call to "GetType". This is the Type.GetType call from our code.
  5. call to "CreateInstance". This is the Activator.CreateInstance call from our code.
  6. isinst for "IPersonRepository". This is the cast to the IPersonRepository interface.
  7. ret. This returns the final value.
The difference between the IL output is in that the 5-line version has the intermediate variables. These are the "stloc" and "ldloc" calls that are interspersed in the code.

So, technically, the 1-line version will be a little faster because it does not deal with these intermediate variables.

But (and this is a BIG BUT), the slowest parts of this method are the reflection calls ("GetType" and "CreateInstance"). These are orders of magnitude slower that the variable code. So, in this case, we really should not worry about the differences in performance. Any slight gain we might get will be overshadowed by the slowness of the reflection code.

Finding the Balance
So, how do we find the balance?

Here's my approach: I start out with the verbose (5-line) method. During the development and early testing process, I want to make sure that the intermediate values are what I expect. So, I like having the extra variables (to put in the Watch window) and extra lines (to add breakpoints).

But once I'm past this, I'd like to refactor things down a bit. My balance point for this method is the 3-line version:


I like this for a couple of reasons. First, I can easily verify (with a breakpoint or watch) that the value I pull out of configuration is what I expect it to be. This is the brittlest part of this method -- configuration is just text in an XML file, and this is very easy to typo or just enter wrong values.

Next, I can verify that the dynamically-loaded assembly is actually available. The "GetType" method uses reflection to load up the specified assembly and get the type information out. If the assembly is not available (or the assembly is available but does not contain the expected type), this step will fail. Again, this is easy to breakpoint, and if there is an exception, it will point right to this line of code.

I'm good with combining the rest of the method into a single line. In my opinion, this is still readable. And we can easily break this into separate lines if we do happen to have problems in this section.

Know Your Team
A big part of this is to understand the skill levels of the people you work with (or the people who will be working with the code). Whenever I'm given a choice between dumbing-down code and making developers better, I will always choose to make the developers better. But sometimes we do not have control over that.

We need to code at a level that the developers understand. So, if I am in an environment where reflection is an unfamiliar topic, then I might just stick with the original 5-line version.

So, know yourself, know your team, and strike the balance that's appropriate for your environment.

Happy Coding!

Thursday, October 17, 2013

How Do I Change Someone Else's Code?

I had an interesting question come up at my Clean Code session at Silicon Valley Code Camp:
How do I change someone else's code?
This question came up as we were talking about refactoring code to improve the readability. And the question was not coming from the technical standpoint, it was coming from the interpersonal standpoint. So, the question could really be stated several different ways:
How do I deal with a developer who is possessive about the changes made to "his" (or "her") code?
How do I tell a developer that his/her code could be more readable?
Let's start with the first question.

Code Ownership
If people are possessive of "their" code in the codebase, this is a sign of a larger issue.

Note: I'm approaching this from a standpoint of developers on a team working for a company just so we have an idea of the environment. But this applies to other types of teams as well.

Our focus really should be on the business -- how the applications we build move the business forward. And the most productive environments I've worked in have this mindset.

In the agile world (and I'm reluctant to use that word since a lot of people who are "Agile" really aren't), everyone on the team is responsible for the code. If someone sees a problem in an application, he is empowered to fix it (or alert someone about it if he is not capable of fixing it himself) -- and arguably, he would be irresponsible to not do anything about it.

So, if you find yourself in a situation where you can't touch a certain module because "that's Jim's code", it might be time to bring in someone to help with the dynamics of the team.

We don't always have control over the team, but we do have control over ourselves. If you find that you're offended that someone changed "your" code, then it's time to take a step back and re-evaluate your own attitude.

Controlling the Ego
Developers are known for having large egos. This really isn't surprising because at its heart, development is more of a creative process than a technical process. The last thing that an artist wants to hear is that you think his painting is ugly. Developers generally react the same way.

But we need to take a step back and look at what we're really doing: we are building tools that propel a business forward. And we don't even own the code we write (from a legal standpoint), the company owns it. This means that the company can do whatever it wants with the code, including rewriting it, breaking it, using it incorrectly, or even never using it at all. So, we cannot get personally attached to any particular function that we create.

I won't say that this is an easy thing to do as a developer. I put a lot of thought and effort into the software that I write. When I see that it is not being used or being used improperly, it really annoys me. But then I take a step back. In my experience, there is very little benefit that comes out getting worked up over these things. I voice my opinion and then let it go (sometimes more successfully than others).

Learn from Other Developers
The same holds true if another developer makes changes to code that you originally wrote. Instead of having a kneejerk reaction, understand that the other developer is not calling your painting ugly. He (hopefully) has the same goal that we all do, to propel the business forward.

So, stop and look at the changes that were made. If you think they are good, learn from them. If you think they are bad, talk to the other developer. Communication goes a very long way in the development world. We don't always approach problems the same way (actually, we probably never approach problems the same way). It's good to understand what someone else is thinking. I've used this several times as a learning experience. And sometimes by working together, we come up with something that neither one would have come up with separately.

It's All in the Approach
So, now let's deal with the second question: How do I tell a developer that his/her code could be more readable?

A great way to approach this is to ask the developer to explain the code. "Hey, Jim, I'm having a little trouble understanding this block of code. Could you help me out?"

If he asks why you're looking at "his" code, tell him that you're just trying to get a better understanding of the system overall.

This may or may not work. It all depends on the other developer. We don't have any control over how other developers react. Just remember to keep your own reactions in check.

If he does explain the code, then you can offer some suggestions to make it more clear to someone just walking up to the code for the first time. Hopefully, you'll be able to work together on making the code better.

Sometimes We're Stuck
If we are part of a dysfunctional development team, sometimes there's nothing we can directly do about it.

But there is a big difference between being *on* a dysfunctional team and being *part of* a dysfunctional team. It is very easy to be overwhelmed by the things going on around you and let them affect you. I've had that experience. I let the problems of a team I was working with get the better of me, and it affected my attitude. I was lucky enough to have someone point this out to me, so I was able to readjust how I was reacting to things.

Attitude is Infectious
Just like a negative attitude is infectious, so is a positive attitude. We can't control others, but we can control ourselves. I've found that if I take a certain attitude toward development (focusing on the business, checking my ego, constant learning), it rubs off on other members of the team.

We *can* change the attitudes on our team. It starts with us re-evaluating our own attitudes. From there, we set a good example, pump out some excellent code, and focus on the goal. Others will want to follow. (And if that doesn't work, polish up the resume. If this is your approach to development, I want to work with you.)

Happy Coding!

Sunday, July 14, 2013

Screencast for Clean Code: The Refactoring Bits

New video available: Clean Code: The Refactoring Bits

New Screencast
One of my latest presentation topics is Clean Code: Homicidal Maniacs Read Code, Too!  One problem is that I usually run out of time during the refactoring portion of the presentation (there's always too much good stuff to talk about).  We always get through the important bits: intentional naming and hierarchical methods, but it's nice to be able to see multiple examples to reinforce the concepts.

To remedy this, I put together a screencast of just the refactoring portion: Clean Code: The Refactoring Bits.  As with all of my presentations, there is a PDF walkthrough of the session available on my website at the link above.

Live Presentations
The Clean Code session has received a good response from folks who've attended.  If you want to see it live, be sure to stop by one of these upcoming events:

Saturday/Sunday, July 27-28, 2013
So Cal Code Camp
San Diego, CA
http://www.socalcodecamp.com/

Thursday, August 22, 2013
Southeast Valley .NET User Group
Chandler, AZ
http://www.sevdnug.org/Home.aspx

Saturday/Sunday, October 5-6, 2013
Silicon Valley Code Camp
Los Altos Hills, CA
http://www.siliconvalley-codecamp.com/

These are the events I currently have on my schedule; I'm sure there will be others as well.  If you'd like me to come to your user group, Code Camp, or other event, feel free to send in a request through INETA or contact me through my website.

I hope to see you at an upcoming event.

Happy Coding!

Saturday, July 6, 2013

Clean Code Question: Exception Handling

Earlier this week, I spoke about Clean Code (Clean Code: Homicidal Maniacs Read Code, Too!) and a couple of questions came up that are good to explore a little further.  In the last article, we talked about properties vs. methods.  This time, we'll think a little more about exception handling.

Exception Handling
This question came up during the refactoring portion of the session.  Here's the code before the refactoring:


Notice that there are two places where exceptions may be thrown.  This will result if the dependency injection container is not initialized properly.

As noted in the session, this is not bad code.  The method is short, and there isn't much complexity.  But it does take a little while to figure out what it's doing.  Our goal is to make this readable, so we refactored out two of the "detail" parts into separate methods.

The updated code looks like this:


Now the original "Initialize" method is easier to follow.  It performs 3 actions, and if we need to drill into the details, we can.  But if we don't need the details, we still have a good idea of what this method is doing.

This leads us to the question:
Where does the try/catch block go?
Since we know that this method could throw an exception, shouldn't we have this wrapped in a try/catch block?  And should we have the try/catch in the original "Initialize" method?  Or should it be in the detail methods?

A Global Exception Handler
So, the answer I gave is that we don't catch exceptions here, we have a global exception handler that takes care of that.  For this application (which is based on a production application), the scenario is that if we have a problem on the client-side code, there really isn't much that we can do about it other than log it and reset.

This was just the first implementation of error handling for this application.  If a workflow failed partway through, it would generally be due to a server error.  The client application really doesn't do much beyond display, basic data validation, and submitting to the server.  If there is an error, the application would alert the user that something went wrong, log the error to the logging service, and reset the user application.  This could result in lost (unsubmitted) data, but this was considered acceptable to the business.  If it became a problem, then a more robust solution with client-side storage would be put into place.

Here's an example of a global exception handler.  This is in the "App.xaml.cs" file in the WPF sample:


So, we can see that our sample application would just shut down (and this is highly simplified for this sample).  But this leads us to an important part of exception handling:
Only catch an exception if there's something you can do with it.
Let's explore this a little further.

Catching Exceptions
Back to the original question: should we have a try/catch block in our high-level "Initialize" method, or should we have the try/catch blocks in the detail methods?

The answer is neither.

In this instance, an exception will get thrown if the dependency injection container is not initialized with the required objects.  If the service (IPersonService) is not configured in the container, it will throw an error.  If the model (CatalogOrder) is not configured in the container, it will throw an error.

If the Dependency Injection container is not populated with the right objects, then what can our class (a View Model) do about it?  The answer is nothing.  Our class relies on having a correctly configured DI container.  Someone else is responsible for making sure that happens.

If we caught the exception, what would we do with it?  In this case, there really isn't much we could do.  We could alert the user that there is a problem, and we could log the error, but that's about it.  We can't "recover" from this problem; our View Model will not work.  So, we don't gain anything by trying to handle the error here versus letting the global exception handler take care of things.

We've seen how we should not catch an exception if we can't do anything with it.  But there are times when we want to try again.  For example, if we are making a service call, we may get a TimeoutException.

In that scenario, we could catch the TimeoutException locally, wait a few seconds, and then try the service call again.  If we fail again (or maybe after a few more tries), then we will simply let the exception propagate up to our global exception handler.

Wrap Up
Exception handling is a big topic.  There are a lot of different approaches.  Our primary focus is that our application behaves appropriately.  There may be times that the risk of data corruption is high and we want to simply abandon all of our uncommitted changes.  There may be times that our application is left in an inconsistent state, and we need to try to reset it somehow.

And there may be times when we can handle the exception by trying again or by alerting the user of a change that he needs to make in order for the transaction to succeed.

What our simple sample shows is that we don't always need to handle exceptions locally.  There are times where it is appropriate to let an exception propagate up to the next level.

Exceptions in .NET are an example of the Chain of Responsibility pattern.  For more information, check out "Learn the Lingo: Design Patterns" that talks specifically about Exceptions and the Chain of Responsibility.  We just need to make sure that our exceptions don't drop off the end of the chain.  Something needs to be there to pick up any unhandled exceptions.

Happy Coding!

Friday, July 5, 2013

Clean Code Question: Properties vs. Methods

Earlier this week, I spoke about Clean Code (Clean Code: Homicidal Maniacs Read Code, Too!) and a couple of questions came up that are good to explore a little further.  We'll talk about properties here.  In the next article, we'll think a little more about exception handling.

Properties vs. Methods
The first question had to do with the refactoring of a conditional.  Here's the original code:


It's easy to see what this block is doing (checking to see if something is more than 10 seconds old), but it doesn't really tell us why.  In following our principle of intentional naming, we want to make the code a bit more clear.  So, we created a property called IsCacheValid wrap the details:


Now, we can tell that this conditional is checking to see if the cache is valid.  If we need details on how that decision is made, we can drill into the property.

So, the question came up:
Why use a property here instead of a method?
A very good question.  My answer was that it didn't really matter either way and that I chose a property to show other ways of wrapping details other than just methods.

That's mostly true from a "wanting to show stuff" standpoint of this particular session, but there's a little more consideration to give this.

Let's see what this same code looks like as a method:


There's not that much difference.  Just a few syntactic changes: (1) adding parentheses and (2) removing the "get" block.

Is There a Performance Difference?
Our first concern is to see if there is a performance difference.  We know that Properties are really just methods in disguise (Explained: Properties in .NET or video).  And if we were to explore the IL, we would see some (but not many) differences between the two.

Realistically, even though there are technically some differences that may affect performance, this code will not see any noticeable difference.  Remember where this code is: it's in a view model.  This is part of the code our users interact directly with.  In this scenario, the slowest part of this application is the user.  So, we don't need to worry about differences between 10 or 12 clock cycles affecting real-world performance.

Now, if this were in a tight loop or the functionality was called repeatedly (hundreds or thousands of times per second), then we would really need to dig in and see what the performance is.  But in this case, the difference is undetectable.

Is There a Readability Difference?
So, now that we've decided we don't need to be concerned about performance differences, we need to focus on the readability of the code and what developers expect to find.

Since the conditionals end up being almost identical, it's hard to argue that one is easier to read than the other.

Property:

Method:

So, we'll decide that the physical readability is the same either way.

What do Developers Expect?
The last thing to consider is what would a developer expect to see.  Remember, our goal here is to have code with no surprises.  We want to make it as obvious as possible.  The code should be easily readable by a developer who is not entirely familiar with the details of the application.

So, the only argument that I would have to prefer a Property over a Method has to do with the naming. As discussed in the session, we prefer to have nouns for "things" in our code (classes, properties, parameters, variables).  And we like to have action verbs for our methods and functions.

There is one more state that we talked about: it is common (especially in the XAML world) to have properties that are state verbs.  Some examples would be "IsReadOnly" and "IsEnabled" that we have on a number of UI controls.  These aren't action verbs, they are simply a way to query the current state of an object.

We followed this same naming convention with the "IsCacheValid" property name.  So, in this instance (with this particular name), I would prefer for this to be a property rather than a method.  But we could just as easily change the method name to something more appropriate.

Wrap Up
We've seen that when we're working in the user code space, it doesn't really matter whether we use a property or a method to wrap up coding details.

We do need to be aware of a few standard guidelines regarding properties, such as, we don't want to put "slow" code into properties.  Developers expect properties to return quickly (and definitely not asynchronously).  So, we should not put things like database calls or network calls into properties.  And we should not put processor intensive code into properties -- in cases where we "get" a property many, many times, this can add up.

As always, we need to be aware of our environment.  We need to keep our code unsurprising to other developers.  And we need to make sure that we weigh the pros and cons for the decisions that we make.

The more we understand, the better able we are to make those decisions.

Happy Coding!

Thursday, April 25, 2013

Where Do Curly Braces Belong?

A question came up in one of my sessions this past weekend (Clean Code: Homicidal Maniacs Read Code, Too):

Do you put opening curly braces on the same line or a separate line?

(Let the religious war begin...)  So, I gave the answer, "It usually doesn't matter as long as you are consistent."  There is an exception for one particular language (which I'll mention below).

The Options
So, let's start by looking at the problem.  With any "curly brace" language, we need to decide whether we put the opening curly brace on the same line as the method or conditional, or if we put the curly brace on a separate line.  "Curly brace" languages are basically anything that uses C-style syntax, such as C, C++, Java, C#, and JavaScript (there are others as well).

Option one is to put the curly braces on the same line.  Here's a sample:


Option two is to put the curly braces on a separate line.  Here's a sample:


Each of these styles has its pros and cons.  So, let's take a look at the advantages, and I'll let you know my personal preference.

Camp One: Opening Curly Braces on the Same Line
The biggest advantage to having the opening curly brace on the same line is to save vertical space.  Vertical density is an important topic when talking about easy-to-read code, so this is definitely something that we should consider.

By having the curly brace on the same line, we reduce the (already short) code sample above by 3 lines.  This means that we have more space on the screen to see additional code.

This is also welcome in books and blogs that include code samples since more code can fit in less vertical space.

Camp Two: Opening Curly Braces on a Separate Line
The biggest advantage to having the opening curly brace on a separate line is that the curly braces will always line up visually (assuming that we are also using good horizontal spacing in our code).  This makes it easy to visually spot the beginning of the code block -- we just need to find the end brace and then scan up until we see an opening brace in the same column.

Camp Three: K&R
Now, there is a third camp that I should mention just because you may run across it.  This is the K&R method (from the book The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie - Amazon link).  I recently ran across a curly brace discussion, and they decided that no matter what, K&R is wrong.

I'll have to admit that I didn't know what the K&R method was.  When I'm reading books, I generally don't pay attention to curly brace layout.  As mentioned above, books often use the "same line" version to save space.  So, I went back and took a look through my K&R and was a bit surprised at what I saw.

Here's a sample (based on the same code block from above):


For methods, the opening curly brace is on a separate line.  But for other blocks (such as the "if" statement), the curly brace is on the same line.

I think that we can all agree that consistency should be high up on the list So, we'll take K&R off the list of possible choices.

Pick One & Be Consistent
Ultimately, which style we choose doesn't really matter.  What's important is that we pick one and stay consistent.

As with everything else in the development world, we need to find the balance.  That's why I don't spend time in my session to talk about this particular topic.  People on both sides are extremely passionate about how they do it "the one true way".  But really, there are more important things that we should be discussing.

One Exception: JavaScript
There is one exception to the "it doesn't matter" rule: JavaScript.  JavaScript has a quirk in the language called semicolon insertion.  This means that if the JavaScript parser thinks that you forgot to put a semicolon at the end of a line, it will put one in for you.  This can cause problems.

For more information on this, just do some searches for "JavaScript semicolon insertion", and you'll find tons of results.  This is also mentioned in JavaScript: The Good Parts by Douglas Crockford (Amazon Link + Jeremy's Review).  Of course, he puts this into a section called "The Awful Parts."

So, for JavaScript, we should put our opening curly braces on the same line.  Otherwise, we may get unexpected behavior from our code.

Update 2020: Another Exception: Go
Go uses a C-style syntax with braces for blocks. The language enforces style #1: opening brace on the same line. It also enforces that braces are required for "if" blocks and similar structures, even if there is only one line inside the block.

Personal Choice
Okay, so you've read through all of this, and I still haven't told you my preference.  I like to have the curly braces on a separate line.  There are 2 reasons for this.

First, I like that the curly braces line up.  This helps me see where the blocks are.  (The same was true when I programmed Delphi (Object Pascal) -- I like to have "Begin" and "End" statements line up.)

Second, I'm a lazy programmer.  I constantly let Visual Studio reformat my code for me (Ctrl+K, Ctrl+R).  The defaults for Visual Studio are to put the opening curly brace on a separate line (unless both curly braces are on the same line -- but that's an entirely different discussion).  As a side note, if you get the "Productivity Power Tools" for VS2012, there is an option to have it reformat your code automatically when you save a file; I don't have this turned on.

You can change the way that Visual Studio formats your code; there's a whole slew of options available.  This is why I put this into the "lazy programmer" category.  For the most part, I run with the Visual Studio defaults (unless there is something that really bugs me).  I have a history of moving around to a variety of machines, so I usually have as little customization as possible so that they will all behave the same.  (I know, there are ways to export profile settings now, but I'm still stuck in my old ways.)

Wrap Up
I always find it interesting to have these types of discussions with other developers.  I like to see who takes it seriously and who sees it as an arbitrary choice.  There's also plenty of other people in between.

Pick your battles.  In a team environment, we need to make sure that we all work in a consistent manner.  Ultimately, where the curly braces go is pretty unimportant compared to other things -- like unit testing strategies.

So, keep your curly braces consistent.  And make sure you're using "the one true way." <smirk/>

Happy Coding!