Clean Code (Best practice for naming) Part 1
In this article, we will discuss
- Clean code definition.
- Best practice for clean class names.
- Best Practice for clean method/function names.
- Best practice for clean Variable names.
- Best practice for parameter names.
- Best practice for constant names.
Write code for humans 👩👨, not only for machines💻💻
When you write code, who are you writing it for? The easiest answer is that you’re writing it for the computer, or more specifically, the compiler or interpreter for the language that you’re writing in. That’s true, your compiler or interpreter needs to be able to understand your program well enough to execute it. What’s another audience? In many professional settings, you’re not writing code in complete isolation. There are other people on your team. And those people need to be able to understand the code that you’ve written. Chances are pretty good that you’re going to need to revisit your code and need to understand what it does, how it works, and why it was written that way. The chances are high that another human will need to work with your code in the future and this is likely to happen after you’re not available to answer questions. Four different groups, but the last three have something really important in common. They’re all human. So we need to make sure that we’re creating code that can be easily understood by humans. That’s where clean code principles come into play. By following them, you will ensure that you’re crafting code that will be understood by anyone who happens to read your code in the future, be it one of your teammates when doing a code review, your future self when fixing a bug, or your successor when adding a feature.
What is the clean code?
- Code that’s written to compile into a machine and readable to human.
- It uses names that are easy to understand.
- Formatted consistently. formatting affects code readability.
- easier to improve, and easier to fix than messy code.
- it clearly communicates its intent. coders can understand what this piece of code does.
in the below sample, a method that doesn’t have a clean name which can illustrate its intent, in such a case you have to read it line by line to understand what it does.
fun s(arr: IntArray) {
val n = arr.size
for (i in 0 until n - 1) {
for (j in 0 until n - i - 1)
if (arr[j] > arr[j + 1]) {
val temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
in a clean way:
fun bubbleSort(array: IntArray) {
val arraySize = array.size
for (index in 0 until arraySize - 1) {
for (pointerIndex in 0 until arraySize - index - 1)
if (array[pointerIndex] > array[pointerIndex + 1]) {
val temp = array[pointerIndex]
array[pointerIndex] = array[pointerIndex + 1]
array[pointerIndex + 1] = temp
}
}
}
here you can catch the intent of the method, from the first look and get what this method does due to its clear name. it is bubble sort
Best practice for clean class names
- Use nouns for class names. ✅
class Performer {}
class Performance {}
- Avoid verb forms for class names. 🚫
class Perform {}
class Performed {}
class Performing {}
- Use adjective prefixes to convey time. ✅
class ActivePerformance {}
class PastPerformer {}
- Avoid adjectives only as class names. 🚫
class Huge {}
class Small {}
class Fast {}
class Slow {}
- Use adjectives as a prefix to a noun as class names. ✅
class SmallPerformance {}
class FastPerformer {}
- Avoid vague prefixes. 🚫
class MyPerformer {}
class APerformer {}
class ThePerformer {}
class ThisPerformer {}
- Avoid single-letter class names. 🚫
class P {} //-> print in console
class L {} //-> logger
- Avoid single-letter prefixes. 🚫
class CPerformer {}
class TPerforer {}
- Avoid all capital acronyms. 🚫
class HTTPAPIPerformer {}
- Use boundaries between acronyms. ✅
class HttpApiPerformer {}
- Avoid abbreviations. 🚫
class Perf {}
- Avoid lower case capitalization. 🚫
class performer {}
- Avoid using plural for a normal class. 🚫
class Performers {}
- Use plural for collection classes. ✅
class Currencies {
...// contain map of Currencies, and format price for each currency
val currencyMap = mapOf(
Pair(RUSSIAN_RUBLE, "\u20BD"),
Pair(EURO, "€"),
Pair(BRITISH_POUND, "£"),
Pair(UNITED_STATES_DOLLAR, "\$")
)...
}
Best Practice for clean method/function names
- Use present tense verbs for method names. ✅
fun open() {}
fun perform() {}
fun close() {}
fun validate() {}
- Avoid start name with gerunds (verb + “ing”). 🚫
fun performing() {}
fun validating() {}
fun opening() {}
fun closing() {}
- Avoid past tense verb forms. 🚫
fun performed() {}
fun opened() {}
fun closed() {}
fun validated() {}
- Use prefix gerunds with `is`. ✅
fun isRunning() {}
fun isClosing() {}
fun isServing() {}
- Use prefix past tense verbs with `has`. ✅
fun hasPerformed() {}
fun hasOpened() {}
fun hasClosed() {}
fun hasValidated() {}
- keep the same naming criteria and conversions consistent across all your Application/System. ✅
- If your programming language supports Camel casing style, use it. ✅
Camel casing has a larger probability of correctness than underscores. (odds are 51.5% higher).
Best practice for clean variable names
- Use singular nouns for primitive types and object instances. ✅
val name = "Ahmed"
val performer: Performer = Performer(name)
- Use plural nouns for arrays and other collections. ✅
val names = arrayOf("Alex", "Ali", "Aesop")
val years: List<Int> = listOf(1980, 1999, 2003, 2010)
- Avoid verbs for variables that store primitive types. 🚫
val perform = 12
val create = false
- Use none for variables that store primitive types. ✅
val performanceCode = 12
val creationEnabled = false
- Avoid single-letter variable names. 🚫
var s = 12
var i = 8
- Use a meaningful name can clarify its purpose.✅
var size = 12
var index = 8
- Avoid confusing acronyms and abbreviations.🚫
val dbsqlSelAllNames = "select * from names;"
- Use separate acronyms and spell out abbreviations.✅
val dbSqlSelectAllNames = "select * from names;"
- Void complicated prefixes such as Hungarian notation.🚫
val f_strFirstName = "Jefferson"
- Avoid using the data type name as a suffix. 🚫
var lastNameString = "Amaya"
Best practice for parameter names
very similar to rules that are used for variable names
- Use singular nouns when naming a parameter that contains a single value ✅
fun add(left: Int, right: Int): Int {
return left + right
}
- Use plural nouns when naming a parameter that contains a collection of values. ✅
fun sum(values: IntArray): Int {
var result = 0
for (value in values) {
result += value
}
return result
}
- Use the noun version of a verb form when naming a parameter that is passing in a function or a closure. ✅
fun compare(left: Int, right: Int, comparer: (Int, Int) -> Int) {
comparer(left, right)
}
- Avoid using single-letter parameter names.🚫 (our goal is to limit the number of assumptions that must be made when reading the code later)
fun add(l: Int, r: Int): Int {
return l + r
}
- Avoid using abbreviations as a parameter name.🚫
fun open(FSP: String) {}
- Avoid starting parameter names with capitalized letters. 🚫
fun random(SeedGenerator: Int) {}
- Use separate acronyms and spell out abbreviations. ✅
fun postResult(httpApiUrl: String, data: String) {}
- Avoid complicated prefixes.🚫
fun persistName(sName: String) {}
Best practice for constant names
but in your mind, not all of the languages agree for the below practice.
- Capitalize All characters.✅
- Use singular nouns for primitive values.✅
- Use plural nouns for a collection of values.✅
- Avoid using single-latter and abbreviations.🚫
- Ensure separation between acronyms.✅
By the end, those are general rules and some of those best practices depending on the language you use, and it might vary from language to another.
Encourage me 👍, to keep it up 📈 and come with the next parts. comment📝, clap 👏, share↗️ between your colleagues.
Resources:
📝 Read this story later in Journal.
👩💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.