I’m working on a prototype to use a document database (currently MongoDB, may change) and found the .NET drivers a bit of a pain, so I thought I would abstract the data access with the Repository pattern. This should make it easy to swap out whatever driver I’m using now (NoRM, mongodb-csharp, simple-mongob) with your killer f# mongodb driver that doesn’t suck when it’s ready.
My question is around the Add operation. This is going to have some side affect to the database and thus subsequent calls to All will be different. Should I care? In C# traditionally I wouldn’t, but I feel that in F# I should.
Here is the generic repository interface:
type IRepository<'a> =
interface
abstract member All : unit -> seq<'a>
// Add has a side-effect of modifying the database
abstract member Add : 'a -> unit
end
And here is how a MongoDB implementation looks:
type Repository<'b when 'b : not struct>(server:MongoDB.IMongo,database) =
interface IRepository<'b> with
member x.All() =
// connect and return all
member x.Add(document:'b) =
// add and return unit
Throughout the app I will use IRepository, making it easy to change drivers and potentially databases.
Calling All is fine, but with Add what I was hoping was instead of returning unit, return a new repository instance. Something like:
// Add has a side-effect of modifying the database
// but who cares as we now return a new repository
abstract member Add : 'a -> IRepository<'a>
The problem is that if I call Get, then Add, the original repository still returns all the documents. Example:
let repo1 = new Repository<Question>(server,"killerapp") :> IRepository<Question>
let a1 = repo1.All()
let repo2 = repo1.Add(new Question("Repository pattern in F#"))
let a2 = repo2.All()
Ideally I want length of a1 and a2 to be different, but they are the same as they both hit the database. The application works, users can ask their question, but the programmer is left wondering why it returns a new IRepository.
So should I be trying to handle the side-effect from Add on the database in the design of the types? How would others go about this, do you use a Repository or some interface class like this or have some better functional approach?
It looks like you’re applying immutability to functions that affect state in the outside world. Regardless of the F# implementation, how would you see this working at the MongoDB level? How would you prevent
repo1from seeing any changes thatrepo2makes? What happens if some other process affects the database — do bothrepo1andrepo2change in this case?To put it another way, imagine an implementation of
System.Consolethat worked like this. IfConsole.Out.WriteLinealways returned a new immutable object, how would it interact with calls toConsole.In.ReadLine?Edit tl;dr: Don’t do this. Sometimes side effects are fine.