Naming your classes well is super important for writing code that others (and you!) can easily understand later.
What's the Big Idea?
The main point is simple: Your class name should tell you what the object is, not the action it performs.
Avoid Naming by Action
It might seem natural to name a class after a job it does, like EmailValidator
. But this focuses only on one task.
The "DON'T" Example
Class EmailValidator
class EmailValidator {
EmailValidator();
void validate(String email) {
// code to check if email is valid
// ... throws an error if not valid
}
}
This name is okay if the class only ever validates emails. But what if you add features like formatting or parsing emails? The name EmailValidator
doesn't cover those other jobs.
Name by What it Is
Instead, name the class after the thing it represents.
The "DO" Example
Class Email
class Email {
final String _value;
Email(String email) : _value = email.trim(); // Represents an email
void validate() {
// code to check if *this* email is valid
// ... throws an error if not valid
}
}
Here, the class is simply named Email
. This clearly states what the object is. Any actions related to an email, like validate()
, format()
, or parse()
, become methods of the Email
class. This makes your code structure much cleaner and easier to follow.
Better Code, Better Projects
Following this simple naming rule helps keep your classes focused and your codebase organized, making development smoother.