3 ms·
I use this pattern fairly regularly in a variety of ways. Here's a quick piece of example code that might help explain this a bit better. I'm writing this examp
by joshka 8y ago
I use this pattern fairly regularly in a variety of ways. Here's a quick piece of example code that might help explain this a bit better. I'm writing this example in C#, but I usually work in other languages (Java / ruby / Python / JS),
before:
public Student GetStudentById(int id)
{
var record = db.findStudentById(id)
if (record == null) return null;
return new Student(record.id, record.name, ...);
}
Then in say a student record controller class:
public View Get(int id)
{
var student = getStudentById(id);
if (student == null) return View("NotFound");
return View("Display", student);
}
After:
[ContractAnnotation("=> notnull")]
public StudentSearchResult GetStudentById(int id)
{
var record = db.findStudentById(id);
if (record == null) return StudentSearchRsult.NotFound;
return new StudentSearchResult(record.id, record.name, ...);
}
Then:
public View Get(int id)
{
var student = getStudentById(id);
return new View(student.ViewName, student); // look no null check becase student.ViewName is always valid here
}
Note: of course this is entirely simplified for the purposes of example. Perhaps your real world example doesn't return null from the db, but a RecordSet with either 0 or 1 elements. Perhaps your db uses exceptions that you translate into results like this.
The cool thing there is that you get tool support (from e.g. ReSharper) telling your that this is entirely safe to do without a null check and tool support when it's not.
- deleted 8y ago[deleted]
- goto11 8y agoBut then the 'Student' object does not represent a student but represent the result of a search which may or may not be a student, and this result decides its own view. Effectively the model is coupled to a specific view, which seems wrong to me. I would much prefer to have the search return an Option<Student> and then have the controller select the view based on this option. This also makes it explicit that the search may nor return a result, which is not really explicit if it always returns a Student instance.
- joshka 8y agoNote the explicit change to StudentSearchResult over student there to make your last comment kind of a yes, I agree and that was the intent... There are many ways that this can be implemented that avoid an if result != null / == no value, often a map suffices.