Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active August 29, 2015 14:05
Show Gist options
  • Save davidallsopp/79fd49840197f3597b72 to your computer and use it in GitHub Desktop.
Save davidallsopp/79fd49840197f3597b72 to your computer and use it in GitHub Desktop.
A demonstration of representing object lifecycle directly in the type system, to avoid the need for nullable references or Options when a value is not really optional; The value is required at one stage in the lifecycle, and should be entirely absent at another stage. This way, we cannot get null pointer exceptions, and we cannot encounter Optio…
package example
import java.util.Date
object NoNulls {
sealed trait Employee // sealed, so nobody else can create further subclasses
object Employee {
def apply(id: Int, name: String, start: Date=new Date()) = CurrentEmployee(id, name, start) // factory method
// Two stages of employment, both private to this object, so can only be created via factory method
case class CurrentEmployee private[Employee] (id: Int, name: String, start: Date) extends Employee {
def terminate() = ExEmployee(id, name, start, new Date())
}
case class ExEmployee private[Employee] (id: Int, name: String, start: Date, end: Date) extends Employee
}
// Create a new current employee
val john = Employee(123, "John Doe")
john.start //> res0: java.util.Date = Wed Aug 20 09:11:53 BST 2014
// john.end -- does not compile; current employee has no end date
// Let them go ;-(
val exjohn = john.terminate()
exjohn.end //> res1: java.util.Date = Wed Aug 20 09:11:53 BST 2014
// john.terminate().terminate() -- does not compile; cannot terminate twice
// Employee.ExEmployee(123, "John Doe", now, now) -- does not compile, can't directly create an ex-employee
}
// PS: it is possible to create both types of employee from an existing employee using the auto-generated copy()
// methods in the case classes. If you wish, you can prevent this by defining your own copy method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment