CLEAN CODE IN A NUTSHELL

What is clean code?  How do you write clean code?  I will attempt to address these questions in this “In a Nutshell” series blog post.

Clean Code In a Nutshell:

  • The crux of it is: Clean code is code that is written in a way that is easily understandable, readable and maintainable by other Humans.
  • Key aspects of clean code:
  1. It is DRY (does not repeat unnecessarily)
  2. Concise (but not too concise!)
  3. Tells a story to the reader in a logical sequence about what is happening in the code
  4. Incorporates the SRP principle and Separation of Concerns
  5. Is easily maintainable (modular) and does not make the person who is reading and working on it want to pull their hair out

That’s basically what it means to write clean code.  For further explanation and examples, continue reading…

Definitions:

  • Code Smell: This refers to code that is not clean and “smells”.  There is something about the code that is unnecessarily confusing, unclear or something that could be improved upon to make it cleaner.
  • DRY: The “Don’t Repeat Yourself” principle.  The goal is to eliminate as much repetition of code as possible and re-use as much code as possible, which keeps things less cluttered and clean.
  • SRP: The “Single Responsibility” principle.  A method, object or class should do one thing and do it very well.  This makes things easier to maintain and keeps things de-coupled.
  • Separation Of Concerns: Code should be logically grouped based on what operations it is performing or data it is related to.  Methods in classes and objects should be closely related to each other and separated.
  • Spaghetti Code: This is code that is not separated logically and is not modular.  It is very difficult to maintain and understand and is usually heavily coupled (the code is connected to and affects many other parts and operations in the application) so that changing one line may have unforeseen side effects on all sorts of other parts of the code base.  It is a nightmare to deal with and the opposite of clean code.

METHODS FOR WRITING CLEAN CODE (and what to avoid doing):

 

NAMING VARIABLES:

  • Names for variables should not be ambiguous, but be descriptive and meaningful.
  • Magic Numbers and Magic Strings: Strings or Numbers usually used as variable names which do not indicate to the reader of the code what their purpose, origin or use is related to.  Don’t do this.  Always make variable names descriptive and meaningful so it’s clear to the reader what they are for and doing.
  • Make naming formats consistent.  If related variables are in camel case, then make sure all of them are in camel case, or if there is a word that is appended or prepended to related variables, make sure you keep using that format.
  • Follow naming conventions in whatever language or framework you are using.  For example, in C# the names of classes, it’s properties and methods use Pascal Case while private fields, method parameters(arguments) and local variables use Camel Case.  In React, all component names and classes should have the first letter capitalized.
  • Try not to use names that are too long or hard to read.  Keep them short (but not too short).

Examples:

// Avoid: Ambiguous variable names:
const x = "Please log in.";
// Cleaner:
const loginMessage = "Please log in.";

// Avoid: Magic Numbers and Strings:
if (userStatus === 1) {
  return true;
}
// Cleaner:
const loggedIn = 1; 
if (userStatus === loggedIn) {
  return true;
}

// Avoid: inconsistent naming:
const username = "Brent";
const user_profile = false;
// Cleaner:
const userName = "Brent";
const userProfile = false;

// Avoid: really long and hard to read names:
const loginUserAndFetchDataFromDatabaseAndUpdateTheReduxStore =  () => { ...code );
};
// Cleaner: use the SRP and Separation of Concerns principles: 
const loginUser = () => { ...code };
const fetchUserData = () => { ...code };
const updateStore = () => { ...code };

METHODS, OBJECTS, CLASSES (SRP and Separation of Concerns):

  • Keep methods short and have them do only one thing!  Methods should do one thing and do it very well (have a single responsibility).  There are differing opinions on how long methods should be, but the goal is to make them as short and as contained as possible.  Some say they should not be more than 10 lines of code.   Just try to make them as short as possible without making the code hard to understand.
  • If methods get too long, look for ways to extract parts of the code to a separate object or function that you use inside the method.
  • Cohesion Principle: All code that is related closely should be together and code that is not should be separated.  Objects and classes should contain data and methods that relate to each other and only have to do with the data or operation that the object/class is concerned with (Separation of Concerns).
  • The Information Expert Principle (or similarly the Encapsulation principle) states that a method should be attached to the class or object that has the related data which it uses (similar to the Cohesion Principle).
  • The number of parameters should not exceed three.   You can extract parameters and batch them in objects or encapsulate them to reduce the number of arguments.  If possible, also avoid using booleans as parameters.
  • Variables should be declared as close as possible to where they are being used so the reader does not have to search around to find where they are defined.

Examples:

// Avoid: long methods and functions with too many parameters and doing more than one thing...
function fetchUserDataAndLoginUser(loggedIn, userId, db, userProfile, userPassword) {
  let userData = {};
  if (!user.loggedIn) {
     ... 
     lots of code to login user on the back end
     ...
     ...
     ...
     userData = db.find({ user: user.id });
     ... 
     lots of code to load userData into a profile view
     ...
     ...
  } else {
 window.location.replace("https://site.com/dashboard"
);
  }
}

// Cleaner (separate the operations into separate functions to use and combine the arguments into a single encapsulated object):

const user = {
   userId,
   userProfile,
   userPassword,
   loggedIn 
};

function authenticateUser(user) {
  ...code for checking passwords and authenticating the user.
}

function fetchUserData(userId, db) {
  ...code for fetching authenticated user data from the database
}

function renderUserData(userData) {
  ...code to render the userData on the view.
}

authenticateUser(user, db)
  .then(user => {
    fetchUserData(user.id, db);
  })
  .then(userData => {
    renderUserData(userData);
  });

// Note how the code now tells a story in a logical succession to the reader and each method only deals with one thing and part of the process separately.  The user is logged in and authenticated, then their data is fetched from the database, and then the data is rendered to the view.  
// The code is also easier to maintain because if there is a point of failure along the way, the developer can look in the appropriate method dealing with the failing operation and pinpoint and debug quickly and easily which step is failing.

CONDITIONALS (IF/ELSE STATEMENTS):

  • Keep conditional statements as flat and easy to understand as possible by using refactoring techniques and avoiding common pitfalls.
  • A Nested Conditional is an if/else statement contained within another if/else statement.  Avoid them: they are difficult to read, understand and test.
  • There are circumstances in which nested conditionals can be refactored by considering the relationship of the conditional parameters between the statements.  (See examples below).

Examples and ways of refactoring conditionals:

Use a Ternary Operator:

// Not nested, but easily refactored to make the code cleaner and more readable:
  if (user.id) {
    userLoggedIn = true;
  } else {
    userLoggedIn = false;
  }
// Cleaner:
userLoggedIn = user.id ? true : false;

// NOTE: Never combine ternary expressions and only use one - multiple ternary expressions are too difficult to understand and read.

If the statement sets a Boolean to a variable based on the condition, you can simplify it by setting the variable to the condition in a single line eliminating the if/else statement:

// Avoid: Unnecessary if/else statement:
if (userLoggedIn) {
  showProfile = true;
} else {
  showProfile = false;
}
// Cleaner: showProfile is simply dependent on the value in the condition...it can be refactored to:
showProfile = userLoggedIn; 

Watch out for nested if statements that a single block is based on. Use the && operator or early exit technique to refactor:

// Avoid: nested if statement inside a single block:
if (user) {
  if (user.id) {
    ...code
  }
}
// Cleaner: refactor using the && operator to eliminate the nested if statement:
if (user && user.id) { ...code } 

// Or use the early exit technique to return if a or b is not true to eliminate nesting:
function verifyUser(user) {
  if (!user || !user.id) {
    return;
  }
  ...code to run if user and user.id are true
}

Refactor nested if statements that have repeated conditions to combine them with logical operators:

// Avoid: Nested conditionals with identical conditions:
if (userIsGoldMember) {
  if(itemsInCart) {
    applyDiscount = true;
  }
}
if (totalCost > 100) {
  if (itemsInCart) {
    applyDiscount = true;
  }
} 
// Cleaner: combine the identical conditions and variant conditions with logical operators to eliminate the nested conditional:
applyDiscount = (itemsInCart && (totalCost > 100 || userIsGoldMember));

Make conditions more expressive by extracting the condition to return a boolean in a separate function:

// Avoid: conditions that are complicated and not easy to read quickly:
if (Date.now() >= (new Date(2018, 11, 25).getTime() + 24 * 60 * 60 * 1000)) {
  ...code
}

// Cleaner: separate the condition into a function that returns true or false and describes what the condition is clearly:
const dateIsAfterChristmas = () => {
  return (Date.now() >= (new Date(2018, 11, 25).getTime() + 24 * 60 * 60 * 1000))
};

if (dateIsAfterChristmas()) {
  ...code
}

Refactor Triplicate conditionals: A triplicate occurs when one of multiple conditions is required.  Use the || operator instead of if statements:

// Avoid: separate if conditionals for a triplicate:
if (condition1) {
  return true;
}
if (condition2) {
  return true;
}
if (condition3) {
  return true;
}
return false;

// Cleaner: use the || operator:
return condition1 || condition2 || condition3;

COMMENTS:

  • Comments should not be redundant or stating what is obvious in the code – it just makes more clutter in the code base.
  • Ideally, you shouldn’t need comments since the code you are writing tells a story and it is clear and easy to understand what is going on.  There are differing opinions on this and I think it is a good rule of thumb to follow most of the time.  In reality, there may be a situation where comments would be very helpful to the reader (i.e. when the code is written in an unintuitive way that is necessary, and refactoring would cause breaking changes).
  • If you need to write a comment, don’t write comments addressing “whats” (what the code is ‘saying’, so to speak), write comments that address “whys” and “hows” (why this code is the way it is or how it is doing some operation).
  • Minimizing comments is also a good idea because developers may change logic in the code base, but not update the comments which can cause confusion in the future.
  • The exception to leaving out comments is the case of making a `TODO` note;  These are good comments when a problem in the code is found and a note needs to be left for an issue that needs to be fixed and addressed.
  • If you see comments for blocks of code describing operations in a method, that is a sign that it should be refactored and the operations should be extracted into separate methods.

FURTHER READING AND RESOURCES: 

FULL VERSION (PROTOTYPE) OF COMMENTS EXPLORER DEPLOYED

I have decided to release a prototype of the full version of my Comments Explorer app to get feedback and suggestions.

Click Here to Try the Full Version of Comments Explorer.

Features:

  • Pull a comments list from a Youtube video and search the list by author or text for keywords or phrases.
  • Filter the list of comments by date, thread, or like count.
  • Save comments to your dashboard for future reference or processing.
  • Google OAuth sign-in for easy access.

Built with React, Redux, Material-UI, Node/Express, PostgreSQL, Knex.js including Stripe payment system integration and consumes the Youtube Data API.

The purpose of this app is to provide Youtube content creators or small business owners with videos on Youtube with an easy way to manage their comments section and organize comments that need to be addressed or removed.  The idea is to help video owners to more effectively process and deal with comments on their videos – whether this means being aware of customer or viewer complaints and suggestions, or monitoring unwanted or inappropriate spam or vulgar entries.

The full version adds on to the basic search and sort functionality of the demo by allowing users to save comments to their dashboard, and create custom categories to act as folders to store and organize comments.  Comments can be moved from folder to folder and deleted as desired.

I’ve also integrated the Stripe payment system to the app which is currently in test mode since I’m awaiting approval by Youtube to commercialize the app.  In the meantime you can access the paid version of the app by clicking on Access Full Features in the header and selecting a plan.  On the payment form simply enter 4242 4242 4242 4242 for the credit card number and any numbers for the rest of the fields (expiration date must be in the future).   This will take you to your dashboard where you can access saved items and see information about your account and current subscription.

Note that some features such as saved searches in the dashboard are still under construction and not complete.  This is a trial run and the app is finished enough to present it to the public to get feedback.

Features that I’m working on adding are:

  • Ability to mark comments as spam if you are the owner of the video for the comments pulled.
  • Ability to add notes to comments or mark them as addressed or replied to.
  • Automatic emails to users who subscribe to confirm their purchase and distribute receipts for payments.

Again, I’d love to hear what you think, so please leave feedback or things that you would like to see in the app that would make it better.  In the meantime, enjoy using it and exploring the depths of the Youtube video comment sections.