Naming functions might seem trivial, but it can significantly impact readability and maintainability. One common dilemma is whether to name a function based on when it’s called or what it does. Let’s explore this with a simple example.
Example: Showing a Popup
Suppose you have a function that shows a popup when a button is pressed:
const onButtonPressed = () => {
popupInstance.show(LENGTH_LONG);
};
<Button onPress={onButtonPressed} />;
The function name onButtonPressed clearly reflects when this function is called – in response to a button press.
But what if you also need to show the same popup when the page loads?
// other initialization code...
onButtonPressed();
Now we have a small mismatch – the function name implies a button press, but we're calling the function even if no button is pressed.
An Alternative Approach: Name it Based on What it Does
Consider renaming the function to reflect what it does, not when it’s called:
const showPopup = () => {
popupInstance.show(LENGTH_LONG);
};
When the button is pressed:
<Button onPress={showPopup} />;
When the page loads:
// other initialization code...
showPopup();
This small change improves clarity. It’s immediately obvious that the function shows a popup, regardless of the trigger.
When is ‘When It’s Called’ Appropriate?
Naming functions based on when they are triggered (onPress
, onSubmit
, onScroll
) is perfectly fine. In fact, it’s often preferred for handlers tied to specific events.
However, as functionality grows and the same logic needs to run in different contexts, consider transitioning to names that describe what the function actually does.
The Takeaway
It’s okay to start with “when it’s called” names. Just be open to renaming functions as their use evolves. Let function names reflect their true purpose, making your code easier to read and reuse.
Top comments (0)