Skip to main content

10 commandments to naming and writing clean code with TypeScript

A code writer is like any other writer; writes to be read and understood. To do so it must obey certain laws. They are so important that must be followed religiously.

Being a good writer is an art. But you can be a better programmer by knowing and applying a set of standards. In this guide, I will show you TypeScript samples for the 10 rules of clean naming.

10 Books by sharonmccutcheon on Unsplash


When you're finished, you'll be able to write heavenly code.Let there be code naming conventions

1️⃣ Be Descriptive

Add value without being repetitive. Context is key. Prefer clarity over saving space. We are not in the ‘90s’ anymore.
// ❌
const width = 5;
class Image {
  imageWidth = width;
}
// ✅
const imageWidth = 5;
class Image {
  width = imageWidth;
}

2️⃣ Be Meaningful

Use the same word for the same concept. Create a dictionary for business and infrastructure common words.
// ❌
getClient(){}
readProvider(){}
postCustomer(){}
// ✅
getClient(){}
getProvider(){}
postClient(){}

3️⃣ Spell properly

Avoid typos by making your names easy to pronounce and search for. Have I told you about having a dictionary?
// ❌
const crtAtTs = new Date();
function insInv() {}
// ✅
const createdAtTimestamp = new Date();
function insertInvoice() {}

4️⃣ Respect your language style

Be consistent, follow community standards, and your reader will be comfortable. TypeScript is not Java or JavaScript.
// ❌
const created_at = new Date();
const workingDays = 5;
function Calculate_payroll() {}
class employee {}
interface IPayable {}
// ✅
const createdAt = new Date();
const WORKING_DAYS = 5;
function calculatePayroll() {}
class Employee {}
interface Pay {}

5️⃣ Use verbs for doing or asking things

Functions have names to tell a story. An action story, in fact. Start with a verb to explain what your function does or returns. Pay special attention to Booleans.
// ❌
function client() {
  return new Client();
}
function allowed() {
  return false;
}
// ✅
function createClient() {
  return new Client();
}
function isAllowed() {
  return true;
}

6️⃣ Be positive

Avoid negative comparations but use common sense. Read your conditionals out loud in case of doubt.
// ❌
const isNotEmpty = true;
if (isNotEmpty) {
  doSomething();
}
// ✅
const hasValue = true;
if (hasValue) {
  doSomething();
}

7️⃣ Don't do magic

Prefer well-named constants over magic numbers. This will lead to better understanding and easy refactoring. You can respect 0, 1, or 100.
// ❌
function calculateDiscount(price: number) {
  if (price > 1000) {
    return price * 0.2;
  } else {
    return price * 0.1;
  }
}
// ✅
function calculateDiscountedPrice(price: number) {
  const EXPENSIVE_LIMIT_PRICE = 1000;
  const EXPENSIVE_DISCOUNT_FACTOR = 0.2;
  const CHEAP_DISCOUNT_FACTOR = 0.1;
  if (price > EXPENSIVE_LIMIT_PRICE) {
    return price * EXPENSIVE_DISCOUNT_FACTOR;
  } else {
    return price * CHEAP_DISCOUNT_FACTOR;
  }
}

8️⃣ No tech encodings

Show intention and hide the implementation details. Remove technical jargon and add business value.
// ❌
function getEmployeeList(paramCompanyNameString: string) {
  return findInMongo(paramCompanyNameString);
}
// ✅
function getEmployees(companyName: string) {
  return findByCompanyName(companyName);
}

9️⃣ No mental mapping

Don’t make me think. Avoid abbreviations. Don’t treat me like a fool. Use local or well-known single-letter names.
// ❌
const cs = customers();
const cn = cs.length;
for (i = 0; i < cn; i++) {
  cs[i].sendInvoices();
}
cs.forEach((c) => c.sendInvoices());
// ✅
const customers = getCustomers();
const numberOfCustomers;
for (i = 0; i < numberOfCustomers; i++) {
  customers[i].sendInvoices();
}
customers.forEach((c) => c.sendInvoices());

1️⃣0️⃣ No comments

Oh, my goodness, no more unnecessary comments. Truth is in the code, comments may eventually be deleted or outdated.
// ❌
const d = 5; // days
// print the schedule
function print() {}
// ✅
const days = 5;
function printSchedule() {}

🌅 Conclusion

These ten commandments can be summed up in two:

✍🏼 Reveal the writer's intention

📖 With minimum reader effort

In this article, you have a set of clean naming best practice examples. Don't be guilty of writing hard-to-understand code. Words are the bricks to build narratives. Choose your names to say what your code does clearly.

learn, code, enjoy, repeat

Alberto Basalo

Popular posts from this blog

Fine-tune ESLint rules to write better TypeScript

Writing clean code is a lot easier with the right tools well configured. ESLint is a static analyzer for JavaScript programs. So what does that mean and what can it do for my TypeScript code? First things first, by static it means that you don't need to run or even compile a program to parse it. Analyzing means that it checks your code searching for flaws or bad metrics that can cause problems in the long run. The ESLint is a linter that runs before the compiler. Witch runs before your automated tests and the end-user. Is your first line of defense and should be as integrated with your editor as possible. For the details about integrating ESLint and VSCode, you can read my article to configure basic extensions But ESLint would not be so popular if it was not extensible and configurable . And there is the real power and complexity. In this article, I'll walk you through

How to configure VSCode to code better TypeScript

Writing a more readable code is your first goal as a programmer. This initial Visual Studio Code setup makes your job easier. Any good worker must know and customize his tools for the job at hand. With minor tweaks, VSCode is the perfect tool to write TypeScript . There are plenty of guides to configure VSCode . Most of them include a lot of extensions. But almost none starts from the very beginning, with no extension at all. I am an enthusiast of writing clean code , so I do my best to promote and facilitate this goal, and I am sure that this can help you to write better code. In this post, you will learn how to adapt VS Code to write better TypeScript code, even without any extension. And above all, you will get tips to adopt good habits and detect programming vices. 🎒 Prerequisites To complete this tutorial, you will need: A local copy of Visual Studi