-
-
Save sapegin/a46ab46cdd4d6b5045027d120b9c967d to your computer and use it in GitHub Desktop.
// How do you avoid name clashes between functions, variables, components, and types? | |
// OK | |
const crocodiles = getCrocodiles({ color: 'green' }) | |
// ??? | |
const isCrocodile = isCrocodile(crocodiles[0]) | |
// OK | |
const user: User = { name: 'Chuck Norris' } | |
// ??? | |
function User(props: { user: User }) => <p>{props.user.name}</p> |
Local variables: If the name of a local variable would clash, I sometimes make it shorter – e.g., isCroc
Good option! And it's clear what it is in a smaller scope.
React component for User: UserView
I guess here I'd prefer to rename the type while importing it and keep the component name to avoid leaking the problem — it might be confusing for the consumer why some components have the View
suffix. Would work if the component isn't exported though!
I guess here I'd prefer to rename the type while importing it and keep the component name to avoid leaking the problem
Note that I only use XView
if it really only is a view for values of type X
. If it does more, I change the name.
I agree with Axel that it's the variables and components that should usually be renamed when a clash happens. For variables, one can sometimes integrate the function result into the business logic, e.g.:
const shouldNotTouch = isCrocodile(animal);
(As I replied in a Mastodon thread, and as @rauschma asked me to reply to here, too) I would probably describe the results more in the names. Something like:
// Well, I assume we are fetching all the green crocodiles.
const greenCrocodiles = getCrocodiles({ color: 'green' })
// Yet again, it seems we are checking if the first item in the array is a crocodile.
const isFirstItemCrocodile = isCrocodile(crocodiles[0])
// Assuming that this is composing a user object to add to a database or whatever.
const userToAdd: User = { name: 'Chuck Norris' }
// Assuming this is a component to show user data. As a single paragraph I
// wouldn’t make it a component, but with that exact example I would probably name
// it something like UserParagraph :)
function UserProfile(props: { user: User }) => <p>{props.user.name}</p>
But well, context matters. Hope these examples were communicated through.
My suggestions:
// add "action" to function name, general pattern when storing variable from getter function: const xxx = getXxx()
const isCrocodile = getIsCrocodile(crocodiles[0]);
// name types / interfaces with "I":
const user: IUser = { name: 'Chuck Norris' }
function User(props: { user: IUser }) => <p>{props.user.name}</p>
isCroc
User
:UserView