Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use an empty List or make it an Option?

Often my methods have a List parameter that is optional. When I receive a list of items I do something with them, otherwise that parameter is ignored. Here's a trivial example.

scala> def convertToUpper(s: String, appenders: List[String] = List()) {
  (s.toUpperCase :: appenders).mkString(" ")
}

scala> convertToUpper("cory", List("asks", "questions"))
CORY asks questions

But sometimes I wonder if this contract communicates an expectation of a appenders parameter when really it is optional. On the other hand, making appenders an Option[List] adds complexity.

Is it bad practice to avoid use of Option when the parameter is a List and I can just test for emptiness instead of None?

like image 301
Cory Klein Avatar asked Feb 10 '23 14:02

Cory Klein


1 Answers

If an empty list is a valid argument (which it is in your example) and it behaves as None would, then I would recommend not wrapping the list in an option.

I'd say that wrapping it in an option signals that None and List() would be treated differently.

I think it's fairly common for methods that accept lists as argument to behave as a no-op.

like image 60
aioobe Avatar answered Feb 16 '23 04:02

aioobe