In a system where every customer has a unique e-mail address, there is the following code to retrieve the customer id by it's e-mail:
public int? GetCustomerIdByEMail(string? email) {
if(email==null) return null;
return DB.Query<Customer>().Where(c=>c.EMail==email).Select(c=>c.Id).SingleOrDefault();
}
Is it considered bad practice to have the email parameter of type string? (instead of string), given that null is not considered a valid e-mail?
Having code like this spares the user of the code to write
var id = email!=null ? GetCustomerIdByEMail(email) : null
instead he can just write
var id = GetCustomerIdByEMail(email)
But personally I think it is a code smell to handle the null case like this, since null is not considered an e-mail address.
What do you people think about this problem?
Nullable isn't a code smell per se.
nulldoesn't represent wrong value,nullrepresents lack of one. If a lack of an email is a normal situation, then your solution is right.However, the real question is "is lack of an email a normal situation" and most likely the answer is "no". Don't engineer your methods to handle situations they can't handle. Make them require the email. Handle null as an exception one level up. Handling exceptional situations is literally the purpose of exceptions. And the whole point of explicit nullablilty is to get this exception check for free.
The code smell is going against "fail-fast" rule: hiding an error and continuing a code path that has no hope of succeeding.