Posts Tagged ‘software craftsmanship’

Extend Your Toolbox: Custom Matchers

Posted in Programming, testing on February 4th, 2012 by Aviv Ben-Yosef – Be the first to comment

I’d like to point out a really nice testing practice that I’ve been loving more and more lately.

Just about every mature testing framework out there supports the concept of custom matchers, which provide us with the ability to define our very own assertions seamlessly into the tests. Even though this ability is quite old, we don’t see it used too often and I think that’s a shame. I’ve seen this practice heavily used in the mind expanding GOOS book and just now am starting to realize its awesomeness.

toolbox

Your Testing Toolbox


Note: examples in this post are shown in Ruby using RSpec’s matchers but the concept is pretty much identical (as can be seen for example in Java’s Hamcrest Matchers).

Matchers 101

Creating your own matcher usually means creating a Matcher class that performs the assertions, supplies human readable error messages and a nice constructor.

Here’s an example from the RSpec documentation:

RSpec::Matchers.define :be_a_multiple_of do |expected|
  match do |actual|
    actual % expected == 0
  end
end

Matchers increase readability and intent

As you should know, one of the most important rules for design is Reveals Intent. Take a quick look here, which way do you think reveals more intent?

# This
response['X-Runtime'].should =~ /[\d\.]+/

# .. or this?
response['X-Runtime'].should be_a_number
view raw intent.rb This Gist brought to you by GitHub.

Also, which error message do you prefer? “expected false to be true” or something along the lines of “expected comment to be anonymous”?

Matchers create robust tests

The most important advantage of all is how using matchers easily allows you to steer away from fragile tests which are the bane of a lot of testing efforts.
The mark of good tests is that a change in your code doesn’t require you to perform changes in multiple tests that don’t really care for the change.
Take this code for example:

expected_comment = Comment.new(anonymous: true, user: "the dude", reply_to: nil)
commentor.should_receive(:add).with(expected_comment)

This might seem like a standard test, but that’s not really the case. A test should assert for a single piece of knowledge, and this test actually checks several. If the purpose of this test is to check the behavior of anonymous comments, why should it change if we no longer allow replies? Or if we no longer require users for posting comments?

The magic of matchers is exactly here. You create a new matcher to check specifically the aspect your test cares about and *boom*, you’re decoupled!

commentor.should_receive(:add).with(anonymous_comment)

This simple change makes your tests DRY and cool.

Happy testing!

Your should subscribe to my feed or follow me on twitter!

Stop Bitching: Do Self-Agile

Posted in Programming on January 28th, 2012 by Aviv Ben-Yosef – Be the first to comment

Continuing on this series of the Autonomous Craftsmanship Core we now reach the methodology problem.

“I want to do agile/craftsmanship/etc.”

The key is basically to put the rest of your team aside and focus on how you can do things like you think they should be done. You want to do “agile”? Open the manifesto, read the values, and think on how you can change your own process in order to further yourself the direction you want to get.

Development Practices

This one deserves a post of its own, but luckily for us I’ve already written it! You don’t need permission to write tests, use the right tools, and just coding in an awesome manner.

Your own mini iterations, planning and retrospectives

I think a big part of becoming a better developer is looking at how we work, analyze it, decide where we need practicing and then getting better at it, deliberately. Here are some examples from my own development process.

Pomodoros

I love pair programming. Love it. Love it so much, I find it hard to be productive without a pair when coding. I find that the crazy simple Pomodoro technique is some kind of magic makes-me-focus-real-good drug. Anytime I’m doing tasks on my own I set up my little timer and burn down the todo list. Using pomodoros allows me to keep track of my time, focus, see how good are my estimations and waste less time on reddit. You don’t need anyone else on your team to “allow” you to do pomodoros. Just do it, and see magic happening.

Goals and Retrospectives

Just like in an agile team we plan sprints, have retrospectives and set goals, I do the same for myself, both at work and for my personal time. Every week I do a retrospective of the past week, think what I did wrong and what I like. I have monthly and weekly goals. I’ve got recurring tasks in OmniFocus to review my work. I write the reviews in Evernote and then create new goals and add them to OmniFocus. That way every week and month I can go over the last few weeks and see how I’m doing. For example, I can set goals for finishing a book, write some blog posts, communicate better at work, etc.

It’s up to you

Uncle Bob Martin said it’s not your boss’s responsibility to make sure you learn and become better, it’s yours. Once you realize this, stop waiting for things to get better by themselves and step up you can actively become better. I was surprised how many of these aspects coincide with what Seth Godin talks about in Linchpin. You have no excuses not to be doing better things. It’s you’re responsibility, so stop bitching and do awesome work.

You should subscribe to my feed or follow me on twitter!

Stop Bitching: Use the Tools You Want

Posted in Programming on December 18th, 2011 by Aviv Ben-Yosef – 1 Comment

Continuing on the thread of the Autonomous Craftsmanship Core, we reach another problem: “they” just won’t let you use the right tool, or in the right way. As I’ve said in the previous posts if anything is so bad you can’t work with it – leave; otherwise, you gotta learn how to make do.

A pragmatic programmer uses the right tool for the job. We all know that if you have a hammer, every problem looks like a nail. In this post I’m talking about the situation where you have an awesome toolbox right there and yet they’re forcing you to unscrew something with your pinky’s nail. Excruciating to your brain.

The thing is, a lot of the times you can just use the right tools and the hell with everyone else. Yes, you can’t just write code in whatever programming language you want, but in a lot of other situations, you can do what you want to. I think this is best shown with a few examples:

“Don’t commit too much. Say once a day”

That’s a real quote a friend’s boss told him. Turns out committing multiple times a day is too messy. Most programmers might just sulk and do as they’re told, but with today’s technology you’re no longer bound to these stupid rules. Your team uses subversion? So what! You can use Git locally, do whatever you like, and just push once a day everything via git-svn. Same solutions are available for just about any VCS combination you can think of! I’ve done this several times working on projects with a VCS I didn’t want to mess with.

“We can’t have a CI server”

Why would someone be against that? Maybe your company doesn’t want to allocate a new server for such a “useless” thing, or maybe the system admins don’t have time for your little “developer toys.” Lucky for everyone, it’s no longer the case that you need complex setup for such stuff. It’s just a matter of looking around. For example, if you’re doing open source you just need to give Travis a look and see you’re suddenly all set. On the other hand if you’re code isn’t open sourced setting up a local Jenkins server is so so easy. You just double click a file and you’ve got it running. If your build isn’t too CPU hogging, you can run it on your box! And I’m almost certain you can find some server with some spare cycles to install it on.

Autonomous Craftsmen Make Do

That sums it up. A craftsman’s gotta do what a craftsman’s gotta do.

You should subscribe to my feed and follow me on twitter!

Your Brain Cares About Code Style

Posted in Programming on December 10th, 2011 by Aviv Ben-Yosef – 8 Comments

My first team had (among many other great attributes) the custom of strictly following a style guide. It was followed so religiously, I’ve yet to come across another place that does so to the same extent. It wasn’t really written down anywhere, but after a couple of weeks of pairing with the other guys you got it.

What does that mean exactly? It means that we wrote code that looked, to a large extent, like it was written like the same guy. We put 2 blank lines between regions. Members had a specific way of documenting. We even used the same idioms for creating empty lists etc. (Java).

If we paired with someone and saw him indent the code the wrong way, we’d go all OCD until it was fixed. And it was regarded totally OK. We didn’t feel like we were nitpicking on each other. It was the way things got done. I even know a guy that would notice extra whitespace at the end of lines (without any IDE help).

Ever since, whenever I see code written with careless indentation and whitespace I feel like the coder who wrote that just doesn’t care enough for the craft. Yes, No Whitespace – No Care!

What’s the big deal?

If code isn’t written in a consistent style in your team, whenever you come across code with the spacing a bit wrong, the first thing your head’s going to process is “I didn’t write this.” This is a natural feeling, and as we all know coders have a hard to restrain impulse to rewrite any piece of code they didn’t write. Once all the code looks the same, that feeling isn’t that hard and you can actually focus on the code itself and have a better sense of ownership. I know, it sounds stupid, but that’s the way our stupid minds work in.

A big part of the Extreme Programming principle Collective Code Ownership is obtained by simply keeping a consistent style. Anything important enough to become a core value of the only methodology that works must be worth the effort to take notice of.

The next time you see code with reckless spacing, change it and let your teammates know. It might be hard at first but the end goal is important – the ability to fluidly read code, without feeling like you’re wearing someone else’s shoes.

You should subscribe to my blog and follow me on twitter!

Stop Bitching: Write Those Damn Tests

Posted in Programming on November 28th, 2011 by Aviv Ben-Yosef – 2 Comments

Diving deeper into the idea of the Autonomous Craftsmanship Core, this time I’d like to talk about one of the first problems a lot of developers face when wanting to start doing clean code.

You read Uncle Bob’s Clean Code, or went to a talk and then go all “Next day at work I’m gonna write tests!!” Then you come to work, and you give the “let’s write tests man!” speech to your teammate, and he just yawns, and slowly the rush fades.

Lots have been written before about introducing tests to a team as a grunt, but I’ll do a quick recap:

You don’t have to ask anyone in order to start and write some tests. Write that first test. Make it pass. Commit. Not that hard, isn’t it?

Usually the next problem is that if no one else on your team runs the tests, they will keep breaking. But can you blame your team? You need to make them understand that running the tests will actually get them something.

For example, I’ve seen that after someone makes a commit that breaks the tests because of a bug, coming over to him and telling him what went wrong and how you found out might make him more interested in the idea of testing. A friend recently told me that he made running tests as simple as a double-click for the developers that don’t write tests. Once it got that easy, they started running them because everyone likes knowing that what they wrote works.

What if your boss won’t let you write tests? Frankly, why the fuck should your boss care? Does he also tell you when to use “while” instead of “for”? I don’t find things such as these to be something any boss should decide about. As I’ve said in the first post, if you find yourself in a place so resistant to change, leave. If you have to stay, do what you have to do. If they won’t let you commit your tests to source control or set up a continuous integration machine, there are solutions, which I’ll discuss on my next post.

In the mean time, focus on writing tests that help your teammates find problems and see how slowly your little tests get more and more traction. It’ll work, because Success begets attention!

You should subscribe to my feed and follow me on twitter!

Stop Bitching: the Autonomous Craftsmanship Core

Posted in Programming on November 12th, 2011 by Aviv Ben-Yosef – 3 Comments

A lot of developers I know keep bitching about how their team isn’t as passionate as they’d like it to be, or about their boss not letting them do things like it should be done. They get into this habit and never advance in the right direction because something is holding them back. I know this situation well, I’m usually one of these guys.

In the spirit of Positivember I’d like to tell you a secret. You can stop whining and start improving. You don’t have to wait for all the stars to align. That cliché about changes starting from yourself is actually right.

I’ve heard almost every complaint in the book:

“My teammates don’t write tests.”
“They won’t let me have a continuous integration server.”
“I can’t use Git.”
“My boss hates it when I make a lot of commits.”
“I was told not to write tests.”
“We’re not doing agile development.”
“I can’t do pair programming.”

If everything above applies, or you really have lots of problems like these, just quit. A developer that really cares about these things usually can find a better job easily. But, if it’s only some of these, remember that no work is perfect. There will always be suboptimal stuff to live with. The trick is not to be all bitter about it, but to actually try and make changes happen, slowly, so you still have fun.

Most if not all of these problems are things you can work around, technologically, mentally or socially. If you just stick to your good ways, you’ll eventually get some followers too.

Step up and realize that everything can start by you and your habits. An Autonomous Craftsmanship Core as I like to call it. Sometimes, you core will seem so awesome from the outside that people will join in on some of your practices. Sometimes it will go unnoticed and you will happily go on programming better and better.

I will blog more on tackling some of the problems I mentioned above, but as a starting point I recommend Apprenticeship Patterns and Driving Technical Change. These great books help a lot in accepting that fact you should take matters into your own hands, and stop bitching.

You should subscribe to my feed and follow me on twitter!

Stepping Up: Do the Pre-Commit Skim

Posted in Programming on November 5th, 2011 by Aviv Ben-Yosef – Be the first to comment

I’m always looking for the easiest way to make my code better, or to train myself to pay more attention to the quality of the code I produce. My latest find is quite obvious yet so very powerful I had to share. Simply put, it’s just going over your code once more before a commit.

Every once in a while, I commit code and forget to add a file. Even worse, I sometimes leave around dead code that I really hate. I’ve found out that simply making a mental note to go over every file I changed before making a commit makes a big difference. It seems like the Boy Scout Rule from Clean Code is a special case of this rule.

The trick is to simply go over every file you’ve changed and look for common pitfalls:

Unused code – Are there methods your changes just made obsolete? Maybe a conditional with an “else” clause that can no longer happen? Delete code! It’s the best code you’ll write today!

Zombie code – Did you start with something that was too complex and is no longer needed? Often in retrospect you can see how to simplify something and spare your colleagues the woes of zombie code.

Overdue refactoring – Look at your changes. Are you pushing a method too far? Maybe making a class too bloated? Maybe it’s time to for some cleaning.

Do you have a better name for it now? Sometimes when you start with something you don’t have a great name for it. After finishing it, you might be able to slap a better name on that class that will make it more obvious to everyone.

Any dangling TODOs? I hate committing TODOs unintentionally.

Make sure it’s all coherent in class-level – Some changes make sense when you’re knee-deep in a change. But step back and make sure it all still makes sense.

 

You should subscribe to my feed and follow me on twitter!

Fight Zombie Code

Posted in Programming on October 28th, 2011 by Aviv Ben-Yosef – 2 Comments

If there’s anything I hate more than dead code, it’s zombie code. Dead code is code that’s remained in the system even though it’s no longer really used.

It might be small, like unused imports, instance variables and methods. It can be whole classes that make up entire features no longer used.

The biggest PITA is when you’re not really aware of the fact the code’s dead and unused, sitting there and occupying precious bits, and stumble across it as part of a task, trying to understand how it influences what you want to do next.

Whenever I recognized something that looks like dead code but I’m not entirely sure, I find it pretty easy to delete it quickly, once I take a look in the version control logs and see when it became no longer in use and why.

Zombie code is code that was never alive, and so couldn’t really become dead. It’s the undead code – code that died right when it was committed. Code that never ran or never worked. The are two reasons I hate zombie code more than “plain” dead code.

The first reason is that it simply wastes more of my time. Looking back in version control won’t help me see the commit in which the code was “decommissioned”, it would just appear to always sit there. That means I have to take extra care to verify that it, in fact, never worked.

The second reason is that it’s plainly someone saying he doesn’t give a damn. I mean, let’s put aside TDD. Heck, let’s put aside unit testing at all. It means the code never even ran the damn thing and saw in his own eyes it did what he claims it did.

Be kind to your teammates. If you’re not a good enough coder to test it, at least see that it runs once in your own eyes.

 

You should subscribe to my feed and follow me on twitter!

When being idiomatic wears you out

Posted in Programming on August 27th, 2011 by Aviv Ben-Yosef – 13 Comments

I believe that when learning a new programming language, it’s really important to learn its idioms and use them. I’ve written procedural C-like code in Java, and bloated Java-like code in Python, but only once you start using a language “like it was meant to” can you really say you’ve started mastering it. Had I not read Effective Java I don’t think I could have ever written a sensible line in this language.

I practically cringe whenever I see someone creating a new list in Java and then adding to it a single element when he just could have used Collections.singletonList(element). I’m that kind of a fanatic.

But, lately I’m getting worn out of being verbose. Yes, you can use the trick above to save a line of code and a lot of typing, but damn it – I just want to say [element]!

Less than a month into BillGuard we realized we don’t want to do all of our coding in Java and started calling Python code from Java (not in the JVM though, since Jython just doesn’t seem solid enough). Running away from Java’s notoriously long idioms, we preferred adding the overhead of having multiple programming languages in one project (which I think justified itself plenty, but it is an overhead).

This solution helped us when doing big stuff we didn’t want to do in Java, stuff that we’d represent in a unique class. But the smaller stuff just kept nagging us. We kept finding ourselves writing 10-15 lines of code to do something we thought trivial and then putting a 1-2 lines of comments before it saying what we actually meant in Python. These eventually lead to a lot of extracted methods which are generally good, but rarely would I extract such logic in Python/Ruby – where it would be a single concise line of code.

Lately, we started toying with just saying “screw the idioms” and doing what feels right. If that means having a JavaSucksUtils class with methods such as zip() and defaultdict_int() so be it. I think that with time this will lead to using a wholly different language in the JVM mostly, but in the mean time this seems to be a nice transition.

I mean, common:

// Why write this..
public static <T, V> Map<T, List<V>> defaultdict_list() {
    return new MapMaker().makeComputingMap(new Function<T, List<V>>() {
        @Override public List<V> apply(T unusedCrap) {
            return Lists.newArrayList();
        }
    });
}

# When you just want this (Python)
defaultdict(list)

# Or this (Ruby)
Hash.new {|h,k| h[k] = []}
view raw gistfile1.txt This Gist brought to you by GitHub.

Now we’ll have to wait and see where this gets us.

You should subscribe to my feed and follow me on twitter!

Crafting Up – Community is Key

Posted in Programming on March 27th, 2011 by Aviv Ben-Yosef – 2 Comments

It’s been almost a year now since the founding of our local Software Craftsmanship group. This, for me, is a huge dream-come-true.

For years I’ve been looking for a good community around here to join, went to several meetups and looked around to no avail. My frustration grew about a year ago when I noticed the Chicago community is so buzzing with activity, people there have a meetup every day almost. That’s why when Uri started organizing the first meeting I jumped in whole-heartedly.

In just a few months the meeting has influenced me quite a lot. First of all I got to meet a lot of new, smart and interesting people I never would have otherwise. It’s not easy to find people that are as passionate about our profession as I am, yet our group didn’t disappoint me.

The meetings also supply my need to pair with new people. Pair programming is a magical way of working and sharing knowledge, and I’ve yet to have a session with a new pair without picking up something new. I love the first minutes where we have to find a common language to get things started, and even more the high fives of getting a green bar.

Also, a good community is the best way to get feedback. I can say I’m trying to leech this to the max. I’ve already gave talks/sessions at 2 meetings, bugging people frequently on twitter and the mailing list. A varied community of like minded people allows you to get different outlooks and insights to things you’ve been neck-deep in for a while.

And last but not least, a good community might make magic stuff happen. I don’t know how, but I’m sure our group had something to do with the fact some of us got to have dinner with Uncle Bob and Brett Schuchert, two awesome coders and Clean Code authors, on their last visit here.

Bottom line, be part of a community, and if there isn’t one around you help start it! It’s a great source of kindred spirits, an invaluable and rare resource!

You should subscribe to my feed and follow me on twitter!