Returning with intention
In the realm of functional programming, a function’s primary aim is to be transparent. By transparent, we mean that the function should not just do what its name implies, but also, its return type should offer a clear contract of what to expect. Let’s dive deep into crafting honest return types in C#.
A seasoned developer knows that a function’s name or signature alone might not depict the entire story. Consider the following:
UserProfile GetUserProfile(int userId);
On the surface, this function seems to promise that it’ll fetch a user profile given a user ID. However, questions linger. What if the user doesn’t exist? What if there’s an error retrieving the profile?
Now consider an alternative:
UserProfile? GetUserProfile(int userId);
By simply introducing ?
to the return type, the function becomes more transparent about its intention. It suggests: I’ll try to fetch a user profile for this ID...