Naming Rules In Clean Code By albro

In this section, I would like to specifically focus on variables, constants and properties (data containers). We can consider three types of specific values that are stored inside these data containers.
- Stored values may be Object. In this case, the name chosen for this variable should describe its content. For example, if your object has a specific user in it, name it
useror if it has an email address, name itemail. - Stored values may be numbers or strings. In this case, the name chosen for this variable should describe its content. For example, if you have stored the user's name as a string in a variable, name it
nameoruserName. - Stored values may be boolean. In this case, the possible values are only
trueorfalse, so the naming must display this state "yes" or "no". For example, for a modal to be active, we use a name likeisActive, or for a user to be logged in, we useloggedInorisLoggedIn.
You can add other descriptions to each of the mentioned names, but these descriptions must have a specific purpose. For example, if a part of the program accepts only authenticated users, we can use authenticatedUser instead of the user name, even if our user is considered a buyer in a part of the program, we can consider the customer name instead of user . Also, if you want to store only the last name of the user, use lastName instead of name. This is also true for booleans; For example, we said that isActive is for a modal, so it's better to use a name like isModalActive so that when we read it, we know exactly what is active (user or modal or whatever)?
By adding these descriptions to the names of the variables, we can determine their function to a large extent, but be careful not to start adding descriptions to the extent that your variables have very long names without paying attention to the meaning.
Examples of naming variables, constants and properties
In this section I examine three different categories of names based on their content: bad names, average names (names that are acceptable but could be better), and good names.
For the first example, suppose we have an object that stores user information (for example, it has the user's email, name, and age). Bad name in this case is u or data or object. When you look at these names, you don't understand anything from them and it isn't at all clear what kind of data we have inside them. Intermediate names are names such as userData or person that specify the totality of the data inside the variable. What is the problem with userData? userData has content! That is, if we chose the name user, it was clear that the user's data is in this variable and the word data is extra. The name person is also too general; Is this person a buyer or an admin? A good name is also a name like user or customer because it accurately specifies what it has inside.
Middle names are names that are not wrong and you can use them, but it is suggested that you look for a better name. Of course, names like userData are completely correct and good. how about Pay attention to the following code:
class User:
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
user_data = {
'entered_name': {
'value': 'Albro',
'is_valid': True
},
'entered_age': {
'value': '27',
'is_valid': True
},
'entered_email': {
'value': 'test@email.com',
'is_valid': True
},
}
user = User('Albro', 27, 'test@email.com')
Here user_data is a good name because user_data only contains raw user data and needs to be validated and has not yet been converted to a user. In such a case, there is a big difference between user_data and user, and using this name is not a problem. My point in giving this example is to let you know that a name may be good in one code but bad in another, and it all depends on the state of your program and code.
Now I have a simple question for you; We are going to validate the data submitted by the user. What name would you consider for such a variable that contains the result of this validation (boolean)? Give examples of your bad, average and good names. A bad name is any name that is not descriptive, so values like input or val or v. input is too general, val may stand for value instead of validation, and v, which is just a letter, is the worst name. Average names are names like validatedInput and correct. The problem with these names is that they don't indicate the result (true or false), but by seeing validatedInput, we may think that the validated data is inside the variable, rather than having the validation result. Good names are names like isCorrect or isValid to reflect the boolean nature well.
Naming rules for methods and functions
Now that we are familiar with the rules of naming variables, we should go to methods and functions. In this section, we can consider two types of special functions: functions that perform a specific operation (this operation can be anything) and functions that check and return a boolean value. In the functions of the first category, we must describe the operation. For example, getUser is a good name to indicate that we are getting the user (we assume this is happening in the database). In the second category of these functions, we must choose a name that answers the true or false question, in this category we should not describe the operation itself. A simple example of a suitable name for this class of functions is isValid().
As always, adding explanations and descriptions to these names is a good thing, provided that there is no padding or overwriting. For example, for the getUser function, we can use getUserByEmail to specify that this function receives a user from the database based on email, or we can use emailIsvalid instead of isValid to specify exactly what we are validating.
Examples of naming methods and functions
In this section, we examine examples of bad, average and good names together. Imagine having a function that wants to store user data in the database. In this case, names like process and handle are bad names because they are very general and do not describe any specific process. For example, process can mean saving the user in the database, but at the same time, it can also mean processing a form or a thousand other operations, and it is not descriptive at all. Also, what does processing mean? Processing can mean storing or updating or deleting and similar operations:
def process(user):
del user
user = {'first_name': 'Albro', 'age': 27}
process(user)
You can see that in the code above, we mean the process of deleting the user!
Medium names are names like save or storeData. These names indicate that something is being saved, but it is still not clear what is being saved. As I explained in the naming of variables and constants section, average names can be good names depending on the environmental conditions. Pay attention to the following code:
class User:
def __init__(self, first_name, age):
self.first_name = first_name
self.age = age
def save(self):
print('Saving!')
user = User('Albro', 27)
user.save()
In this case, the save method is called on the User class. In this code, the name save is perfect because it is called on the user class and it is clear what we are saving, but if you only have one function called save, it is better to change its name to a more appropriate name. Good names are names like saveUser or product.store. saveUser clearly specifies that we are saving the user and product.store also specifies that the store method is called on the product class.
Now imagine that you have a function to validate user data. What name do you choose for him? Bad names are names like process or save. Why? Because our function wants to validate the user's data, it doesn't save anything, let's call it save. The process name is also too generic. Medium names are names like validateSave and check. validateSave is not a good name because it tells us that our function performs both validation and saving operations when it is not. check also does not fully specify what we are checking. Good names are names like validate or if your function only returns the result as a boolean, names like isValid or isValidated are very suitable.
Rules for naming classes
Classes don't have specific types, and we only have one guideline for naming them: always describe the object on which the class is based. For example, if we are going to create an object for the user from the desired class, we name that class User. Of course, as always, it is recommended to be more precise in the naming (for example, choosing the name Customer instead of User). You can choose the name of your classes with a few words, but this name should not contain any words. For example, DatabaseManager isn't a good name because it contains stuff. We could have named this class just Database and it would be clear that this class is responsible for managing our database (the word manager is redundant). These names are usually used for static classes that are full of utility and auxiliary classes.
Examples of naming classes
In this section, I will review examples of bad, average and good names. Imagine we want a class that creates a User object. Bad names are names like UEntity or ObjA. These names are so general that they do not refer to any important user details, so you should not use them. Intermediate names are names like UserObj or AppUser. These names have a lot of content; For example, naturally, the class that is defined to create a user creates the user object, so instead of UserObj, we can only use User because it is obvious that it is Obj or Object. Also, "user" means the user who is in our application, so AppUser has a content and it is better to use empty User. So, you must have noticed that good names are names like User or Admin or Customer because they specify in detail what kind of user this user will be (normal user, admin, buyer, etc.).
Now I ask you: choose a name for the class that is going to be connected to the database. The bad name in this case is Data or DataStorage because Data is too general and DataStorage does not specify what kind of storage we will have (maybe it is a database storage location, maybe it is a simple text file and so on). Middle names are names like DB but still may not be obvious to some people. Good names are also names like Database or even more precisely SQLDatabase because they specify exactly what we are dealing with.
Why the exception?
The rules we have reviewed up to this section were general rules but still have exceptions. A simple exception is as follows:
from datetime import datetime
class DateUtil:
@staticmethod
def get_formatted_today():
date_today = datetime.now()
formatted_date = date_today.strftime('%Y-%m-%d')
return formatted_date
print(DateUtil.get_formatted_today())
If you pay attention to this code, you will notice that names like strftime are exactly the opposite of what I explained to you. Anyone who has worked with Python knows that strftime stands for string from time because it returns a string from a date object. Why? Developers of programming languages usually try to shorten the method names as much as possible and in this way they sacrifice the readability of the code. Different people have different opinions in this field; People who agree with this method say that by choosing long names, we cause developers to type more characters while coding and their speed decreases, and those who oppose say that the speed of developers decreases more in this case. Why? that they should search about these methods to know what each method does. I'm personally against such names because typing long names in programming is not a serious problem. We have autocompletion in our editors, and by pressing the tab key, the entire name is typed for us. I find it more annoying to search for method names to understand how they work. You should always try to keep your codes descriptive and readable, even if you agree with this summary method, because everyone has to learn a programming language, and maybe it doesn't matter because it's only one language, but if everyone is going to code like this If they write, then we have to spend a lot of time to read each code and decode it!
Another important thing is that I have named my class DateUtil while I told you to stay away from names like DatabaseManager. Why? If our class contains mostly static methods (such as the get_formatted_today method in the code above) and is a set of helper methods as a whole, using such a name is quite appropriate.
You can see another exception in the following code:
class Database {
private client: any;
get connectedClient() {
if (!this.client) {
throw new Error('Database not connected!');
}
return this.client;
}
connect() {
// Establishing connection ...
this.client = {};
}
}
const db = new Database();
db.connectedClient.query();
In this code, we have a method named connectedClient. The name of this method is like the name of a property or variable and it does not follow the rules of naming methods, so it is not a proper name, right? No! Here connectedClient is a getter that returns our private property called client and at the end of the code you can see that we have accessed it as a db.connectedClient.query property. Therefore, I request you to use the described instructions according to their situation.










Comments