Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose between private member and let binding?

Tags:

f#

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?

  • I tend to use private members because it's easier to change accessibility if required, but are there other aspects to keep in mind when making the choice?
  • Are let bindings compiled as private members (making this only a style choice)?
like image 889
Francesco De Vittori Avatar asked Oct 15 '11 13:10

Francesco De Vittori


3 Answers

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
like image 162
Ruxo Avatar answered Oct 21 '22 13:10

Ruxo


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.

like image 30
Daniel Avatar answered Oct 21 '22 13:10

Daniel


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.

like image 25
Brian Avatar answered Oct 21 '22 13:10

Brian