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 specific laws. They are so vital that they 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.
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; // 🤢 with of what?
export class Image {
imageWidth = 5; // 🤢 redundant
}
// ✅
const imageWidth = 5; // 😏 full context
export class Image {
width = 5; // 😏 inferred from context
}
2️⃣ Be Meaningful
Use the same word for the same concept. Create a dictionary for business and infrastructure common words.
// ❌
function getClient() {
return "Alice";
}
// 🤢 is read the same as get?
function readProvider() {
return "Bob";
}
// 🤢 is a customer the same as a client?
function postCustomer(name: string) {}
// ✅
function getClient() {
return "Alice";
}
// 😏 same action, the same verb
function getProvider() {
return "Bob";
}
// 😏 a client is always client
function postClient(name: string) {}
🤖 Code generators use your previous code to infer the next. Help them help you by being consistent.
3️⃣ Spell properly
Avoid typos by making your names easy to pronounce and search for. Have I told you about having a dictionary?
// ❌
function insInv() {
const crtAtTs = new Date(); // 🤢 read out loud if you dare
}
// ✅
function insertInvoice() {
// 😏 easy to spot mistakes
const createdAtTimestamp = new Date();
}
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(); // 🤢 avoid _symbols_
const workingDays = 5; // 🤢 a const primitive is a CONSTANT
function Calculate_payroll() {
// 🤢 oh lord... Hell_case
}
class employee {
// 🤢 type definition should be PascalCase
}
interface IPayable {
// 🤢 an interface is not a class; find a good name
}
// ✅
const createdAt = new Date(); // 😏 camelCaseIsEasyToRead
const WORKING_DAYS = 5; // 😏 CONSTANTS SHOULD SCREAM
function calculatePayroll() {
// 😏 function naming is naming
}
class Employee {
// 😏 TypeDeficnition
}
interface Pay {
// 😏 is about the behavior
}
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() {
// 🤢 what are you doing with a client?
return new Client();
}
function allowed() {
// 🤢 are you asking me?
return false;
}
// ✅
function createClient() {
// 😏 a verb in a function tells what she does
return new Client();
}
function isAllowed() {
// 😏 is, has, can, must... help reading and understanding
return true;
}
6️⃣ Be positive
Avoid negative comparations but use common sense. Read your conditionals out loud in case of doubt.
// ❌
const isNotEmpty = Math.random() > 0.5;
// 🤢 express conditions in positive
if (!isNotEmpty) {
console.log("do nothing");
} else {
console.log("do something");
}
// ✅
const hasValue = Math.random() > 0.5;
// 😏 easy to read
if (hasValue) {
console.log("do nothing");
} else {
console.log("do something");
}
// Even for early returns
if (! hasValue){
console.log("returning...");
}
console.log("do something");
7️⃣ Don’t do magic
I 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) {
// 🤢 where these numbers came from?
if (price > 1000) {
return price * 2 / 100;
} else {
return price * 1 / 100;
}
}
// ✅
function calculateDiscountedPrice(price: number) {
// 😏 clearer
const EXPENSIVE_LIMIT = 1000;
const DISCOUNT_EXPENSIVE = 2;
const DISCOUNT_CHEAP = 1;
// 😏 100 is easy to infer in this context
if (price > EXPENSIVE_LIMIT) {
return (price * DISCOUNT_EXPENSIVE) / 100;
} else {
return (price * DISCOUNT_CHEAP) / 100;
}
}
// Exceptions:
// well-known constants like 0, +-1 or 100 in certain contexts.
8️⃣ No tech encodings
Show intention and hide the implementation details. Remove technical jargon and add business value.
// ❌
function getEmployeeArray(paramCompanyNameString: string) {
// 🤢 too much technique and little business
return findInMongo(paramCompanyNameString);
}
// ✅
function getEmployees(companyName: string) {
// 😏 tell what, not how
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.
// ❌
// 🤢 a bad naming reminder
const cs = customers();
const cn = cs.length;
for (let i = 0; i < cn; i++) {
// 🤢 what was cs meaning
console.log("send invoices to", cs[i]);
}
cs.forEach((c) => console.log("send invoices to", c));
function customers() {
return [];
}
// ✅
// 😏 well-named things always seem right
const customers = getCustomers();
const numberOfCustomers = customers.length;
for (i = 0; i < numberOfCustomers; i++) {
// 😏 no doubt with i as an index
console.log("send invoices to", customers[i]);
}
// 😏 it is ok for immediate-use
customers.forEach((c) => console.log("send invoices to", c));
function getCustomers() {
return [];
}
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(d: number) {
console.log("your schedule for the next", d, "days");
}
// ✅
const days = 5;
function printSchedule(days: number) {
console.log("your schedule for the next", days, "days");
}
// Exceptions:
// Public API documentation, warnings, or any temporary or todo comments
🌅 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 in TypeScript to make your reader’s life easy. 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.
To keep writing clean code, follow my guide to write better functions and methods with TypeScript
🙏🏼If you liked this post, consider clapping or sharing it. Check my profile to get in contact or find more info about clean code, testing, and best practices with TypeScript.
learn, code, enjoy, repeat