Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private/Protected setters with F#

I have decided to undertake a relatively large project with F# together with MVC4 and Nhibernate.

Now, in C#, my usual practice with ORM's is the have private setters for certain properties (E.g. auto-incremented/identity properties, timestamps, etc). I.e

public class Guide
{
    public int Id { get; private set; }
    public DateTime Created { get; private set; }

    public Guide()
    {
        Created = DateTime.Now;
    }
}

Here id is an "identity column", and the ORM will handle setting its value.

In F# here is what I have so far

type public Guide() =
    member val public Id = 0 with get, set
    member val public Created = DateTime.MinValue with get, set

But the problem I have encountered is that the getters/setters cannot have access modifiers!

I am new with F#, so I would like to know the best way to perform this sort of thing. However, I do not just want to rewrite C# code in F#! I would like to know the correct (functional) approach to this. Maybe use some other construct??

Edit: For NHibernate, replace private with protected in the setters :)

like image 465
Umair Avatar asked Jun 22 '13 18:06

Umair


People also ask

Should setter methods be private?

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.

What will happen if getters and setters are made private?

The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.

Are getters and setters access modifiers?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

Are setters and getters public?

Generally, it getter and setters are made public to provide acess to other classes.


1 Answers

According to the Properties (F#) page on MSDN, you can have access modifiers on your getters/setters. You can also use different access modifiers for the getter and setter (e.g., a public get and a private set).

What you can't do is use difference access modifiers for automatically-implemented properties. So, if you want to use different access modifiers you'll need to manually implement the backing field (with a let) and the getter/setter methods.

like image 123
Jack P. Avatar answered Sep 27 '22 20:09

Jack P.