Archive for the ‘Clean code’ Category



I had a blast at SocratesUK 2014

Last week I participated in SocratesUK for the second time. I learned many things, met amazing people and had a lot of fun.

I flu from Tenerife to London the day before and met Sebastian Larsson in the pub where we had a nice chat on professional careers, talking about the resources and techniques we use for improving our skills.

---------- On the way to Cotswolds -----------

The next day I went to meet Sandro,  Gonçalo, Samir and Emanuele - part of the Socrates' team. Sandro drove us to the venue. It was a nice journey, full of rock and fun.

I had the luck of sharing room the Nicole Rauch this time although we almost didn't see each other, there were many things going on so as not to stay in the room for long.

After dinner Codurance sponsored a selection of craft beer in the main room. In that room there were several flipcharts and that helped to host very interesting discussions. Steve Tooke explained the benefits of Specification by Example when we started talking about Cucumber.

Discussing with beers

--------------- Discussing with beers ---------------

 

This year I came up with the idea of booking a dedicated room for deliberate practice where one could code and pair all day long. I exposed the idea during the proposals in the next morning and got the room. The idea was to work on code katas or pet projects together. During the day there were always people in the room but the truth is that for many people it wasn't clear what to expect from the "workshop room".  I had fun pairing with Stefano Cadario and Matt Glover among others and facilitating some exercises like the Word Wrap kata. Next time rather than booking a room I'll be at the bar with my laptop ready to code. I was unlucky this time and my laptop's screen got broken during the flight.

There were like six or seven tracks going on at the same time, some in the garden or the bar and  fortunately none of them was about Scrum or Kanban!

After dinner Pawel Duda and I started a pair programming session at the bar and we ended up doing a kind of Mob Programming with Matt, Uku, Sebastian and Jan using tmate - a terminal sharing tool. We worked on an experiment, trying to solve a Sudoku from the outside in, stubbing out smaller functions. It was kind of brain fuck, it was good practice and fun. Working on experiments, trying different techniques to those you usually apply is one way to improve your skills.  The problem was quite hard and there were situations where Pawel and I couldn't see a mistake and then Matt or Uku spotted it on. I believe somebody took pictures of us, please let me know if you find them out.

sessions in the garden

-------------- Sessions in the garden -------------

 

 The next day I ran a two hours workshop on the fundamentals of TDD and Pair Programming, an introduction. We were just a handful of people which made me realise that most Socrates' participants were seasoned practitionersNaseer Ashraf and Sebastian came along to help with their vision after years of practice. It was really good as we had complementary opinions to make the discussion enriching. It was very nice to see how Matt and Nic Infante realised the value of PP and TDD in terms of empathy and productivity, they found a sustainable pace.

Samir's session

-------------------------- Samir's session ----------------------

Ivan Moore showed us the "refactoring golf" exercise before lunch. I find it useful if we get rid of the "points" and focus just on keeping the tests green.

In the afternoon I attended to Samir's session on refactoring. The exercise was very interesting - avoid primitives in the code and then add new features. The repository is here.

Later on that Pawel and I went to the tiny gym beside the reception desk to work out together. Pawel is an amazing guy. Being able to do some exercise raised my energy levels.

Mob programming

Mob programming on Saturday night - Look how much we cared about the football

After dinner a bunch of us went back to Samir's code, this time in front of the projector, running a Mob programming session. A different person was at the keyboard every 7 minutes with Pawel controlling the time rigorously. Interestingly enough the person at the keyboard always tried to understand and learn IntelliJ shortcuts and the Mac keyboard. Everyone was trying to learn and bring value in a very respectful atmosphere. I was sincerely amazed but the suggestions of my fellow craftsmen.

On Sunday morning I was late to join the group on their walk through the beautiful country side so I stayed in the hotel. In the bar again people were pairing. I started a kata with Sebastian in Java. Then he had to set off but Steve and I took over using Erlang. It was my first Erlang program and I believe Steve's too. I learned several tricks on Vim thanks to Steve and some Erlang which is very cool. This is the code. Unfortunately we didn't commit often to show all the intermediate baby steps.

The way back to London was also very nice. Mashooq took Oliver and Raph to the airport and then gave a lift to Pedro and me. We pretty much crossed London by car it was my tourist tour thanks to the infinite patience of Mashooq. It's funny that I should have met Pedro in England after he's been living in Barcelona for so many years. His Spanish is better than mine! I am glad he is part of Codurance.

I like this year's edition more than the one before but I think it had to do with my attitude and the fact that this time I knew more people already and I had different expectations. Half the participants were new anyway.

What I like the most about this conference is that I get to meet people from whom I can learn a lot but at the same time there is no hierarchy we all treat others with respect. It's definitely important to run open spaces on software craftsmanship where it's about developers, practice and learning.

For this reason some friends and I are thinking of organising and hosting Socrates Canaries on the next winter, when it's cold in Europe but warm in the Canary Islands. I'd like to hear from you, would you participate in Socrates Canaries? Please fill in the form and give us your opinion.

Thank you so much to the organisers and to Rachel Davies our excellent facilitator. Thanks also to Farncombe's staff that kindly provided me with a vegan option on every meal - it was delicious. If I can make it next year, I'll be there again!

In a previous post I wrote some examples of method names that use their arguments' names to form an expressive expression:

  • Users findBy(String name){...}

It reads well when looking at the method definition but it may not read well when used:

  • users = findBy(someReallyBadVariableName);
  • users = findBy("bob");

In this case I can prevent consumers from writing unexpressive code with some redundancy:

  • Users findByName(String name){...}

But the redundancy may be annoying in some cases, so when may I avoid the redundancy?

I believe it depends on:

  • If the method has more than one argument, I can't count on the argument's names - still they have to be good names.
  • The level of abstraction of the method:
    If the method or function is a low level one, like in a general purpose library, then I prefer to have some redundancy because it's hard to tell how is it going to be invoked. On the other hand if it's closer to the domain then the usage gets narrower and I feel better counting on the argument's name.
  • The type of the argument - are they primitives or objects?
    If the argument is a primitive like a string, someone may pass a literal into the function thus making the readability bad. However if it's a domain object, literals are not possible and variable names use to be more precise:
    generateOrderFor(shoppingCart);

What others heuristics do you usually consider?

With good names for packages, classes, methods, variables,... code should be self-explanatory.  Long method names are not a problem if they really make code read better and don't reveal too much implementation details. Names are more powerful than most developers usually think, they have a profound impact on our designs. In general names should be pronounceable but there are always exceptions.

  • In a small loop, it's OK to name the index i, j, k or something like that you don't have to say theLoopIndexWhatever. In fact, "i" reads better in a short loop.
  • Methods should not contain concrete details, those should be parameters instead:     

            assertThatThereAreTwoResults(results)

          Should better be written like:

                      assertThatThereAre(2, results)

  • Method names should say what they do, but not how:

            addWordIfIsValidAndHasCorrectLength(word,  results)

          Should may be:

                     addValid(word, toResults);

  • The name of the class should be considered when naming methods. The name of the methods should be considered when naming its arguments. Given that methods should not have more than 3 parameters (the less the better), the names of the arguments may be combined with the name of the method, specially if there is a single parameter. Good names care about their context.

            result = expressionResolver.resolveExpression(expression)

          Reads better like this:

                     result = resolver.process(expression)

  • In the case of test methods, the name should describe the behavior without concrete details. The details are inside method body. The test method name is the description and the body is the example:

            one_plus_two_returns_three()
          Should be:

                     sums_two_single_digit_numbers()

  • Names should not contain technical details, like the types , because they are an excuse not to search for proper domain names. Modern IDEs provide enough help for the programmer to find out types, code should be business domain oriented.

            parseString(expression)
          Should be:

                     parse(expression)

Avoid prefixes and suffixes like "Abstract*", "I*" (ISomething), "*Impl"...

Don't let the syntactic noise bother you when choosing your names, the fact that there is a brace in the middle should not impede you from writing a line of code that reads like well-written prose 😉

I'll probably will go on updating this post with more examples.

 

Methods should be short, from 1 to 7 lines of code, maximum 10 in some cases (with the exception of some algorithms). Because a method does just one thing its name should describe it precisely. But it should not contain implementation details (like data types). The name of the method is the "what" and the implementation is the "how". Try to avoid implementation details in the name.
When you find yourself using the words "and/or" in your methods names, consider that you might be exposing too many implementation details and try to search for a better name.

Sometimes, people new to this kind of modularity end up creating methods that are not necessary:

  1.  
  2. private boolean checkIfCharsAreEqual(char[] wordArray,int first_char, int second_char) {
  3. if (wordArray[first_char] != wordArray[second_char]){
  4. return false;
  5. }else{
  6. return true;
  7. }
  8. }
  9.  

This method does not add any clarity to the code. Moreover boolean methods can just return the condition:

  1.  
  2. private boolean checkIfCharsAreEqual(char[] wordArray,int first_char, int second_char) {
  3. return (wordArray[first_char] != wordArray[second_char]);
  4. }
  5.  

There is no need for the "if-else" block when the result of the condition is the return value of the function/method. Even after this change, the method does not make sense. Try to "inline" the method to see whether the code invoking it reads equally good.

When conditionals contains more than one boolean expression (using logic operators AND/OR) then I usually prefer to extract a method so that the reader doesn't have to think, just read and understand:

  1.  
  2. // before:
  3. if (someCondition(arg1) && !someOtherCondition(arg2))
  4.  
  5. // after:
  6. if (isSomeCaseWithProperName(arg1, arg2))
  7.  

When methods are boolean, try to name them so that they read well preceded by the "if" keyword. I like using the prefixes "is" and "are" or "areThere" for boolean methods operating on single variables and collections respectively.

When the new method is just an alias of another method, consider whether adding it adds any value in terms of readability:

  1.  
  2. result = someVar.toUpperCase(); // is good/clear enough
  3.  
  4. // Whilst this method does not make sense:
  5. public String convertToUpper(String input){
  6. return input.toUpperCase();
  7. }
  8.  
  9. // And this method does not bring value:
  10. private void addWordToList(List<String> palindromes, String word) {
  11. palindromes.add(wordToBeChecked);
  12. }
  13.  
  14. // And this method does not bring any value:
  15. public boolean stringContainsAtLeastOneSpace(String input) {
  16. if (input.contains(" ")){
  17. return true;
  18. }
  19. return false;
  20. }
  21.  

Also notice that the prefix "string" in the method name is redundant because the parameter is a string. In the case of methods with one or two arguments, consider using names for the arguments that read well together with the method name:

  1.  
  2. public User findBy(int phoneNumber){
  3. ...
  4. };
  5.  

I believe the idea of a single exit point for functions comes from the 70's. A function used to have only one exit point, a single return statement. I still see some developers doing this but it's not a good idea. As soon as you have found what you were looking for, just get out the function.

The old style:

  1.  
  2. public int someMethod(String input) {
  3. int code = 0;
  4. if (someCondition(input))
  5. code = 1;
  6. else if (someOtherCondition(input))
  7. code = 2
  8. return code;
  9. }
  10.  

Improved: returning the value as soon as it's found:

  1.  
  2. public int someMethod(String input) {
  3. if (someCondition(input))
  4. return 1;
  5. if (someOtherCondition(input))
  6. return 2;
  7. return 0;
  8. }
  9.  

The second example is not only shorter but also less exposed to defects. In the first example, if for some reason I forgot the "else" and the second condition applies, I'd be returning the wrong value.

The reasons to return as soon as possible are:

  • Code is usually more simple
  • The likelihood of future defects is lower

"Feature envy" is a typical code smell in Object Oriented Programming. It can be appreciated when code talking to an object accesses directly to that object's fields or properties, from the outside, breaking the encapsulation.

  1. // feature envy:
  2. fullName = person.name + " " + person.surname;
  3.  
  4. // possible solution:
  5. fullName = person.fullName();

The "Tell, don't ask" principle helps to avoid feature envy when used properly, by using a declarative approach instead of a procedural one. This is, rather than asking a method for a value to make a decision based on the answer, we tell the method to perform an action. Any decisions based entirely upon the state of one object should be made "inside" the object itself. This principle promotes encapsulation, and low coupling. Query methods (method returning values) can't be totally avoided, in fact they shouldn't, but they can be pushed down to places where coupling is affordable, thus avoiding coupling high level classes, reducing the impact of changes.

"Tell, don't ask", and "Law of Demeter" were explained  by Andy Hunt and Dave Thomas in a IEEE Software column and on their site. Also recently by Martin Fowler.

Recently, I came across an "extract method" refactoring promoting this principle that makes the code easier to read and maintain:

Before:

  1.  
  2. // Service class:
  3. ...
  4. public virtual void RequestPin(User user) {
  5. var newPin = PinBuilder.CreateNewPin();
  6. PinRepository.SaveNewPinFor(newPin, user.UniqueIdentifier);
  7. SmsProxy.SendSms(user.Phone, CreateSMSMessage(newPin));
  8. }
  9. ...
  10.  
  11.  

After:

  1.  
  2. // Service class:
  3. ...
  4. public virtual void RequestPin(User user) {
  5. var newPin = PinBuilder.CreateNewPin();
  6. user.ResetPIN(newPin, PinRepository);
  7. user.RequestSMS(CreateSMSMessage(newPin), SmsProxy);
  8. }
  9. ...
  10.  
  11. // User class:
  12. ...
  13. public void ResetPIN(string newPin, PinRepository pinRepository) {
  14. pinRepository.SaveNewPinFor(UniqueIdentifier, newPin);
  15. }
  16.  
  17. public void ReceiveSMS(string message, SmsProxy smsProxy) {
  18. smsProxy.SendSms(Phone, message);
  19. }
  20. ...
  21.  

This refactoring brings several advantages. First, we remove feature envy, because properties "UniqueIdentifier" and "Phone" are used inside the User object. So the data and the behavior are in the same place. If I have to change the field in the future, it will be clear what is it affecting to. Second, the service code is easier to read and encapsulates details that should not be visible there.

It looks weird at first, sending a repository or a service instance as a parameter to an entity's method. I usually do it as I refactor, not upfront. The tests don't need to be changed if they are well-written.

The best coding dojo ever

 


I've got goosebumps on my arms most of the day. And it doesn't happen very often. This is the most emotional coding dojo I've ever facilitated. It's been in Gran Canaria, at the Universidad de Las Palmas de Gran Canaria (EII ULPGC).

The last day in college for some students, where many of them were thinking of their uncertain near future. Asking for recommendations and expressing many doubts.

More than 50 people coding together for more than 8 hours, in an incredible atmosphere.

 

 

How did we get here?

There is only one book on TDD in Spanish so far. Published by my friends and me back in 2010, under the creative commons license. Creative commons is like a virus for this. One year ago a real master, Jose Juan Hernandez (@jjhernandez) decided the book was nice to teach his students how to write clean code. We didn't know each other. In fact I didn't know the book was being used at the University. Jose Juan has been coding since 1985 and I do believe he is a software craftsman, now that I've seen him coding and teaching.
A couple of months ago he contacted me  see if I could give a talk to his students, about TDD in the real world™ and the encounter was excellent. The coding dojo proposal came along right after that.

Why has it been so good?

Guillermo and I

Several factors in here. Jose Juan has been teaching TDD, Refactoring, Patterns and Clean Code to his students the whole year. No only the practices but the values. This is the reason we believe he is a master, because his students have embraced and internalized his values and principles.

  1. So about 30% of the students were familiar with the techniques, and we asked them to pair up with those not exposed to automated tests and example driven design before. And they explained everything to others with passion. 
  2. In a regular coding dojo the facilitator does not necessarily teach. Her goal is facilitating. In this case though, we've been teaching people, so it's been half of a training session. With direct feedback on their work, based on our experience.
  3. We were 3 guys facilitating: Guillermo Pascual (@pasku1), Jose Juan and me. And the sinergy it's been huge.
  4. Everyone was absolutely willing to learn and share. Passionate people, warm and friendly.
  5. It's been a total win-win event. We (facilitators) have felt very useful and appreciated, it's been fulfilling. Some people have discovered a new way of understanding their careers, and what "caring about code" means.
  6. The retrospectives following every iteration were very participative, people were able to discuss among them.
 

Jose Juan

What's next?

  • This is a milestone in the Canary Islands software development community, I can feel it. Something is changing...
  • Let's keep on practising together. The AgileCanarias community is growing and it's a good starting point  o meet new people and learn new stuff. The Tenerife group is kind of mature and stable now, let's do the same in Gran Canaria. And let's join the two groups for dojos and local conferences.
  • We have the Agile Open Space this year in Tenerife. Join us, it's a great opportunity to discover more.
  • Now you know there are different ways of writing software. Keep on learning, it's a never ending path.
  • When is the next coding dojo, who will organize and facilitate it? 🙂

I want to facilitate a dojo, what should I know?

  • Manage people's expectations. In general a coding dojo is not a training session. Be honest with participants and help beginners as much as you can. Otherwise they'll be scared, run away and take a wrong idea about what it is.
  • A dojo is a space for innovation, try different things all the time, you don't have to follow the manual on the go. Just use your imagination and empathy.
  • Ask someone experienced to facilitate it before doing it yourself, if possible.
  • There is an interesting new book on this by Emily Bachehttps://leanpub.com/codingdojohandbook (haven't read it yet), foreword by Uncle Bob Martin.
  • Check out this video by Emily Bache: http://www.youtube.com/watch?v=yao5XLJqogQ

Acknowledgments

  • Jose Juan and Guillermo Pascual.
  • All the participants, of course. Without them, there is nothing to do.
  • Jorge Castellano for his pictures and video. Pictures will be uploaded soon here. Jorge already uploaded some pictures to twitter. Just search for the hashtag #dojoULPGC
  • Fran Santanta for his support and organization. Fran brought journalists from local newspapers and TV, apart from the food and everything else.
  • Mario Hernandez Tejera for his company, hospitality and sharing his interesting/wise thoughts.
  • All the colleagues who work with Jose Juan for his support and energy.
  • JM Beas, Xavi Gost and other folks from Agile Spain, as they introduced me to coding dojos.

This is the related thread in the AgileCanarias mailing list.

fotos de Jorge Castellano
Guillermo Pascual y Carlos Ble
 

 

 

A new change or feature is about to be implemented. There are several places where it can fit in, and all of them seem to respect the Single Responsibility Principle. My tendency used to be adding the new feature where it was easier to place.  However now I consider other criterion. I ask myself this: If I need to navigate through the code base a bunch of months later to read the feature implementation... where would I look at in the first place?

Lesson: once you make sure your code is going to be SOLID, add the new feature in the place readers would expect to find it.

Value objects can contain methods. Otherwise they are just anemic models. Those methods prevent the feature envy code smell and ease refactoring. They manipulate object internals promoting cohesion and low coupling. But don't forget about the Open/Closed principle. If you add that method to the object, is the code still open to extension without modification?

Imagine a value object encapsulating a collection. Now you need a method to sort the items in the collection. Should the "sort" method be part of the collection object? If is there a way to change the sorting algorithm without code modification, then the answer is yes. Otherwise the answer is no. Move the "sort" method to a specific class whose responsibility is sorting.

Writing quality code is about satisfying the expectations of the reader. And the reader might be yourself a couple of months later.

Let me tell you a mistake a made recently. I was test-driving a few classes and one collaborator was a stack. But I only needed the stack to give me the last two items pushed on top of it.  So I ended up with a function like this:

  1. function pop(numberOfItems){
  2. // ... some code dealing with border cases...
  3. // and the happy path:
  4. return [items[len -1], items[len -2]];
  5. }

And everything went well. The stack was good enough for the object using it.
After a few months I needed to use the stack again but I forgot about its internals. I was writing some tests for a new class also depending on a stack. As the stack was already tested, I stubbed out the "pop" method in the new test pretending it could give me the last 3 items on the stack. The unit tests passed and my new class was working fine with the stack. However, it didn't work into production. Lesson:
Although TDD encourages you write only the smallest amount of code necessary to make the test pass, you should implement all the behavior a method is expected to have when someone reads its signature.

In one way or another I was coupling the stack to the class using it. But APIs should always tell the truth. Classes and methods should do what their name say without the need to know how other artifacts consume them.

 

  • Newer Entries →