This content originally appeared on DEV Community and was authored by Jakob Attkinson
Coming from a world where "find" and "get" are (were) used interchangeably, I find myself staring at a piece of code for over 10 minutes not being able to decide how to proceed.
I know naming is one of the most difficult task in programming, however I feel like in this particular case there should be like an unwritten rule for how we should prefix a method.
To be more specific, let's assume we want to fetch a user from the DB by its ID.
public async getOneById(id: number): Promise<User> {
const user = await this.userRepository
.createQueryBuilder("u")
.where("u.id = :id", {id})
.getOne();
if (!user)
throw new Error(`User with ID "${id.toString()}" not found.`);
return user;
}
The same method can be used to return null
in case the user is not found:
public async findOneById(id: number): Promise<User | null> {
return await this.userRepository
.createQueryBuilder("u")
.where("u.id = :id", {id})
.getOne();
}
I'm struggling to decide if I prefer the above or if the find
and get
should be swapped around.
I don't know if there's any "standard", wasn't able to find anything conclusive.
What do you think? Does / should the same convention apply regardless of the programming languange?
This content originally appeared on DEV Community and was authored by Jakob Attkinson
Jakob Attkinson | Sciencx (2022-05-30T22:32:45+00:00) How do you use “find” vs “get” prefix?. Retrieved from https://www.scien.cx/2022/05/30/how-do-you-use-find-vs-get-prefix/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.