Don’t be anti-negative

The negative conditionals in code blocks are most of the time difficult to read and understand.

It becomes worse when you make the conditionals anti-negative.

Before

Anti-negative conditionals

Try to read above code snippets and try to understand it. Please note the highlighted parts. Does that code reads like

  • When inverse of a package is not damaged then report an error: “Package is damaged”.
  • When inverse of a package is not empty then report another error:
    “Package is empty”

Ouch! Unreadable? Complex? Painful, isn’t it? Let’s revisit the same condition with positive conditionals.

After

Positive conditionals

Another example:

Before:

Set hours logged when it is not NonWorkingDay. What?

Above snippet is showing hours worked for the day if it’s not non-working day!

After

Set hours logged when it was working day.

Now, this reads like simple statement. Show hours worked for working day.


Extract Method

Extract method is the most frequently used refactoring technique. It reorganizes the code for better reuse and readability.

Ah! alright. Let’s proceed.

Use the extract method in following cases —

When your class contains a long method.

A long method does more than one thing and it is not considered as cohesive. The method more than 10 lines could be considered the as long method.

See this example of a long method, It is doing more than one thing.

Setting up GST rates, item/category mapping, accepting user inputs, calculation and so on. 

A long method is considered a code smell. 

Now see the refactored version of the above long method.

It is divided into small, cohesive, fine-grained methods which are doing one and only one thing.


When you favor a comment to express the intent of the code.

Before

 ...
// Parse input and convert it into Document
var xDocument = XDocument.Parse(input);
var document = new Document
{
   Title = xDocument.Root.Element("title").Value,
   Text = xDocument.Root.Element("text").Value
};
...

Here let’s get rid of comment [Parse input and convert it into Document]. 

After

...
var doc = ParseInput(input);
var serializedDoc = JsonConvert.SerializeObject(doc);
...
private Document ParseInput(string input)
{
    var xDocument = XDocument.Parse(input);
    var document = new Document
    {
        Title = xDocument.Root.Element("title").Value,
        Text = xDocument.Root.Element("text").Value
    };
    return document;
}

When the extract method helps you to improve readability.

Do you know that people extract method for a single line too? Because it adds to the readability of the code. Sometimes a statement may be difficult to interpret. In that case, you could use the extract method to convey intent instead of taking the aid of comment.


When there is a code duplication or copy-paste.

Consider below example, it is formatting date and code is duplicated. Perhaps, lines are copied and pasted.

Before

    var formattedStartDate = startDate.ToString("dd MMMM yyyy");
    var formattedEndDate   = endDate.ToString("dd MMMM yyyy");

As soon as you see copy and paste of lines of code then go for an extract method refactoring even if it is a small portion of code.

After

    var formattedStartDate = FormatDate(startDate);
    var formattedEndDate  = FormatDate(endDate);

public string FormatDate(DateTime date)
{
   return date.ToString("dd MMMM yyyy");
}

The advantage

  • Code becomes more readable.
  • Fine-grained methods make code easier to understand.
  • You can easily plug-in and plug out the implementation for some routines.
  • When your method becomes cohesive, you can easily spot the bugs in the code.
  • Your calling method reads more like a sentence.

Points to Ponder —

  • Remember, keep the method short, well-named, and cohesive to get more benefits out of it.
  • Your calling method should read more like sentences.
  • When extracting a method, a developer should think about the cohesiveness of the class. should ask a question to oneself: Does the extracted method really belong to this class? If Not, then move it to the appropriate class that should perform that operation.
  • Small methods really work only when you have good names.
  • Don’t just extract method if you can’t give the meaningful name.

Extract method only if you can give an intuitive name.

Authentication and authorization

 

Authentication:

I don’t know who you are, so, you are not allowed to enter the premises.

Authorization:

I know who you are, you are allowed to enter the premises. However, you do not belong to the accounting department hence you are not allowed to perform any action like accessing resources in this section of the premises.

Authorization is all about what you can do.

 

When you work with any web technologies, be it server-side UI generation or serving API. They always provide you interceptors (The components who intercept the HTTP request) to perform these checks.

These interceptors may be called as HttpModules, Middleware and so on.

In ASP.NET, we could achieve it using pluggable HTTP modules or C# attributes, and so on.

In ASP.NET MVC or WebAPI, we could authenticate or authorize request using Authentication and Authorization filters at the controller action level, controller level or at the global level.

 

Don’t forget to return below HTTP status code from web API if a request fails to authenticate or authorize.

401 UNAUTHORIZED

Don’t confuse with unauthorized. It says valid authentication credentials for the target resource are missing, Authentication failed.

403 FORBIDDEN

It means the server understood the request but refuses to authorize it.

Developer Professionalism : Take a stand

Few weeks ago, I was travelling to my hometown by a bus. I reached the pick-up point at scheduled time, but when I arrived, I found that the bus was late.

Finally after a wait of 2 hours, the bus arrived and the driver found himself in the middle of many angry passengers who were also waiting for the bus. After a while, I patiently asked the driver, “What was the problem?”. To which he replied, “The bus is having problems since last 4-5 days. I told the management that we need at-least 2-3 days to fix the bus, but they are not ready to listen. They are insisting to run the bus by doing a quick-fix for the time being.” I again asked him, ” Are you sure it won’t fail again?”. He replied, “We’re not sure, let’s pray that the bus does not fail.”

It was an overnight journey, I started thinking, why is the crew taking such a risk of using a bus they are not confident of. There were kids, old people on that bus. What-if it fails in middle of nowhere?

How many of us have encountered such a situation before in our own professional lives?

Have you ever been asked to ship a low quality quick fix, so that the software can be shipped into production quickly?

Have you ever been pressurized to develop a piece of code in short time, thereby giving you less time and opportunity to produce a good work?

I have been in such situations too and to be honest, I’ve even done that. I’ve succumbed to pressures. But is that the right thing to do?

People from these professions, such as doctors, construction engineers have an obligation towards the society and that obligation is to protect human lives first.

Software these days, is no different. Software is everywhere. It’s being used to suggest what medication a patient should get, it’s driving cars for you, it’s even bringing you from top floor to the ground floor of the building you live in. It’s omnipresent.

And the onus to ensure that it works as expected, is on us. People have lost lives, due to bugs in software, it’s as real as it gets. Developers these days, are now being held accountable for the work they produce.

So if you are not sure, if you’re code will as expected, if you are not sure, you’ve covered all edge cases, if you are not sure that the quality is up-to the mark, learn to say NO, take a stand. (But remember, when you do so, do it with a proper justification too.)

Don’t be too clever

A few days ago, I along with my friend went to the restaurant. When I went to use a washroom, I found these symbols on the doors.

I realized the humor of the designer and then I went to the Male washroom. However, I observed that other people who don’t understand the humor, having difficulty to understand the correct washroom. They had to ask staff for help. Hmm! That’s not that user-friendly.

Similarly, people try to be too clever while writing the code.

Please see the above code snippet. Do you understand the intent of BombDetector.Detect? Original author must have tried to use his humor while writing the code.

However, the maintenance developer may not understand the humor behind it and he would feel helpless to understand the intent.

The original author was checking the value of the input argument and throwing the exception if a value of an argument is null.

Above snippet could have been kept simple.

Try to keep your code as simple as possible so that everyone could easily understand it and easily work with it.


Image source: https://quotefancy.com/quote/1469345/Billy-Wilder-Don-t-be-too-clever-for-an-audience-Make-it-obvious-Make-the-subtleties
https://blog.beingcraftsman.com/datta/

Start slowly to finish fast

“In programming, the hard part isn’t solving problems, but deciding what problems to solve.” – Paul Graham

I am fortunate enough to work with new, genius, competitive developers who have fresh perspectives. They often talk about faster algorithms, data structures, new-generation technologies, and buzzwords in the software industries. They are eager, motivated and wanted to change the world!

However, I did not hear from them about problem-solving using object-oriented analysis and design.

Some people try to solve the problem by directly jumping into programming solution without doing an analysis. They believe in trial and error methods. It’s like solving problems without knowing what problems to solve.

The well-proven OOAD techniques are there for decades, It’s a very beneficial technique for problem-solving. They will help you to know what problems to solve.

We should focus on what problems to solve rather than just writing the code.

IMO, we should start slowly to finish fast. What I mean here is, we have a problem at hand, divide it into three parts: Analysis, Design, and Programming.

These three are related terms.

The object-oriented analysis is meant for understanding the customer problem. Write use cases to capture what is needed and what is not. You can write lightweight use cases. Thus, you’ll focus on what is needed than trial and errors.

Benefits of writing use cases!

The next step would be the object-oriented design which emphasizes on designing the conceptual models i.e. classes to achieve the various use cases.

This classes will have attributes and behaviors. They interact with each other to solve the problem.

Try using outside in approach, class diagrams, sequence diagrams. You could use the whiteboard to evolve your conceptual design that tries to solve the customer problem.

Object-oriented thinking, the big picture!

Then comes the programming phase. Now you know “what part” of the problem and conceptual models, you can focus on how part i.e. coding.

The good analysis and design would help you to understand problems to solve, prepare good conceptual models, that intern leads you to good programming solution for the problem at hand.

Remember, don’t directly start coding without understanding the problem to solve.

Instead, use object-oriented analysis and design.

Start slowly to finish fast.

Start practicing Shoshin

When you were a child and wanted to learn something for the first time. You chose to learn it from others with an open mind. Take an example of painting the picture. You could experience this when your kids try to mimic you while learning something the first time.

(My daughter Shruti tried to paint the butterfly. She was eager and tried to accept every information with an open mind)

When you acquire knowledge about something your mind becomes more closed. Over the period of time, you become reluctant to accept more information.

I hope you had experienced this at least once. When you try to give suggestion to improve processes like stand-ups, grooming, retrospective or some other agile process, the senior person would refuse to change since he/she thinks that he/she knows everything.

He/she choose to kill your suggestion with her/his closed mind! EGO?

I was introduced to this term by my agile coach when I was working with Tieto education Pune.  Initially, I was not very convinced or sure about it, preconceptions!

(Image: http://kungfupanda.wikia.com/wiki/File:Mantis-Po-acupuncture.png)

However, over the period of time, I saw good behavioral changes in me and my scrum team.

Shoshin clearly encourages good behaviors in you and your team. See below description from Wikipedia.

“If your mind is empty, it is always ready for anything, it is open to everything. In the beginner’s mind there are many possibilities, but in the expert’s mind, there are few. ” ― Shunryu Suzuki

I started attending various agile and software craftsman ceremonies with an open mind like study circles, knowledge sharing sessions, refinements, the storytelling of epic work items and so on. It really helped me and my team to grow as a scrum team.

Believe me, if you choose to practice below-mentioned attitude (SHOSHIN), it will really help you in the long run.

  • Openness

  • Eagerness
  • Lack of preconceptions.

I would highly recommend practicing Shoshin mindset in your team. Even you could include it in your way of working.

(Image: https://www.deviantart.com/keysamoguri/art/Inner-peace-301041283)

See what James Clear says about SHOSHIN: https://jamesclear.com/shoshin.

https://blog.beingcraftsman.com/datta/

Agile Economics : How decisions impact cost?

Cost is one of the important corners of the Project-management triangle. This factor is especially important for decision-making from business perspective.

Let’s look at one of the techniques that will help us take more informed decisions about various operations we as developers do.

Consider a scenario when we have to automate the deployments in your project. One natural approach these days, is to automate everything. But let’s take a closer look at the things more closely.

Let’s put some numbers on a graph. On the X-axis we have the percentage of automation done in the project and on the Y-axis we have the cost needed to automate it.

Let’s put one more graph on it, that of “doing things manually”, indicated by green curve.

As it turns out, the cost of doing everything manually is too high. It would require a step-by-step manual intervention many personnel (typically Devops). So if we have 0% automation in our project, the cost of doing everything manually is quite high.

On the other hand, the cost of automating everything, every single step is also high, since doing this will take a considerable amount of time and effort for developing it. (indicated by orange curve)

However, if everything is automated, the cost of doing deployments manually tends to be zero, we can deduce this by comparing the curves.

Now let’s do something interesting. If we add the values of these 2 graphs, at every single point, we would get a curve of something like this (indicated by dotted red curve)

This red U-shaped dotted curve, indicates the total cost if the deployments are done in combination (manual and automation). As you can see the cost tends to be minimum at Point(X,Y).

We can therefore infer that you should:- “Automate X parts of the system by investing Y amount in it“.

Why is this statement important?

Simple, cost. You don’t want to overspend on one particular aspect of the project. Instead prioritize things, (which in this case is X %) and automate them first. And then if you have time, money and will, go for the remaining (100-X)%.

Find your minimum dropping point. It could be way off on either sides. But having a rough idea of where you stand, can help you optimize your business.

Please note the above curves are approximations for explanatory purposes, the actual values may vary, scenario-to-scenario, team-to-team…..

This technique can be used in many other decision-making processes, such as “How much code coverage should we have?”, “How good product quality we want?” and so on…..

The most important part in this thought process is “Prioritization”. Do not plan big upfront. Instead, go step by step. Look where you stand after regular intervals and then do course corrections accordingly. After all, that’s what “Being Agile” means….

Don’t add unnecessary context

This is about a class, which has fields and methods whose name repeats the class name.

Please see the below class diagram for a student.

Looking at the class diagram, it’s clear that this whole class is all about the student. However, do you think repetitively adding the word “Student” in fields and methods really adds value?

Don’t you think it’s redundant?

It reads more like

  • The student has a student name.
  • The student has student birthdate.
  • Get student age of a student. It reads like a weird sentence, isn’t it?

We already have the student context, hence adding words repeatedly is redundant.

Let me show you the revised class diagram.

This one removes the redundancy. 

It reads more like

  • The student has a name.
  • The student has a birthdate.
  • Get the age of a student.

You may come across such redundancy when working with code. Identify it and remove it.

Next time, “Don’t just add unnecessary context”!

Another example:

Student repository

Don’t repeat the name of the class in class’ fields and methods.

Just don’t be mute pair programmer

The motivation behind this post was, I saw few developers who do full time or part time pairing with their peers and driving the process, choose to be mute for the whole time. Of course, this is an anti-pattern.

If you choose to be mute rockstar coder then it wouldn’t help anyone neither you nor your team.

If you see food shows on TV, you’ll observe that there will be two people working together (I used the word working TOGETHER).

You know there will be one chef who knows how to prepare the dish and other chef doesn’t know about it.

They talk with each other about the recipe, ingredients, do’s and don’t, what, how and why and so on so that the other chef gets the knowledge. Next time, the other chef could easily prepare the dish. During this process, the first chef would know few tips from another one.

You see the secret of their success is they talk with each other about the problem at hand.

The same thing is applicable to developers who work in a pair for full time or part-time.

As a developer, our peer may be facing some problem and when he/she comes to you, you should do the same thing as these chefs choose to do, just don’t be mute, talk, work together!

You should talk about the problem at hand, why, what, how and so on. There is a possibility that as a driver of the process, you would learn something new from another developer.

Even one of four values of agile and software craftsmanship emphasize on individuals and interactions. Please see below.

From agile manifesto

 

From manifesto for software craftsmanship,

https://blog.beingcraftsman.com/datta/