Is it better to use an empty list or "list option" in F#?

Viewed 147

Is there a best practice when using potentially empty lists in domain models in F#? For example, in a todo app, a task could have 0 to N sub-tasks. Which way of modeling this is preferred?

type Task :
    { Name : string
      SubTasks : Task list option }

or

type Task :
    { Name : string
      SubTasks : Task list } //potentially empty

I am very much a beginner, but it seems to me like the business logic can work with either implementation. I would verify there are no sub-tasks by checking the option type or checking the list length for length = 0.

If we add the value of ParentTask : Task option to the Task record type, maybe it is better to make the SubTasks list an option as well?

Thanks!

2 Answers

Only use Task list option if there is a meaningful difference between the values None and Some []. Otherwise you're just adding a redundant possible state that will need to handled everywhere with Option.map etc.

It sounds like there is no difference between these two states in your domain, so you should probably just use Task list.

Related