Observables are “just functions”, but also collections… How do I name them?
Naming things is hard. Naming things in programming is even harder, IMO. RxJS and observables bring more confusion for some people when it comes to naming because they’re just not sure what to make of them. Observables are a lazy type that, when subscribed to, pushes values at you like a collection. Observables can have side effects, just like functions. Observables might just have side effects, in fact.
In truth, it probably doesn’t matter too much how you name them, as long as you’re consistent, you can understand your code, and perhaps more importantly, your team and/or the person that comes after you can understand your code.
Here are a few rules of thumb I follow:
- Pluralize observables that could give you many values.
- Singular nouns for observables that just give you one value.
score$. Just be aware that the
$on the end (if you’re using Finnish Notation) might be confused as pluralization.
- Add a
maybeprefix in front of observables that might not give you a value at all.
maybeBirds$, you get the idea. If the observable might complete before it gives you a value, put a
- If the observable is all about the side effect, name it like you might name a function. Give it a verb and noun combination that describes what it’s doing, and what it’s doing it to.
updateAccountData$, and so on.
- If the content is ambiguous, name it by intent. For example, if you have an
Observable<number>that is mean to be clock ticks, name it
incrementingNumbers$, that’s just weird and isn’t going to help anyone that comes after you.
- Try not to confuse people.
maybeUpdateAccountData$is probably a no-no if you’re just being a pedant about the word “maybe”. Yes, we all know that your HTTP call might fail resulting in no values. Likewise, don’t name them all like functions because “creating a log on the http server is technically a side-effect”. Just relax. Naming observables is not a science.
$ is OPTIONAL
Finnish Notation is all over the place, but in truth it doesn’t really matter. It might help your team in RxJS-heavy applications as it could avoid ambiguous variable names where you have a
foos$ observable that you’re subscribing to and updating some other
foos variable. If you do postfix with a $, do not include the $ like an “s” for pluralization. I know I’ve done that and advocated it in the past, but I’ve since found it’s confusing.