Should returning false rather than throwing an exception be better behaviour?
See original GitHub issueThe code looks very good, but I think it is more useful if ‘IsDefinedFast(string states)’ returns false rather than throwing an exception. This means that if the string is not defined in the enum collection and we get back ‘false’ and can act on that in the if statement.
Here is my example:
// currently throws an exception (would be better if it returned false)
if (UserTypeTestEnumExtensions.IsDefinedFast("Gien"))
{
System.Console.WriteLine("'Gien' is defined");
}
else
{
System.Console.WriteLine("Not defined is 'Gien'");
}
Here is the pseudo code for what I am suggesting:
public static bool IsDefinedFast(string states)
{
return states switch
{
nameof(UnitTests.UserTypeTest.Men) => true,
nameof(UnitTests.UserTypeTest.Women) => true,
nameof(UnitTests.UserTypeTest.None) => true,
_ => false
};
}
This is only for this specific scenario that I suggest returning false.
What do you think?
Issue Analytics
- State:
- Created a year ago
- Reactions:2
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Function returning true/false vs. void when succeeding and ...
Therefore, deciding between throw and return requires other criteria. Throwing exceptions should often be avoided if it endangers the efficiency ...
Read more >Should I throw an exception or return false?
As informally agreed, whenever you use TryXXXX pattern, your method must be always successful, but return actual success result as boolean.
Read more >Should I throw an exception or return a boolean? : r/java
The first form is fine, you're making sure your arguments are valid and throwing a runtime exception if they're not. If you're passing...
Read more >Safe PHP: throwing exceptions instead of returning false
For historic reasons, the PHP core functions return false on failure instead of throwing exceptions. Let's see how we can fix this!
Read more >Clean Code and the Art of Exception Handling
Rather than fearing exceptions, we should embrace them and learn how to use them to make our code ever better, cleaner, and more...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I have tried 1.0.13 out. It works perfectly. Thanks again for making this change.
Yes, the version is finalized in 1.0.13. There should be no problem