When writing a private method that has no need to access other members of the same class, how do you choose between private member and let binding?
let
bindings in a class are private. The main difference I think of between let
and a private member
are that let
bindings cannot be overloaded, and are called with name()
rather than this.Name()
. As such, I think it's a mostly stylistic choice.
let
bindings cannot be accessed through the class instance but private method
can. For examples:
type A() =
let someUtil() = "util code"
member private this.AnotherUtil() = "anotherUtil"
member private this.DoSomething() =
let anotherA = A()
A.someUtil() // compilation failed
A.AnotherUtil() // ok
The relevant portion of the spec is section 8.6.2. It states:
The compiled representation used for values declared in “let” bindings in classes is either:
A value that is local to the object constructor (if the value is not a syntactic function, is not mutable and is not used in any function or member).
An instance field in the corresponding CLI type (if the value is not a syntactic function, but is used in some function or member).
A member of the corresponding CLI type (if the value is a syntactic function).
Also:
Non-function let-bindings that are not used in either the members of a type or a function binding are optimized away and become values that are local to the resulting CLI constructor. Likewise, function bindings are represented as instance members.
I prefer let
bindings to private members because they're more "functional," i.e., they emphasize "what" over "how." The compiler takes care of the optimal compiled form.