Observables are “just functions”, but also collections… How do I name them?

Ben Lesh
2 min readJun 7, 2018

--

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:

  1. Pluralize observables that could give you many values. accounts$, videos$, cheeses$, etc.
  2. Singular nouns for observables that just give you one value. person$, account$, score$. Just be aware that the $ on the end (if you’re using Finnish Notation) might be confused as pluralization.
  3. Add a maybe prefix in front of observables that might not give you a value at all. maybeData$, maybeBirds$, you get the idea. If the observable might complete before it gives you a value, put a maybe on it.
  4. 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. performBounceAnimation$, addButtonElement$, updateAccountData$, and so on.
  5. 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 clockTicks$, not incrementingNumbers$, that’s just weird and isn’t going to help anyone that comes after you.
  6. 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.

--

--