C# – Method naming with an out parameter

cmethodsnaming

What naming convention should use when I have a method with an out parameter. I want to do this using clean code principles. So is it a good practice to include the name of the out parameter in the method name?

I want to write a couple of methods like this in which I use one of them in another method. And I want to be legibly and understandably by only reading they names.

Example:

public bool TryFindItemNameInNameDomain(out string itemName)

or

public bool TryFindInNameDomain(out string itemName)

Best Answer

For C# you need only look at the conventions already in place within the .NET framework --- specifically the various Parse and TryParse methods.

The int.Parse(string) method throws a FormatException if you pass it a string that cannot be parsed into a 32 bit integer.

The bool int.TryParse(string, out int) method returns false for every input that throws an exception when passed to the int.Parse(string) method.

If your use case falls outside of these bounds, then you don't need to utilize this pattern, and in fact you might confuse other .NET developers who are already accustomed to this pattern.

If you Find something, should it throw an exception or return null when the thing is not found? This, too, depends on the use case.

If you try to find a key within a dictionary and there is no item with that key, it makes sense to throw an exception.

If you attempt to find a record in the database, where your code doesn't have the same level of control as it would with a Dictionary object, then throwing an exception will happen more often. Reserve exceptions for truly exceptional conditions (i.e. stuff that doesn't happen often and your code can't recover from).

If you are trying to find a record from a database or some sort of data store I would say it is more idiomatic to return a null value than throw an exception. If you are really worried about how other programmers might interpret a null pointer, then wrap it in another object that has a boolean property determining whether or not something was found.

A "find" method on a data access object returning a null pointer has never been a mystery to me, even as a novice programmer. I always knew it meant "the thing you tried to find was not found."