Coding Style: switch() and Some() variables


#1

Code like this makes me slightly nervous:

let quantity = Some(3);
let price = switch (quantity) {
   | Some(quantity) => Some(float_of_int(quantity) *. 5.95)
   | None => None
};
Js.log(price);

because I am using the same variable name in the switch as in the Some(...) clause. Is it best practice to use the same name, or to use different names?


#2

I don’t see anything wrong with that coding style. The two values are different types, so I don’t think there should be any ambiguity.


#3

Also, if you’re using Belt, another way you could have written this code is:

let quantity = Some(3);
let price = Belt_Option.map(quantity, x => float_of_int(x) *. 5.95);
Js.log(price);

#4

I do that a lot to be honest. Not sure if it’s good either, it might make it harder to read when you come back to your code in a couple of months :confused:
I think when you use Some/None as a replacement for “nullable”, then the same name makes sense.


#5

My two cents: I do this all the time. No problem at all. But we all have our idiosyncrasies!


#6

Exactly, if you buy the whole category-based approach. I guess we’ve yet to see whether it becomes popular with the devs. There’s a lot to adopt as it is.