Write Greppable Code
When writing code, strive to ensure that named things can quickly be found by their name. Avoid using interpolation, clever pattern matching, or string assembly to translate names because this makes them harder to find. Be explicit, donβt invent names based on their context.
Why? π
Other teams in the business know only the name of the thing thing, not the implementation. Therefore, using their name means that the implementation is self-documenting, and other engineers can quickly use that name to find where it is used.
Examples π
Ruby π
In this example, assume that there are events generated for a βSign Up Createdβ event. A non-engineering team uses this exact term to inform business decisions.
Do this π
def track(event:)
Analytics.track(event:)
end
track(event: "Sign Up Created")
Not this π
def track(event:)
event_name = event.split(".").last(2).map(&:capitalize).join(" ") # => "Sign Up Created"
Analytics.track(event: event_name)
end
track(event: "membership.sign_up.created")
Javascript π
Donβt use a Regular Expression when a plain ole string will be easier to grep for:
Do this π
const ids = ["nav-desktop-menu-toggle", "nav-mobile-menu-toggle"];
if (ids.indexOf(someElement.id)) {
// ...
}
Not this π
const regex = /#nav-(desktop|mobile)-menu-toggle/;
if (regex.match(someElement.id)) {
// ...
}
HTML class attributes π
Newer versions of CSS allow us to style things based on partial matches of the class name. This should be avoided.
Do this π
div.alert-warning,
div.alert-info,
div.alert-success {
/* styling */
}
Not this π
div[class^="alert-"], div[class*=" alert-"] {
/* styling */
}
Reference π
https://jamie-wong.com/2013/07/12/grep-test/