Showing posts with label code quality. Show all posts
Showing posts with label code quality. Show all posts

Thursday, July 16, 2015

Naming Conventions

A consistent naming convention is a key player in OOP (Object Oriented Programming) but it can certainly be extended to other paradigms.

Names serve the purpose of identifying elements.
Choose the wrong name and you will not identify a piece of code correctly, this costs time and money.

This is a simple guide to help you avoid this problem and get your code's quality  a step higher.




Characteristics of good code naming:
  • Tells what it actually does or contains.
  • Understandable with little contextual information.
  • Consistent all over the application.
  • Simple

Nameable elements classification:
  • Physical
    • Folders and Files
  • Logical
    • Classes, Methods
    • Configuration, Documentation *
* Format and characteristics my change depending on the technologies used.

My posts on Good Code are an introduction to a triad of concepts: Simple, Consistent and Readable code. Reading them takes a couple of minutes and will help you make the most this topic.

Physical elements

Physical elements are place holders for groups of elements or functionality.

I recommend using plural for directory or folder names.
For instance:


  • The MVCApplication only contains files and folders related to the application.
  • The Controllers folder contains only controller classes
  • The Models folder contains only model classes
  • The Views folder contains only view classes or files.
  • The Views folder has a subdivision based on functionality, but still contains only views

Logical Elements

Classes
Model only one object at a time therefore the name should be a noun or a noun phrase.
For instance: Car or CarPage

Use the prefix "I" for interfaces. For instance: ICar or ICarPage

Try to avoid generic words like Manager, Processor, Data or Info

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

Building good method names

Never use one of the above alone. Always combine them.

Verb + Adjective + Noun + Structure


Verbs
Save, delete, notify, update, or generate, etc.
Sometimes you could use "process" but only for queues or other things of this nature.
Verbs that are clear on the meaning according to the context are also ok.
Adjective
Find a balance between the number of parameters and the adjectives in the name.
Try not to use more than 3 parameters.
Noun
The class or object being interacted with.
Structure: (optional)
Unique to the situation.

Example:

  • GetGreenFruits()
  • GetRedFruitsArray()
  • GetFruitsList(Color desiredFruitsColor)
  • GetFruits(DesiredFruitsClass desiredFruits)



Contextual Vs Technical naming



Usually good code is composed of other simpler pieces.

If these simpler pieces are not technical, then choose a contextual name.

Look at the elements inside this code element.
Is it context heavy or is it tech heavy?

        private static void ValidateCompression(string input)
        {
            HuffmanTree huffmanTree = new HuffmanTree();
            BitArray encoded = huffmanTree.Encode(input);
            string decoded = huffmanTree.Decode(encoded);
            PrintValidationResults(input, encoded, decoded);
            Console.WriteLine("Valid compression: " + input.Equals(decoded));
        }
        //It is context heavy!
Is it context heavy or is it tech heavy?

         private List CreateNodesList(Dictionary frequencies)
         {
            List nodesList = new List();
            foreach (KeyValuePair symbol in frequencies)
            {
                nodesList.Add(new Node() { Symbol = symbol.Key, Frequency = symbol.Value });
            }
            return nodesList;
        }
        //It is tech heavy!




Apply good naming on all languages for all the pieces that compose your code, from documents to variables and methods.

You can use it as a tool to discover code that needs simplification:


  • If a method name has two verbs you need to split that method
  • If the class has two strong nouns you need to split that class.
  • If the directory has a generic name brake into several folders.
  • And so on.



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.





Thursday, April 30, 2015

What is good code?

Regardless of your reasons to be writing code, you should be writing good code that does what it has to do and does it well.

This is an introduction to a series of articles about how to improve code quality.

Code is a kind of text used to model objects and processes and it is usually written and edited by humans.

What are the characteristics of good code? How to write good code? What does it mean to write “good code”?

I will define good code in three layman's terms:

Good code is Simple, Consistent and Readable

Simple - Consistent - Readable
No acronyms
These three terms are your principles.
Develop each of them all the time.


This post is not about the best algorithm or the best pattern for the situation, is about good practices that will help you write good code regardless of the programming language or problem domain.

Simple Code:

Simplicity: The quality of being easy to understand or use. The state or quality of being plain or not fancy or complicated. Something that is simple or ordinary but enjoyable"
Merriam-Webster Dictionary

How to achieve simplicity?

  • Find pride in a simple solution to a complex problem not the opposite.
  • Ask questions, don't read minds.
  • Do only what you need to do things well.

How to write simple code?

  • Get a good enough understanding of what you need to accomplish and how to validate the results.
  • Divide your code into simpler parts.
  • Be consistent.
  • Make it readable.
  • Repeat as needed. (Iterate)

Simplification has a positive impact on:

  • Architecture
  • Identification of needs and responsibilities.
  • Project structure.
  • Time/Cost estimation.
  • Code test-ability.
  • Consistency.
  • Readability.

Keep it simple!

Consistent Code:

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

How to achieve consistency?

  • Do things the same way all the time.
  • Have a good and clear reason to do what you do.
  • Keep it simple.

How to write consistent code?

  • Get familiar with common industry patterns and use them.
  • Choose a simple coding standard and follow it.
  • Avoid synonyms. If you choose the word "human" over the word "person", use human always.
  • Favor processes that can be repeated all the time.
  • Test and Unit Test your code.

Consistency has a positive impact on:

  • Good, sustainable development pace.
  • Effective interaction between people and systems.
  • Easier code changes.
  • Simplicity.
  • Readability.

Be consistent!

Readable Code:

The quality of written language that makes it easy to read and understand."
TheFreeDictionary.com

Code is text, technical text, and someone will need to maintain it.
This is really important do not underestimate it.

How to achieve readability?

  • Choose the right words to convey your ideas.
  • Develop one idea at a time.
  • Use correct syntax and grammar.
  • Keep it simple.
  • Be consistent.

How to write readable code?

Apply the principles of simplicity and consistency.

Lets focus on five basic ideas:
  • Verbs mean actions, 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, use them for 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"

Readability has a positive impact on:

  • Maintenance
  • Collaboration
  • Simplicity
  • Consistency.

Make it readable!

Final notes

Good code is the result of applying a set of good practices that help you achieve simplicity, consistency and readability.

Each one of this principles builds on the other and together become a powerful tool that you can use to improve your code which in turn will save you time and money.

Writing good code is an art, it takes time and dedication, but start now, you wont regret it.
Start writing good code.

The best time to plant a tree was always 20 years ago.
The second best time is always today."
Chinese proverb