Friday, May 29, 2015

Simple Code

Despite the complexity of the situation, software should aim to provide a simple solution.
It may sound very simplistic but simplification is the most important skill required for problem solving.


Simple code has all or some of the following characteristics:

  • Does what it has to do and does it well.
  • Does what it has to do in a short number of steps.
  • Files and folders are well organized. (See my post on Consistent Code)
  • Classes represent only one thing.
  • Methods do only one thing.
  • It is readable.
  • It is consistent.

If you have not read my introduction to good code: "What is good code?", please do it. It will take you just a couple of minutes and will give you the context to follow this post.

How to simplify your code?

Usually software is compared to a tool, like a hammer or a screwdriver but software is also like a machine, composed of multiple moving parts and able to perform actions without human interaction.

Given this machine like behavior, we need to simplify our software objects and actions.



In general you could follow two different paths to simplify you code:

  • Top Down
  • Bottom Up

Sometimes, doing architectural changes, implementing new patterns and functionality into your code is the best way to go, but this is expensive and if you don't have unit tests it can be really risky.

Sometimes, what you need is to make the code more manageable and testable with a reduced amount of cost and little risk, ones you have done this, then you can think of something more complex.

Top down code simplification:

Complex objects are composed of simpler objects for instance a skate board:
  • Deck
  • Grip Tape
  • Trucks
  • Wheels
  • Bearings
  • Mounting Hardware


Actions are composed of simpler actions, for instance shaking hands:
  • Walk close to the other person.
  • Look at the other persons face to validate their identity.
  • Look at the other persons hand to validate height and position of the hand.
  • Get hand in front of the other persons hand.
  • Get your palm in contact with the other persons palm and wrap your fingers around the other hand.
  • Shake your hand.
  • Let go of the other hand.

In "Top Down Simplification" you are working with existing code not creating something from scratch, the goal is not to rebuild the system but to make it simpler, more manageable, more testable, better.


..it happens in all human affairs that we never seek to escape one mischief without falling into another. Prudence therefore consists in knowing how to distinguish degrees of disadvantage, and in accepting a less evil as a good.”
Niccolò Machiavelli, The Prince

Bottom up code simplification:

Bottom up is what you use when you are building a new piece of code. It requires a constant refactoring process.

The idea is very simple:

If a piece of code can be named then it deserves its own place.

Here you have a very simplistic example:  Shake Hands >>> Let go of other hand:

"Let go of the other hand"
  • Stretch thumb
  • Stretch index finger
  • Stretch middle finger
  • Stretch ring finger
  • Stretch pinky
  • Move hand against the direction of the palm
  • Move arm to the side of the your body
  • Stretch elbow
  • Relax muscles on the arm
  • Relax muscles int he hand

Could be turned into several methods:


Let go of the other hand
  • Open hand
  • Move arm to the side
  • Relax arm
                         Open hand
  • Stretch thumb
  • Stretch index finger
  • Stretch middle finger
  • Stretch ring finger
  • Stretch pinky
Move arm to the side
  • Move hand against the direction of the palm
  • Move arm to the side of the your body
  • Stretch elbow
Relax arm
  • Relax muscles on the arm
  • Relax muscles int he hand


Which is simpler to read and understand and more testable since you can validate the outcome of every method separately.


A scientific theory should be as simple as possible, but no simpler."
AlbertEinstein

The magic number 7:

An average person will not work well with more than around 7 plus or minus 2 items at the same time.

You can find out more at "The Magical Number Seven, Plus or Minus Two Some Limits on Our Capacity for Processing Information" by George A. Miller. (Harvard University)


The magic number 7 in code simplification:

Some people say that methods should have at most 5 lines of code. This is too idealistic therefore extreme and unrealistic.

I think that 7 actions (not lines of code) present a better measure.

Split the methods in three sections:
  • Input validation (counts as 1 action even if it has several lines)
  • Body (5 actions is excellent, 7 actions is good, more is too long)
  • Exception handling (counts as 1 action even if it has several lines)
The total will be 3 to 9 actions, 

This way an average person will not have a struggle to analyze your code.  



Simple does not mean easy, it takes practice, but the more you do it, the better you get at it.

It might never be perfect but it will be better then before, which is good.






Thursday, May 28, 2015

Consistent Code

The result of a process on which randomness is involved, cannot be predicted.

You want to be right all the time, consistently.

Ironically enough, you want to be consistent in the things that you do well and also in the thing that you are not so good at.

If there is something wrong in your process, you want it to be consistently wrong.

Consistent and predictable errors can be analyzed and corrected, random errors will always come back to haunt you.

Consistency: Steadfast adherence to the same principles, course, form, etc..Agreement, harmony, or compatibility, especially correspondence or uniformity among the parts of a complex thing.The condition of cohering or holding together and retaining form; solidity or firmness."
Dictionary.com

If you have not read my introduction to good code: "What is good code?", please do it. It will take you just a couple of minutes and will give you the context to follow this post.

How to write consistent code?


Get familiar with common industry patterns and use them.
Software patterns are a concrete and structured solutions to common problems in a given context.

If you are building a webpage you might use MVC (Model View Controller) or you could build and API for the server side functionality and MVVM (Model View View Model) or similar for the presentation.

It is not about the features or functionality or a particular framework, is about the naming conventions, files and directory structure, its about the mechanics and the flows of the application.


Choose a simple coding standard and follow it.
Code standards are conventions, agreements that you or people before you made to prevent that software is written with different styles and practices.

Not everybody writes code in the same way, but if they did, things will be easier to understand and to work with. This is why we like code standards.

Some of the leading companies in the software industry have made public their code standard, you could choose the one that you like the most or define your own.

Use a tool to enforce your code standard, I recommend checking out:
Resharper, CodeItRight, JustCode, CodeRush and StyleCop.


Avoid synonyms.
Novel writers try to choose synonyms all the time to avoid cacophony, but in software you want to use the same word all the time. If you choose the word "human" over the word "person", use human always.


Favor processes that can be repeated all the time by everyone.
One of the best examples I can think of is Continuous Integration.

Create an automation for each different part of your development process. For instance: Compile, Test, Package, Deploy.


Document your work.
I favor small simple documentation, automated if possible.

General project information:
Every project you start should have at least a Readme file, it should be in txt or MarkDown or similar, but it has to be a format that can be read without any special tool.

The Readme file should contain: Description of the project, prerequisites, how to compile, how to run, pointer to other important sources of information, Owner or contact information.

Code internal documentation:
Your code should be self documenting, which means that your code is very simplified (check my post on Simple Code), the names that you choose to name your parts are very descriptive and straight to the point (check my post on Readable Code).

If you decide to create internal documentation, keep it to the minimum.

Most of the large and popular development IDEs have automated ways to add comments by typing "///", "/**" or similar. For .Net I like using a tool called GhostDoc (I'm not getting payed to mention it) as it can be integrated in your build process to automatically create your internal code documentation.


Test and Unit Test your code.
If you can apply test driven development go for it, its worth the effort

Creating unit tests is a good way to discover problems with our code early in the game so even if you write them as you go or at the end of your coding they are still valuable.

Automated Unit Tests execution allows you to refactor the code with a "safety net" and helps you have a more predictable outcome.


Consistent directory naming.
First of all, follow your code standard if it already has rules about folder naming.

A folder or directory is like a bucket, a bag, a sack, its a container and is it meant to store files.
It is a good idea to take advantage of the name of the directory to indicate what kind of files it contains.
Directories should be named in plural, a directory that has only one file is a special case in the universe of directories, therefore in this case it can be ignored.

Controller classes should live in a Controllers folder, Exception classes should live in an Exceptions folder, Views should live in a Views folder and so on.

Final notes

In software development, it is of the highest importance to be predictable and consistent.

Consistency allows you improve, allows new team members to get on board faster and it is a most have for code that is meant to be supported.

An organization benefits more from a good and consistent development process and consistent code, than from a randomly awesome piece of software that is also randomly wrong..

Readable Code

Code is text, technical text, and you or someone else will need to maintain it.

Readable code goes beyond coding standards and visuals, readable means that a human can easily understand it.

An IDE or text editor will make a good job with visuals like fonts and colors, and a good code standard will align how code is written in a given language, and yet it is not enough to make your code readable.

Readability becomes critical when working on a team where every developer has different preferences and backgrounds.

If you have not read my introduction to good code: "What is good code?", please do it. It will take you just a couple of minutes and will give you the context to follow this post.

Legibility vs Readability (In the context of writing code):

Legibility:
Composed by two factors: "Visuals" and "Code Standards".
Visuals refer to the job of the computer and the editor in regards to fonts, screen resolution and the overall presentation of the code in the screen.
Code standards refer to spacing, brackets, tabs, case, new lines, etc.

Readability:
Is the human aspect of writing code. Refers to good practices on how to name methods, classes, folders and other elements supported by code standards.

Code Readability

You want code that looks almost like pseudo code.

Regardless of the programming language,  you have control of how you name files, folders, variables, methods, classes, procedures, etc. Use these elements as labels to produce readable and "self documenting code".

There should be one single common spoken language.

People all over the world may read your code. There is a high chance that the persons writing and reading a piece of code don't speak the same language.It makes sense to write code in English, even if it is not your first language (my first language is Spanish). It makes since because the most common programming languages use English words as part of its core components anyway. If your organization uses a language other then English use that one instead (you will have to adapt my tips to your language)

Unlike novels, code seeks beauty in consistency and simplicity.

How to write readable code?

Lets focus on five basic ideas:
  • Verbs mean actions or questions, used them for methods
  • Nouns represent items or things in general, use them for class names (in singular) or collections (in plural)
  • Adjectives and characteristics are variables or properties
  • States represent current boolean conditions. For instance an engine that is started, has a variable named "started" and a method called "IsStarted"
  • Capabilities are usually boolean conditions. For instance an engine that "can start", has a method called "CanStart"
Naming your classes:
Classes are a noun or a noun phrase, use singular. For instance: Car, BookPage
Avoid generic words like Manager, Processor, Data, or Info
Use the prefix “I” for interfaces.

Naming your methods:
Methods represent actions or questions.
Names should indicate what action is been performed or the question been asked.


Basic indicators of bad code naming:
You need to explain what it does by saying: "what I meant was", "it should have been named", "ooh this thing does…"
Rename it as what you meant, what it should have been named, what it does, etc…

You can't decide the name because the method does more than one thing
Simplify. Split it in several smaller classes or methods.

You can't decide the name folder because it contains files of different types
Simplify. Group files on separates folders, so there is one folder per file type

What vs How:

When writing or reviewing a method name, asking the following questions is very helpful.

"What does it do?"
  • The name of the method should answer this question.
  • There should be no need to read the internals of the method.
  • Should contain only one verb.
"How does it do it?":
  • The internals of the method should answer, not the name.
  • Should be a series of other readable elements.


The "Then" test:

This is a simple, consistent and powerful tool to validate that you have readable code.

They key is to read your code aloud as if it was prose.

Your code should be structured into several simple, consistent and readable methods.

Methods are composed of two kinds of elements:
  • Defined by the programmer. Read this ones as prose
  • Defined by the language (try, if, for, etc). Read the elements defined by the language in a functional way, for instance
    If: If MethodCall is true then


Test Steps
  1. Ask "What does it do"?
  2. Read the name of the method aloud. It should give you a clean answer.
  3. Ask "How does it do it"?
  4. Read the internals of the method one by one, saying "Then" between each one
  5. Repeat from 1 for every method
If you can read you code without much pause and it is understandable,then you have achieved your goal.

Final notes:


Readable code is much more than syntactic sugar, is not about colors and fonts.

It's about been able to express with clarity the purpose of your code.

Whether C#, Java,  ColdFusion,  Erlang, Javascript or any other language, your code has to be able to be readable, this principle can be applied to to every single language I've worked with, regardless of the patterns that you use, the version that you are running or the OS of your choice.

Readable code takes time and practice but is saves time / money in all stages of the life cycle of an application.