Skip to content

Code style

Eugene Fox edited this page Nov 12, 2023 · 6 revisions

🚧 Work in progress!

This page currrely is worked on. There may be some discrepancies or outdated information. Use VS Code and ESLint (yarn lint) for code formatting.

Overview

This article contains a set of rules and guidelines that you should follow when working on an issue.

ℹ️ Advice

This repository has additional configuration files that contain some formatting rules and recommended extensions for VS Code editor. So, it is recommended to use VS Code editor during the development, since it that case it will be easier to follow these guidelines.

General

βš”οΈ Indentation and spacing

  • We use tabs, not spaces.
  • Separate logical blocks with empty lines
  • Separate block statements (if/else, try/catch, switch, etc.) with empty lines
  • Always place opening braces on a new line
  • Always place conditional statement on the a new line
// ❌ Incorrect
function GetMessage(key: string): string {
  if (key.length) throw new Error("Empty string is not allowed");
  switch (key) {
    case "success": return "Completed successfully";
    case "fail": return "Something went wrong";
    default:

  }
}

βœ’οΈNaming conventions

The project inherits .NET Naming Guidelines with some exceptions and additions.

Use this table in addition to the main guidelines to determine what naming convention to use

PascalCase camelCase _underscoredCamelCase
All exported members Local-scoped variables Private variables
Files in src folder Local-scoped constants Private constants
React hooks Non-exported constants
Files in public folder Non-exported variables
CSS-in-JS classes

πŸ“– Documentation

  • All exported and public members must be documented using JSDoc syntax
  • Other parts of code may be documented at will

Overall, the more documentation there is, the better.

/**
 * Calculates amount of energy equal to provided mass
 * @param mass Mass of an object in kilograms
 * @returns Amount of energy in Joules
 * @throws If mass is negative
 */
function GetEnergy(mass: number): number
{
	if (mass < 0)
		throw new Error("Mass must be a non-negative value");

	const speedOfLight: number = 3_0000_0000;	// 3 * 10^8 m/s

	return mass * Math.pow(speedOfLight, 2);	// E = mc^2
}

Strings

Always use "double quotes" for literal string values

// βœ… Correct
import React from "react";
export const Message: string = "Hello, World!";

// ❌ Incorrect
import React from 'react';
export const Message: string = 'Hello, World!';

Variables vs constants

  • Always use either let or const keywords. Do not use var
  • Use const when the value will not change. Otherwise, use let
function GetEnergy(mass: number): number
{
	// let speedOfLight: number = 3_0000_0000;			// ❌ Incorrect
	// var result: number = Math.pow(speedOfLight, 2);	// ❌ Incorrect
	const speedOfLight: number = 3_0000_0000;			// βœ… Correct
	let result: number = Math.pow(speedOfLight, 2);		// βœ… Correct

	result = result * mass;
	return result;
}

Constants vs functions

  • Use constants with arrow functions only when it's a one-liner:
     // βœ… Correct
     const log = (...args: string[]): void =>
     	console.log(...args)
    
     // βœ… Correct
     async function GetData(): Promise<unknown>
     {
     	const response: Response = await fetch("https://example.com/api/data");
     	return await response.json();
     }
     // ❌ Incorrect
     const getData = async (): Promise<unknown> =>
     {
     	const response: Response = await fetch("https://example.com/api/data");
     	return await response.json();
     }
    
     // ❌ Incorrect
     function PrintLog(...args: string[]): void
     {
     	console.log(...args);
     }
  • Use constants when exporting React components with no logic. Otherwise use functions
     // βœ… Correct
     export const MyComponent = (props: IProps): JSX.Element => (
     	<Component>
     		<Child data={ props.data } />
     	</Component>
     );
    
     // βœ… Correct
     export function MyComponent(): JSX.Element
     {
     	const [data, setData] = useState<IData>({ });
    
     	useEffect(() =>
     	{
     		fetch("https://example.com/api/data")
     			.then(res => res.json())
     			.then(json => setData(json));
     	}, []);
    
     	return (
     		<Component>
     			<Child data={ data } />
     		</Component>
     	);
     }
     // ❌ Incorrect
     export const MyComponent = (): JSX.Element =>
     {
     	const [data, setData] = useState<IData>({ });
    
     	useEffect(() =>
     	{
     		fetch("https://example.com/api/data")
     			.then(res => res.json())
     			.then(json => setData(json));
     	}, []);
    
     	return (
     		<Component>
     			<Child data={ data } />
     		</Component>
     	);
     }
    
     // ❌ Incorrect
     export function MyComponent(props: IProps): JSX.Element
     {
     	return (
     		<Component>
     			<Child data={ props.data } />
     		</Component>
     	);
     }

Style

  • Prefer to use lambda functions
  • Always put curly braces on new lines
    • Wrong:
      if (condition) {
          ...
      }
    • Correct:
      if (condition)
      {
          ...
      }

    Note: For JSON files put opening brace on the same line as the key

  • Put spaces between operators, conditionals and loops
    • Wrong:
       y=k*x+b;
       if(condition) { ... }
    • Correct:
       y = k * x + b;
       if (condition) { ... }
  • Use ternary conditionals wherever it's possible, unless it's too long
    • Wrong:
      var s;
      if (condition)
          s = "Life";
      else
          s = "Death";
    • Correct:
      var s = condition ? "Life" : "Death";
  • Do not surround loop and conditional bodies with curly braces if they can be avoided
    • Wrong:
      if (condition)
      {
          console.log("Hello, World!");
      }
      else
      {
          return;
      }
    • Correct
      if (condition)
          console.log("Hello, World!");
      else
          return;
  • Prefer export modules as default
    • Wrong:
       export class MyClass { ... }
    • Correct:
       export default class MyClass { ... }
  • Prefer export modules as classes unless it is excessive
    • Wrong:
       export function MyFunction1() { ... }
       export function MyFunction2() { ... }
       export default class MyClass2()
       {
       	public static GetDate(timestamp: number): Date
       	{
       		return new Date(timestamp);
       	}
       }
    • Correct:
       export default class MyClass1
       {
       	public static MyFunction1() { ... }
       	public static MyFunction2() { ... }
       }
       export default GetDate(timestamp: number): Date
       {
       	return new Date(timestamp);
       }
  • When JSX attributes take too much space, put each attribute on a new line and put additional line before component's content
    • Wrong:
       <HelloWorld attribute1="value" attribute2={ value } attribute3="value">My content here</HelloWorld>
       <HelloWorld attribute1="value"
       	attribute2={ value }
       	attribute3="value">My content here</HelloWorld>
       <HelloWorld attribute1="value"
       			attribute2={ value }
       			attribute3="value">
       	My content here
       </HelloWorld>
       <HelloWorld
       	attribute1="value"
       	attribute2={ value }
       	attribute3="value">
       	My content here
       </HelloWorld>
    • Correct:
       <HelloWorld
       	attribute1="value"
       	attribute2={ value }
       	attribute3="value">
      
       	My content here
       </HelloWorld>
  • If JSX component doesn't have content, put space before closing tag
    • Wrong:
       <HelloWorld attribute1="value" attribute2={ value } attribute3="value"/>
    • Correct:
       <HelloWorld attribute1="value" attribute2={ value } attribute3="value" />

Clone this wiki locally