Today, I came across a function in our codebase that appears to have a logical flaw. The function is written in TypeScript and looks like this:
const getUserInitials = (user: IUser | null) => {
if (!user) { return ""; }
return (user.FirstName.charAt(0) + user.LastName.charAt(0)).toUpperCase();
}
After some analysis, it seems to me that allowing the function to accept incorrect argument types and then trying to handle them internally by returning an empty string is not ideal. Instead, I believe the function should only accept arguments of type IUser
, with any necessary argument checking done before invoking the function.
This raises the question of whether it should be considered a best practice to always check for argument correctness before calling a function? While there are cases where internal checks are necessary, such as ensuring an integer falls within a certain range, in situations like the one presented here, it may result in violating the function's contract.
In fact, I suggest renaming the function to
getInitials(user: IUser) => {...}
as the word "user" in the function name becomes redundant when the argument itself is clearly specified.
Do you agree that validating arguments before function invocation is crucial in preventing contract violations?
Are there instances in statically typed languages where checking argument correctness internally is acceptable?
Is my observation about redundancy in function naming accurate?
Thank you for your insights.