Friday, December 9, 2011

How to write readable code? 5 Tips to improve your code readability.

Written by Alberto Gutierrez

Readability is one of the most important characteristics of good code. These are a few tips that may help you to produce it.

1.- Use a top down approach (TDD).

Using a top down approach is similar to TDD you start with the highest level logic: the validation of what your code has to perform (The unit test), and then you add layers of abstraction, which as you keep coding become more separated from the domain problem and more related with implementation details. This approach helps to produce more readable code because:

  1. Producing the unit tests will give you a general idea about how readable is your code. Readable unit tests generally mean readable code.
  2. Separating the implementation details and the domain logic makes them easy to understand.

2.- Make your design match your domain (LRG and DDD).

In the excellent book applying UML and patterns, Craig Larman introduces the concept of Low Representational Gap (LRG). The representational gap is how different is the domain logic of an application from its design, having a low representational gap means that the design has very few differences with the domain logic it represents. LRG and Domain Driven Design DDD are much related concepts as they both focus on designing a domain model that matches the real model.

An application that has a LRG will be much easier to read because the actual domain logic will match the implementation domain logic.

3.- Use abstractions only when necessary (YAGNI and KISS).

Sometimes is tempting to make everything too much flexible. As software developers we always have to have in mind these two principles: You Are Not Going to Need It (YAGNI) and Keep It Short and Simple (KISS), remember: Code is not better because it has abstraction layers that may be useful in the future, they are going to make your code harder to read, just use abstraction layers when you need them now, not just in case they are necessary in the future.

4.- Use good names.

Using good names in your code is critical, it will make a difference between a code which will be read as plain English and a code where you will be shouting WTF?!! every two lines.

In this article: tips to write variable names, there are a few tips that can actually be applied to name any named element not only variables.

5.- The 5 minutes explanation test.

Apart from using the previous 4 tips and some other guidelines you may think appropriate to create readable code, I like to pass the 5 minutes explanation test to my code to know how readable it is.

  1. Grab a fellow programmer who spares some time to review your code
  2. Walk him through your code, just a high level introduction.
  3. Ask him if he understood your code.

After following these steps you can evaluate how readable your code is based on how much it took you to explain it. I call it the 5 minutes explanation test because as a rule of thumb if it takes more than 5 minutes for the other programmer to have a high level idea of the design, assume that the code is not readable.

10 commandments for creating good code

Written by Alberto G

1.- DRY: Don't repeat yourself.

DRY is usually the easiest principle to understand, but it is quite harder to apply. It means that when finding similar code in two or more places, we should abstract them into a new method and change the previous code fragments so they will now call the new method with the appropriate parameters.

DRY is maybe the most universal coding principle, I have never found a developer who would argue that repeating code is good, but, I have found developers that forget about this principle when coding unit tests, as an example: imagine that you have changed the interface of a class which had lots of unit tests, if you haven't used DRY, you will have to manually change the call to this class interface to match the new signatures to each test case.

2.- Write short methods.

There are three very good reasons for writing short methods.

  1. Your code will be easier to read.
  2. Your code will be easier to reuse (short methods are likely to produce loose coupling).
  3. Your code will be easier to test.

3.- Use good names for your classes, methods and variables.

There is nothing nicer than using some other developer code and not having to read its documentation because the names of the classes and the methods are telling us everything, so, make everyone's life easier and take this approach, expend always a few seconds before naming any element in your code.

4.- Assign the right responsibility to each class.

One class, one responsibility, that will sound familiar to those who know about the SOLID principles, but not any responsibility, the right responsibility, so if we have the class Customer, we won't assign to it the responsibility to create a new sales action, we will just assign it the responsibility to handle all the data related with a customer.

5.- Keep your code organized.

This organization is at two levels.

  • Physical organization: Whatever the structure you are using, packages, namespaces, folders… Organize your classes in such a way that is easy and intuitive to find where the code is stored.
  • Logical organization: Whatever belongs logically together should have access to each other members, but what belongs to a different logic structure has to access them by an interface. These logic groups are commonly implemented as layers, services…

6.- Create lots of unit tests.

The most tests you have, the better, they are our safety net for all the changes we will have to perform in the code in the future.

7.- Refactor often and sooner.

Software development is a continuous discovery process, in order to keep up to date with good code that matches the new/changing requirements is essential to refactor the code as we go. As this is a risky task there are 2 main preconditions to avoid entering new bugs into the system.

  1. Have lots of unit tests.
  2. Do small refactor steps at a time. In software development there are very few things more annoying than start refactoring 2000 lines of code to after 3 hours of work realize that is necessary to roll back to the original version because now nothing works and the track of which change is causing the problem is lost.

8.- Comments are evil.

This particular one is a bit controversial, most of us were taught that comments are good, and actually it's better to have a comment in an obscure piece of code than just having the code by itself, what this point means is that: even better than having a comment for an obscure piece of code is to not to have that code at all, just refactor it until is a nice and readable piece of code. [EDIT] Please read this other post for a better explanation of what "comments are evil" means.

9.- Code to an interface, not to an implementation.

This is a classic one, coding to an interface will free us from the implementation details, we just define a contract and rely on calling the defined operations on the contract, expecting that the actual implementation will be passed to our code or decided at runtime.

10.- Have code reviews.

We all make mistakes, and there's nothing better than asking some other person to have a quick and informal review in our code to find them, in order to make the reviews,  it's better not to wait until the code is completed, it's better to ask for reviews whenever some important part of the code has been completed or when a few days have passed from the previous review.

5 Tips for creating good code every day; or how to become a good software developer

Written by Alberto G

Being a good developer is like being any other good professional, it's all it's about doing as much quality work as possible. There is a popular sentence that summarises it: "Do it. Do it right. Do it right now".

1.- Have your own to do list for the day.

The best approach to complete complex activities is to break them down into simple activities. Do this every morning by breaking down the different activities you would like to complete for the day and assign them a schedule. This will help you to:

  • Have a better understanding of the activity.
  • Have a focused goal for the day
  • Improve your estimating skills. After a few days you will find that you can predict how much work you can do in a day.

2.- Do one thing at a time.

It's been proven by different studies and published in different media (ie CNN) that it  is more productive to be focus only on one task than to do multitasking.

Work in short batches of intense work of about 25 minutes with a 5-10 minutes rest. There are popular techniques like the pomodoro technique to help you manage the time. There are also tools to help you measure the time you spent on the different tasks, my favorite one is CoolTimer.

3.- Do it right.

There are two keys to know if something is done right

  1. To be proud of the solution; it is not just any solution, it is a good solution. It follows the principles of the "Pyramid of the software quality".
  2. The solution passes at least one review. Ask one of your colleagues that you respect as a good developer to review your solution and for his sincere opinion.

4.- Don't finish something until it's completely done.

We all know that if there's still a glass to wash, we cannot say that we have done the dishes, the same applies for painting a wall or driving to a destination but in software development we don't do that, we say that we are done even when we haven't completed all the unit tests or when we haven't checked if the implementation is correct with the customer, that's a typical behavior from Hope Driven Development and that's evil.

Something is only done when you are 100% sure that it won't be necessary to work at all on that solution unless the requirements change.

5.- Better late than sorry BUT better sorry than never.

If it's going to take you an extra day to complete the testing of some code, or to refactor a class which is unreadable, do it, that's an investment in time for the future, but if you are stuck with something and you are delaying the project too much, just find an easier solution. It may not be as elegant as the one you are implementing, but at least you will have a solution. Make sure to document it as future risk for the project and something that will probably need to be revisited.


7 best practices for taking decisions in the development team

Written by Alberto G

During the software development process, a lot of decisions have to be taken, they may be related to design or architectural issues, testing approaches and many other different areas… What follows is the 7 best practices for making the most when you are about to take a decision in your team

The 7 Good practices.

1.- Have a clear goal. (A vision statement)

Good Example: "We need to decide on what technology we are going to use for the UI of the next product".

Bad Example: "What are we going to do next week?".

Write it in a board making sure that everyone can read it. (Importance of boards are highlighted in the 6th point)

2.- Gather all the inputs.

As explained in my previous article about inputs, outputs and actions, inputs are the clues that leads us to find the best solution, in order to take the best decision we need to make sure that we  have the appropiate inputs.

Good Examples: "We are not tight to use the same technology for the backend and the frontend", "Inside the team there is strong expertise in technologies x,y and z", "The dead line for the UI is in one month"…

Write them in the board as well. (Importance of boards are highlighted in the 6th point)

3.- Keep the discussion objective

Opinions should be translated into facts and numerical arguments, if not it will be impossible to compare with each other, keep an eye on the following symptoms of a non objective discussion

- Don't use Buzz words/be vague/use the word "should".

Some examples: "This approach should be easy", "performance is going to be bad", "what I am suggesting is a best practice in the industry"….

- Don't let people speaking in future terms (if they are outside of the scope).

If the scope of the solution doesn't include any point that states that the solution has to be time proof, then don't let people use that argument to discuss. Example: "Well, I don't like this logging approach because there is too much overhead data, and maybe in one year we will run out of space".

- Avoid people from first being understood rather than to understand.

Lots of time two persons argue about something but they are basically saying the same thing with different words, two tricks to avoid this are:

- Don't let people interrupt
- Make them rephrase other people point with polite questions like: "Sorry Tom, just to make sure you understood Andrew point could you rephrase it?".

4.- Don't make it personal

If deciding A or B becomes deciding if Bob is better having good ideas than Harry, your may be discussing for the next two weeks.

- Separate opinions from people.

Write them in the board and call them with letters or numbers, NEVER write besides them who suggested the idea. Try to mix the best from all the ideas rather than selecting just one person approach.

- Be careful with the egos.

Software developers usually have huge egos, actually the better is a developer, the bigger is his ego.

5.- Timebox the decision, make the decision process takes as short as possible.

As we will see in the last part of the article it's not about the idea is about the execution, but we still want a good enough decision, as a rule of thumb, if the vision is clear, the inputs have been discovered and every one have expressed their opinion, it shouldn't take longer than 15 minutes to make a decision.

6.- Keep Focused

Book a room with a board. The idea of having a board is to picture all that has been discussed, at least in the board there should be the "Vision" (Point1), "Inputs" (Point2), all the different alternatives, and the final decision.

Don't discuss anything outside the scope of what needs to be decide.

Focus on "why" rather than "how" or "what", just make them explain why a solution is better or worse, is very easy to get stuck in implementation details.

Make people describe their opinions in short sentences and write them on the board.

7.- Make everyone participant of the final decision.

Have a final solution that includes the best from every alternative, thank everyone for their effort.

At the end all is about the execution, not the idea.

Even being important to have a good decision, what matter is the execution, that's why point5 focus on make the decision making process as quick as possible.


ITWORLD
If you have any question then you put your question as comments.

Put your suggestions as comments