Coding for readability

In the recent Agile conference, I heard that the code should be written primarily for human readability. Good code is something that does not need any explanation or comments. It does not need any “Knowledge Transfer” from other developer. Good code must be like a book. Anyone who knows the language should be able to read and understand what the author is trying to say.

I am fascinated by the concept, but was wondering  how to apply this concept while actually coding. After all, the code we write has to adhere to the syntax imposed by the language. After thinking for a while, I think I found one way to make this happen. Let me experiment this technique on you, my reader.

Let us consider an example of method used in some financial application for buying stocks. This method takes in the stock Symbol, the number of shares and  customerId as parameters. Can you guess the logic of the code below?

public void BuyStock(string tickerSymbol, int numberToBuy, long customerId)
{
CompanyToTrade company = Get_CompanyToTrade_If_Valid_Ticker(tickerSymbol);
Customer validCustomer = Get_Customer_If_Valid_Id(customerId);
float totalAmount = Calculate_Transaction_Amount(company, numberToBuy);
Check_Customer_Account_Balance(validCustomer, totalAmount);
Deduct_Amount_From_Customer_Account(validCustomer, totalAmount);
bool success = StockExchange_Buy_Stock(tickerSymbol,numberToBuy,customerId);
if(success)
{
Add_Stock_To_Customer_Account(tickerSymbol,numberToBuy);
}
else
{
Rollback_Deduct_Account(validCustomer,totalAmount);
}
}

The logic I tried to implement is as follows -

  • Need to see if the tickerSymbol is valid
  • Need to see if the customerId is valid
  • Need to see if the customer has enough money to buy the “numberToBuy” number of shares
  • Deduct Money
  • Buy the Stock by calling the stock exchange API
  • If above call succeeded, Add stock to customer Account
  • Else rollback the money deducted from the customer

Were you able to understand the logic from the code? If not, which part of the code was not clear? Please let me know in the comments section so that I can update the code.

I feel we can make use of the name of the functions to reveal the logic as it can be written in english. Hence, a good way to write readable code is break down the logic required into a set of steps in english and then convert each of these steps into function names. The actual logic of the step would be inside these functions. This has an additional advantage of following Single Responsibility Principle. Let me give an example of Calculate_Transaction_Amount function.

Initial requirement-

float Calculate_Transaction_Amount( company, numberToBuy)
{
return company.Price * numberToBuy;
}

Later on, there might be requirement to add transaction tax and brokerage charges to it. In this case, only this method needs to change. Even here, we can further sub-divide the logic into individual functions -

float Calculate_Transaction_Amount( company, numberToBuy)
{
float basePrice = company.Price * numberToBuy;
float transactionTax  = Calculate_Transaction_Tax(basePrice);
float brokerageFees – Calculate_brokerage(basePrice);
return basePrice + transactionTax + brokerageFees;
}

What do you think? Do you have nay other tricks to make the code more readable?

 

Leave a Comment

Filed under Agile, Agile - technical practices, Concepts

Are we looking for wrong skills?

I believe that most software companies in India have a flawed interview process. Candidates who are looking for a job change have to first prepare for an interview. Mostly, it involves brushing up on concepts related to the platform, framework or syntax.

Can existing employees of these companies pass the interview process without preparation? If not, how are they managing to do their work properly?

I believe most people will not be able to clear their own company’s interview process and yet could be earning praises for their work in the company.This is because, there is a fundamental disconnect between what is required to do a job and what is being tested during the interview process. Answers to most of the questions asked during an interview can be found by using a nice little tool called “google”. However, the actual issues and problems faced by developers in their regular work are so unique that most of them do not yield results with just a simple search on the internet.

I believe, we need to test a developer for the following qualities -

  • Problem Solving
  • Ability to write logical code
  • Ability to write readable code
  • Ability to debug or fix code
  • Ability to apply theoretical concepts when faced with actual problems.

I would design an interview process with the following steps -

  • A couple of aptitude questions.

Purpose – Does the candidate have the talent to solve problems? You cannot teach someone to solve problems. Hence it is a critical to check this. You cannot google the solutions to unique problems that come up while coding.

  • Give a small problem and ask the candidate to write code to solve it

Purpose -  Can the candidate write code? Can he/she solve problems through a programming language? Can the candidate write code in such a manner that you can understand it by reading it? In the recent Agile conference, one of the speakers asked an important question.What do developers do all day?

Most of us assume the answer is “write code”. I have always believed, writing code is just 50% of the time, rest of the time is spent debugging. The speaker gave me an even more surprising  answer. Developers spend most of the time “reading code written by others.” Hence, it is critical that the candidate writes neat, readable code.

  • Provide a running program which fails a couple of test cases. Ask the developer to fix the code

Purpose -  Can the candidate read and understand someone else’s code? Can the candidate debug and fix the code?

  • If candidate has some experience, then a couple of design questions that require him to apply simple concepts.

Purpose - Everyone answers questions like “What is interface and why is its use?”. However, when you provide a problem that requires the use of interface for an elegant solution many candidates fail.

A person who attends this interview will either clear or fail. No amount of preparation would help. A developer is either good or bad. A little preparation on certain concepts will not make a developer good. So, the above process is more in touch with the skills and talents required in real world.

Of course, I would throw in a couple of theoretical questions regarding scrum and agile :-)

What do you think of this process? Do you think it would help get better candidates?

Leave a Comment

Filed under Concepts, My thoughts on Business & Stuff

Can you rewrite software incrementally?

Recently, I was dragged into a discussion about agile way of redesigning or rewriting a product. One side believed that a complete redesign should also occur incrementally and hence all existing features should continue to work every sprint. The other side believed that a complete redesign cannot occur incrementally.

The people who argue against incremental redesign often give analogy of real building construction. It would be impossible to add 10 floors to an existing building. The existing building has to be torn down, foundation strengthened and then the extra 10 floors can be built.

I believe that most of the redesigns can be done incrementally and that the argument of a building is a case of bad analogy.  People assumed the analogy all these years and came up with layered, waterfall method of development. You can’t build the first floor without building the ground floor! In construction, there is usually only one right way of building things.

However In software, you can either build in layers(waterfall) or build thin slices of each layer to provide a functionality. This is equivalent to building complete kitchen before starting on the bedroom. We all know that construction of a building does not occur this way. Having this bad analogy of constructing a building has led to other evils in software world. One of the evils is that of an architect who does not code. After all, in construction business, architects do not lay bricks.Anyway, I intend to write a separate post about Ivory tower architects later, but in the mean time think about how an architect starts his career. In software world, a developer becomes a tech lead or an architect as he gains experience. In construction business, a daily wage worker cannot ever dream of becoming an architect.

Another area where construction differs is that a successful project means the initial requirements and the final product match. In case of  software, a successful project will definitely get requirement changes to improve the final product. Hence, construction business is built to follow a plan while software should be built to adapt to changing requirements.

Read more about this fundamentally flawed analogy in Martin Fowler’s article - http://martinfowler.com/articles/newMethodology.html#SeparationOfDesignAndConstruction

Coming back to the topic, I am sure there are cases where the original code is so bad that it is better to thrash it and rewrite the entire thing. Barring these rare cases, where rewrite is cheaper,it is possible to redesign the code without breaking existing functionality in all cases. Let me take up a few examples to show this -

  • Underlying Database changing to support new functionality.

In this case, the ideal design is to follow the Open-Close principle. That is, try not to change the existing table, but add another table to support additional functionality. Add a mapping table if you require a binding between the original data and new data. The old code will read just the first table and continue to work the earlier way. You can then change the code to read the new data.

  • Underlying table to change drastically to fix a bug

An example of this case is that a data type chosen earlier is wrong. In this case, the layered architecture helps. Only the data access layer should be aware of the actual schema of the database. This schema should be abstracted in terms of models for other layers to use.  Suppose the data type issue was present even in the models. The first iteration of redesign should address only the DB and the DAL( Data Access layer). The code that converts from DB schema to the model should take care of converting values from new DB type to old model type.The second iteration of redesign should then take care of changing the model and all the layers to make use of the new data type of the model.

What if there was no proper DAL? What is multiple code pieces accesses the DB directly? In this case, the existing functionality would break when you change the DB schema. In this case, the first iteration would be to re-factor code to use a single piece of code to access this affected table. That is ,Create a DAL layer. Further iterations would then change the DB schema and models that are used.

  • Underlying table needs to be split into multiple tables

In this situation, a particular attribute of an entity would have to be enhanced to have multiple properties. So, a single column of an existing entity would expand to a table of its own.The first iteration should take just the column and then create a new table just for the column. The DAL layer will change to get data from 2 tables instead of one. The rest of the code need not change. In the second iteration more columns can be added to support enhanced functionality.

Can you think of any scenarios where you feel incremental rewrite is not possible? Let me know!

 

Leave a Comment

Filed under Agile, Agile - technical practices, Concepts

Is having a dedicated Scrum Master Anti-Agile?

Most companies that move from traditional ways of working to Agile face a lot of issues. Some of them are people related,others are process related and most of them are culture related issues. The tendency of these organizations is to blame the Agile ways of working for the issues. However, Agilists say that Agile just brings out issues that were existing earlier but hidden. The Agile development process forces the teams to come up with working software every 2/3/4 weeks and any hidden issues are uncovered.

I completely agree with the Agilists point of view. Agile helps brings out deep-rooted issues within the company’s processes,people and culture out in the open.

However, the idea of a dedicated Scrum Master is bothering me. A part of the Scrum Master’s role is to make sure that the team follows Scrum as it is meant to be. That is, the team follows the principles behind the practices and not just practices. That is fine. Would that work need a full-time scrum master? No. So, an add-on responsibility for Scrum Master is to remove impediments for the team. This is bothering me.

Many large companies have large, out-dated processes that cause impediments for delivering working software every sprint. However, by advocating having a dedicated Scrum Master, the Agilists are making the mistake of burying /managing  the real problem.

I believe a true Agile organization would desist from having a dedicated Scrum Master. Any impediments that come up would be raised to the management and it is the responsibility of management to make sure that particular impediment is removed. Not only removed, eliminated permanently. Frequently, this means consulting across various departments to ensure the processes are changed to enable the development teams to work efficiently.

If your organization is having so many impediments that it needs a full-time scrum master, then there are deep-rooted problems in the processes or culture of the company. These issues are coming out in the open for management to resolve. Instead, Scrum has taken the easy route of managing the underlying problem by having a dedicated Scrum Master.

So,my prescription is – management to remove impediments permanently(Change processes,culture etc.) and part-time scrum masters who can help in development( includes testing ).

 

1 Comment

Filed under Agile, My thoughts on Business & Stuff

What is wrong with the Australian cricket team?

Couple of days ago, it was announced that 4 players are sacked and would not be considered for the 3rd test against India. The reason given was that they did not complete an assignment given by the coach. At the surface, it looks like a discipline problem and the strong message sent by Clarke and the coach would fix it.

However, I have different opinion on what might have happened in the team. My opinions are based on 5 Dysfunctions of a Team written by Patrick Lencioni. I had earlier written about it in the context of an agile team - http://bigfatbooksinapage.com/2012/05/20/managing-agile-team-dynamics/

 

I will repeat the dysfunctions briefly here -

  • Lack Results
  • Lack of Accountability
  • Lack of Commitment
  • Fear of Conflict
  • Lack of Trust

Everyone easily notices the lack of results. In case of Australian team, the drubbing they received from a weak( my opinion) Indian team triggered action from coach.

The coach asked the team to take time off and come up with a presentation on how the team can do better. Four members of the team decided not to work on their powerpoint skills and were sacked. Now, the reason given from management is that they were sacked for indiscipline. That, it is not one instance. That,there are many instance of team members not filling up a daily health form and these particular 4 members were just unlucky that their indiscipline broke the management’s patience.

Why did the team members choose not to create a presentation? Were they committed to the idea? Did they feel it was a waste of time?If they felt it was a waste of time, why didn’t they speak up during the team meetings? Did they fear conflict? What made them feel that they could not express their opinions openly?

My thought is that the answer lies in the second process that has come to light. The process of filling up a daily “health” form? I can’t think of a single good reason why I would have to fill up a form daily? What can change everyday?

I am sure several members were fed up of this process.

But, why did the management come up with process in the first place? I believe, there must have been a single instance when a player did not inform the management about his injury and led to disaster in one Test(Maybe Ashes?!? Someone can research and let me know). The management lost trust in the team. Instead of reprimanding that one player, the management thought about bringing in a process that would eliminate the possibility.

The team members must have brought it up in a meeting and aggressively overruled by the management. This would have made the team hold back their opinions. One thing led to another and finally, management got fed up of the perceived indiscipline.

A good team would have intense team meetings were all things could be discussed. A team where  daily “health” form would be unnecessary since everyone is confident that if a player is not feeling well, he would walk up to the coach/therapist and inform them of the niggles. A team where presentation would be unnecessary as each person knows that his opinions would be valued in a team meeting. A good 2-3 hour meeting where everyone expresses their opinion would have been great.

So, my conclusion is that the team will not do well unless some of the management is changed. Somehow, the they need to work on developing trust and removing these unnecessary processes.

What do you think?

2 Comments

Filed under Business book summary, Management Book Summary