Mar, 2015

Is Clean Code less Code?

For me clean code is simple, easy to understand code. No over-engineering, as little boilerplate as possible and of course non-cryptic. But does that lead to less code?

I really don’t think so. Most of the times less code is more cryptic and harder to understand (and therefore harder to maintain).

When working with jBehave and testing the meta filtering, I wrote something similar to the following code:

@Override
public Embedder configuredEmbedder() {
Embedder embedder = super.configuredEmbedder();
ignoreStoriesAndScenariosWithMetaInformationParameter(embedder, "ignore");
return embedder;
}

private void ignoreStoriesAndScenariosWithMetaInformationParameter(Embedder embedder, String ignoreParameter) {
embedder.useMetaFilters(Arrays.asList("-" + ignoreParameter));
}

Later, I had a discussion about that code and a colleague said he just deleted the “unnecessary” private method which leads to the following code:

@Override
public Embedder configuredEmbedder() {
Embedder embedder = super.configuredEmbedder();
embedder.useMetaFilters(Arrays.asList("-ignore"));
return embedder;
}

Obviously shorter and less methods. For us, working on that specific class, it may be obvious what’s happening in this method, but just imagine somebody joining the project and never working with jBehave before. For him the longer code provides additional information and even if he does not understand how it works and what “meta filters” are and what the minus means, he’ll at least understand what we are trying to achieve.

When I try to explain my choice, other developers agreed to my point but said that we can also achieve the same result with a comment. And yes, I totally agree that this is a valid option. I think this is just a question of style. I personally don’t like comments (and Uncle Bob’s “Clean Code” is on my site), but maybe in this case the comment really is the better choice because you can explain the connection between this meta filter code and the jBehave story files.

So the resulting code is the following:

@Override
public Embedder configuredEmbedder() {
Embedder embedder = super.configuredEmbedder();
// ignore stories and scenarios with meta information parameter @ignore.
embedder.useMetaFilters(Arrays.asList("-ignore"));
return embedder;
}

Of course you can argue, that this small example isn’t worth talking about. But I think within a project style it is important. And you can find a common style by discussing specific examples. Maybe the other developer will think about if his code could may be unclear to project joiners and I will think about a comment instead of one-line methods.

Conclusion

So clean code isn’t always less code. You need to trade off the benefits of more small methods against lesser lines of code. I’ll discuss the other examples about coding style in some future blog posts.

Which solution is your favorit one and why?

Clean Code and Java 8

I write more and more Java 8 code. But within the last week I wondered if streams and lambdas may lead to code that nobody understands (like generics back in the days). But I’ll give you a few examples and my opinion about it.

Messy Code because of Streams and Lambdas?

I wrote some code like this:

items.stream()
.filter(item -> mapper.hasMappingFor(item))
.map(item -> mapper.map(item))
.findFirst();

Wouldn’t it be more readable for other developers seeing the code for the first time, if I write it like that?

for(Item item : items) {
if (mapper.hasMappingFor(item)) return mapper.map(item);
}

Or does it just feel that way because I see these for-loops every day? In general, I really like fluent APIs and for me the stream-solution seems to be very elegant. Are developers complaining about Java 8 code because they are just old-fashioned? Or is it really harder to understand and maybe also harder to maintain?

Elegance of Streams and Lambdas

Last week I attend at one of our internal coding events and we worked on the yahtzee kata. I had to leave early but because I had a lot of ideas, I worked on that kata on the train, focusing on Java 8 features and check if the code feels clean. The problem I was solving: get all possible yahtzee categories for a given roll. I solved that with an enumeration of categories, each defining an predicated against a given roll is tested.

public Set<Category> possibleCategories() {
return Stream.of(Category.values())
.filter(category -> category.isPossibleCategoryFor(dice))
.collect(Collectors.toSet());
}

And here the definition of the single categories and the check if a dice matches the category:

enum Category {
ONES(hasAtLeastOne(ONE)),
TWOS(hasAtLeastOne(TWO)),
THREES(hasAtLeastOne(THREE)),
FOURS(hasAtLeastOne(FOUR)),
FIVES(hasAtLeastOne(FIVE)),
SIXES(hasAtLeastOne(SIX)),
THREE_OF_A_KIND(atLeastOneDieOccursAtLeastXTimes(3)),
FOUR_OF_A_KIND(atLeastOneDieOccursAtLeastXTimes(4)),
FULL_HOUSE(atLeastOneDieOccursAtLeastXTimes(3)
.and(anotherDieOccursAtLeastYTimes(2))),
SMALL_STRAIGHT(dicesInARow(4)),
LARGE_STRAIGHT(dicesInARow(5)),
YAHTZEE(allDiceAreEqual()),
CHANCE(matchesForEveryDice());

private Predicate<List<Dice>> rule;

private Category(Predicate<List<Dice>> rule) {
this.rule = rule;
}

public boolean isPossibleCategoryFor(Dice dice) {
return rule.test(dice);
}
...
}

Of course you could implement something like this with earlier Java versions as well. Only the method implementations are different.

Here I struggled again, when I wrote the method creating possible straights:

private static Set<Set<Dice>> possibleStraights(int numberOfDice) {
return IntStream.range(0, Dice.values().length - numberOfDice)
.mapToObj(startDice -> IntStream.range(startDice, startDice + numberOfDice)
.mapToObj(die -> Dice.values()[die]).collect(Collectors.toSet()))
.collect(Collectors.toSet());
}

I fear everyone of you thought “WTF?” at the first sight. Although I chose an self-explanatory name (at least I hope so), it’s not clear, what the code does. You may hope, that it really creates a set of possible straights. But after I extract a method it seems more readable again.

private static Set<Set<Dice>> possibleStraights(int numberOfDice) {
return IntStream.range(0, Dice.values().length - numberOfDice)
.mapToObj(startDice -> createStraightStartingAt(startDice, numberOfDice))
.collect(Collectors.toSet());
}

private static Set<Dice> createStraightStartingAt(int startDice, int numberOfDice) {
return IntStream.range(startDice, startDice + numberOfDice)
.mapToObj(die -> Dice.values()[die]).collect(Collectors.toSet());
}

You can find the code on GitHub.

Conclusion

I really think my feeling that the Java 8 code is less readable and maintainable, is just because these Java syntax is quite new. (And maybe I don’t trust other developers, that they are familiar with these new features.)

I am quite sure, that the code is as easy to read and maintain as the “old-fashioned” java style. And in a few month it will be completely common. But we should always think twice, if streams and lambdas are the best possible solution for our problem. Just because we have a hammer, not everything is a nail.

But what do you think? Do you think the code is less cleaner because of the Java 8 syntax?

Make it a good piece of work

During my diploma studies I had an English lecturer who gave use one simple and important advice (besides that “information” never has an “s” 😉 ):

Make it a good peace of work!

Even now, seven years after I finished my diploma study, these words echos in my head.

The good

Of course this is a very valuable advice. You should always give your best. Because:

Anything worth doing, is worth doing right.

So I took it to heart and try to give my best at everything I do. And that is what I expect from a Software Craftsman. Of course it is hard, you have no time, you need to do ten things at once and so on. But I’m sure the quote, echoing in my head over and over again, makes my results better.

The bad

On the other hand, I am never satisfied. Every time I write an important email, I must to force me to click send, because I always thing about “Can I express it that way? Am I impolite?” and so on. Whenever I write a blog post I think “I can not publish it, because it is not good enough!”. There is always so much to improve. And than I start to doubt, if the whole post is even useful. “What is the message?”, “What is the value for the people reading it?”. Even when I code I always find some parts which I want to hide from everybody else, because to me it seems too messy, and so on.

Conclusion

But luckily most of the time I come to the point where I think “It doesn’t matter. You did your best, if somebody will complain, you can do better next time.”, and I click “send” or “publish” or “commit” anyway. And most of the time I even get positive feedback. And if you think about, it is not that extraordinary, because I spend a lot of time doing it and most of the time I thought “You have to make it a good peace of work!” and so I do. Even if it is not perfect, it wouldn’t be that bad.

So I thank my English lecturer for his wise words and hope you will find them helpful, too.

Know your Tools: IntelliJs Shelve Function

I switched to IntelliJ for half a year now. For backend java development I couldn’t figure out lots of advantages compared to eclipse. It always seems to me like it’s six of one and half a dozen of the other. A few things within moving and renaming classes seems to work better, but therefore I always struggle with the module structure. But yesterday I found my killer feature and I’ll never switch back to eclipse until they have this feature too: Shelving changes.

You may know this feature from git, it’s called git stash or mercurial hg shelve. (If you don’t know it check it out! It’s worth it!) You just put your current uncommitted (maybe not even compiling) changes aside to work on a task that cropped up (maybe an important bug fix). I already loved this feature as I learned it in git. In IntelliJ you just click “Shelve Changes..” in the “Changes” view, select all changed files you want to shelve and IntelliJ creates a patch in your “Shelf” (a tab in the “Changes” view).

After you are done with the other tasks, you can unshelve your previous work, again by right clicking on the files in your shelf and selecting “Unshelve changes”. You don’t even need to unshelve all at once. You can also select “Unshelve…” and select only a few files you want to unshelve. If you do so the patch in your shelf stays untouched. If you want to remove the unshelved files from it you need to do it manually. For more details have a look at the IntelliJ documentation.

So if you didn’t know this feature, try it! And if you know an equivalent feature in eclipse, please let me know!

What is Software Craftsmanship?

Definition

A lot of people don’t know what Software Craftsmanship is. Is it just a synonym for Clean Code? No, it isn’t. I really like the definition of Sandro Mancuso, I already shared on Google+ in 2011:

Software craftsmanship is a long journey to mastery. It’s a lifestyle where developers choose to be responsible for their own careers and for improving their craft, constantly learning new tools and techniques. Software Craftsmanship is all about putting responsibility, professionalism, pragmatism and pride back into software development

Important are the words journey, lifestyle, improving, constantly learning, responsibility, professionalism, pragmatism and pride.

A long journey to mastery

Yes it really is a long journey. You need to get a lot of experience, experiment with technologies and architectures. Learn principles, practices, techniques, tools and so on. Some things you will like, some things will turn out to be not practicable and you will stop doing it.

If you really want to be a software craftsman you need to be totally committet. You can’t be a software craftsman for just a few hours. You need to take responsibility. Either you act professional or not. Either you want to improve your craft by constantly learning or you don’t. Only if you are totally in you can make the long journey.

Project Reality

Unfortunately, I met a lot developers who didn’t seem to care. They worked nonprofessional and they didn’t take responsibility. Those developers demotivate their colleagues. Why should I care, if the others mess it up anyway? Working in such teams can be very frustrating.

Why you should care anyway?

I am sure that Software Craftsmanship is worth it – and I’m quite sure you agree, otherwise you wouldn’t read this, right? Even if none of your teammates share your opinions. You can make the project (and your working environment) better! And I’m sure software craftsmen will become a role model for all other developers and can share their knowledge with their teammates, once they see the improvements. And in the worst case (no one cares and maybe they even laugh at you, although you improve something), you can switch your job and use your experience and achievements when you apply to another company.