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?
My take is use get to retrieve an object by providing a unique identifier. It returns the object or an error (object not found).
Find is used to search for some property of the object
and either returns identifier or identifiers (for use with get) for matching objects. It could also return the objects directly but I don't like that quite as much. It can also return none/and empty list indicating nothing matches the find/search request.
E.g. get the book at this specific location from the shelf compared to find all books that are red and have the words moby in the title.