Categories
Best practices Development Workflow

Front-end naming conventions

There are only two hard things in Computer Science: Cache invalidation and naming things.

— Phil Karlton

Naming convention is probably the most difficult thing that can be universally agreed upon. While everyone in a team agrees to have a good convention to follow, but probably no convention ever satisfy everyone’s way of writing. Every developer prefers to make it close to their personal preference and at time it creates a mess which to an outsider gives the impression of not following any convention altogether. So, disagreement is obvious. Hence, it’s always recommended to follow what fits better for the team.

Adopting good names and patterns makes everyone understand the context quickly, search faster, brings more predictability. Different languages/frameworks may follow or recommend different kind of convention, and in most cases, it’s advisable to follow them closely. Here we will discuss some of the generic patterns that has proved to be easy to adopt based on the following judging parameters and which one to pick. 

  • Easy to read: As we spend more than 10 times reading the code, we must make it pleasing to read and easy to comprehend.
  • Faster to type: We should try to make the code easier to type and avoid accidental typo errors
  • Avoid cross OS issues: Though most operating systems have similar file/folder naming conventions, but at times they differ. As an example, windows is case sensitive whereas linux is not. GIT sometimes create problem in resolving names because of uppercase and lowercase filenames for windows and mac.
  • Easy to identify context: The file/folder names, variable/method/class names should indicate their purpose and context
  • Followed by most libraries / Frameworks: It makes seamless and easy to convince anyone in the team

Before we start jumping to examples section for each kind of use, let me put the names of each kind of case for quick lookup in this article.

  • camelCase (starts with lower case and all subsequent words starting with upper case )
  • PascalCase (every word start with upper case)
  • snake_case (words separated by underscore)
  • kebab-case (words separated by hyphen)

There is not a single choice for naming conventions and there is not one rule for all. Depending on the usage, origin and context, the rules change and there are exceptions as well. We shall go through each of these rules and variations one by one. I would also put primary and some secondary choices that you can have where ever possible.

Naming Files & Folders

While choosing file and folder names, the most crucial thing to take care of is the operating system dependency. So, I always suggest not to opt for any special character other than underscore (“_”) and hyphen (“-“).

Naming folders

Let’s check out choices that we have based on the different kind that I mentioned above.

  1. oldArchive
  2. old_archive
  3. OLD_ARCHIVE
  4. old-archive
  5. OldArchive

The best choice is to opt for all lower case and hyphenated.

ex: old-archive, login-section

Naming Files

Camel / Pascal Case

Here there are lot of variations, people coming from other language that follow oops prefer to have camel and pascal case for javascript files. This comes from the principle of writing classes and methods in pascal and camel cases. People with python background follow underscore delimited words. To be honest, file names need not be written in exact same manner as the class name, but it certainly helps searching. HTML and CSS files also follow the same rule at times. For HTML files, this trick helps in hiding underlying file system by mapping SEO friendly URLs to actual HTML files/fragments/server side templates.

// Pascal case
Login.js, 
LoginModule.js, 
Login.html

// Camel case
login.js
loginModule.js
login.html
loginPage.html

While this is one of good choices this still carry the risk of cross OS issues. This is suitable if your you are too much into class based programming.

Hyphenated ( Kebab style)

Hyphenated names are adopted in so many good libraries. This is in line with the folder names, and most simpler to write.

ex:

login.js
login-module.js
mobile-products.html
mobile-products.css

The benefit of using hyphenated structure all type of file brings more consistency in typing and does not have any cross os issues.

While using versioning, variation or as a child library, the names should be joined by a dot “.”. And in case of SASS partial files, the default convention is to prepend underscore. Ex:

login.v3.0.0.js 
login.min.js
coursel.jquery.js
_color-variables.scss // exception for sass partial files

In general the file can name can follow the following pattern:

<name-of-the-file>.<name-space/parent-library>.<variations>.<version>.<extension>

There are few variations and exceptions in both the cases. Both styles are equally good, but I prefer and suggest the kebab style for consistency any day. However there exists a third style which is mixed bag and getting more love these days by the new age developers. Its mostly adopted by react and angular community and it adopts a contextual styling. But no matter what file names you use, I would always suggest to kebab case with all lower case letters for folder names. If you are starting with a new project, probably you should consider this for your team.

Here is typical file/folder naming illustration.

config
    - app-config.json /* these files are external helpers and do not follow regular camel casing. */
    - build-config.js
    - project-aliases.js 
    - unit-testing
        jest.config.json
src
    - components
        - main-navigation
            - MainNavigation.js // React class/ react functional component
            - MainNavigation.style.js // css in js 
            - MainNavigation.css // if using regular css or css modules
            - MainNavigation.spec.js // test cases, it may have .spec or .test 
            - index.js // file that exports the MainNavigation to avoid typing the long path
    - assets
        - images
            - application-logo.svg // assets to follow lower case kebab convention 
        - fonts 
            - custom-font.ttf
    - utils
        - browser-utils
            - getNavigatorDetails.js // utilities or any other such javascript to be named by default export 
            - scrollTo.js
        - ApplicationCache.js // class utils - so starts with capital case.
    - views
        - index.js // view templates in case there are no html files
        - applicationDashboard.js // follow camel case as per the module name inside.
    - templates
        - index.html
        - application-dashboard.html // html files to be named kebab style
.editorconfig // configurations like eslint, editorconfig, prettier to follow hidden file style - all lowercase and no space
README.md // special treatment to readme doc to easily differentiate
package.json
package-lock.json

I am sure, you might have deviations and fair logic to support it and I am happy learn about it. Please put that in the comments below this article.

Naming Javascript variables

Variables

Variable names where I think developer gets the highest level of freedom as a misconception. The reality is there are least options found to be good enough. People with python background prefer underscore as word separator, people coming from action script world preferred to use prepend underscore for private variables and so on.

While these conventions are possible, but the most preferred and agreed convention is to follow camel case for regular variables and methods. Its always suggested to avoid abbreviations.Note: avoid abbreviations and acronyms Examples of such instances are given below.

var counter = 0;
var selectedIndex = 0; 
let humidityFactor = 45;
function getIndex() { //....} 
const getIndex = () => {} 
const getHttpHeader = () => {} 

// getter, setter in classes
const getClientId = () => {}
const setClientId = () => {}

Note: For acronyms also follow camel casing.

As long as the variable names are self-explanatory, they are good. Here is the example of some “not so good” and “good” names

var a = 0; // not so good
var basePrice = 0 // good
function index() {} // not so good
function getIndexOfStateSelection () {} // good

Constants

With introduction of const keyword in ES6, there is good indication of something that won’t change once declared. For this purpose, the best and the most common way to show it visually to use upper case letters separated by underscore.

( Note : const when used with a function name does not follow this rule)

// example of constant variable
const TOTAL_STATES = 50; 
const GENERIC_ERROR_MSG = "Oops! Something went wrong"

Events

Event names are kind of constants, so they should follow the same pattern as that of constants. Here is the sample example:

// example of events
let customEvents = {
        ANIMATION_START: "animation-start",
        ANIMATION_END: "animation-end"    
    }

Naming Javascript Classes

Class names should follow pascal case.

class BrowserUtils {
  static freeze() {
       // some code here.
    }
}

React functional components

Functional components are still considered as kind of class, though we never use class keyword, but they are custom components so they should follow class naming convention.

const SecondaryHeader = ( props ) => {
   return (
        <>
            <h2 className="SecondaryHeader">{props.label}</h2>
        <>
   )
}

Naming CSS Classes & Variables

The way we write CSS has gone through lot of changes in recent past. Starting from simple way of writing one single css files to CSS in JS way of writing – every where the way of using classes and variables have been changed based on the technology it followed. I have seen three major phases which has affected the naming of classes and variable.

Regular CSS and with preprocessors like SCSS/SASS/LESS: Developers used basic hyphenated (kebab case) class names and variables. SASS/LESS functions/variables followed javascript method names.

Evolution of BEM/SMACCS/ITCSS/DRY and similar concepts: Dealing with large css, css fragments and development teams, it required a lot of consistency and pattern. BEM is still considered as the most adopted pattern. Click here to learn more about BEM

CSS Modules / CSS in JS : This solved the problem of css precedence and conflict of names. This adds extra details to your class names so that they are unique always. While css module still can follow BEM or other similar pattern, CSS in JS is too much in to javascript way and hence follow camel case in most cases.

Before we jump in to the details of writing classes, let’s learn about ids. It’s always recommended to avoid id for styling and use classes instead. If still you need to declare styles using ids, then prefer to write it in camel case. Though few developers use pascal case , but it’s relatively rare.

#mainHeader {
 padding: 50px;
}

So, let’s explore classes and variables one by one.

CSS variables

Note: CSS variables are relatively new and may have few old browser limitations as of writing.

CSS variables can follow either camel case or kebab case or BEM pattern. Choose one of them depending on what the team follows. The code below is primarily for SASS, LESS.

:root {
    --primary-color: #000;
    --brand-name-primary-color: #00f
}

For simple css, hyphenated is the most preferred and this is adopted in almost all the libraries.

css in js and SASS/LESS way


/* sass/less hyphenated */
$primary-color: #000;
$brand-name-primary-color: #00F;

/* camel case */
$primaryColor : #000;
$blueThemePrimaryColor: #000;

/* BEM way*/
$accent-color: #ff0;
$accent-color--primary: #000;
$theme-name__accent-color--primary: #00F;

/* modified BEM - hybrid of camel casing along with BEM separators */
$accentColor: #ff0;
$accentColor-primary: #000;
$themeName_accentColor-primary: #00F

My preference goes towards simple hyphenated structure for small projects and the original BEM for large distributed projects.

CSS Classes

Unlike variables css class names should follow the pattern based on preprocessor use. For regular css and SASS/LESS ways of writing I suggest to adopt utility first approach for global reusable classes and for individual components and their child BEM is the best convention. As we tend to have component oriented architecture, I never been a big fan of SMACSS or adding prefix for components ( c-header) , layouts ( l-left-container), utility(u-center-align), typography(t-body-copy) etc.

Mixins / Functions / Placeholders

For mixins and functions can also follow similar pattern as of classes and variables. Follow it according to the pattern used in classes.

// example of function
@function calculate-rem($size) {
  $rem-size: $size / 14px;
  @return #{$rem-size}rem;
}
.application-bar {
  @extend .app-bar;
  @extend %flex-layout;
  background-color: red;
}

At the same time, as they closely resemble with methods in javascript, it makes sense to give them similar treatment.

// example of function
@function calculateRem($size) {
  $remSize: $size / 14px;
  @return #{$remSize}rem;
}

@mixin mobileOnly {
  @media (max-width: 599px) { @content; }
}

.applicationBar {
  @extend .appBar;
  @extend %flexLayout;
  background-color: red;
}

Naming convention for HTML

HTML is forgiving. You can write both in upper case and lower case, however because of easy typing, its recommended to use lower case for all elements and attributes.

<P>Example of uppercase : avoid writing like this</P>
<p>Example of lowercase : this is the best</p>

This article primarily focused on html, css and javascript conventions. It’s more important to be consistent than choosing the right convention. Pick the one that your team is more comfortable with.

Do let me know your views in the discussion thread below.

Comments