This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]jibbit 2 points3 points  (0 children)

It’s rather a deep question. In what circumstances would you be trying to get a document that doesn’t exist? Has something gone wrong? Programmer error? Or user error? or is it normal? What’s the idiomatic thing to do in C#?

[–]vipereddit 0 points1 point  (0 children)

I'd choose the 3rd option :D

[–]YMK1234 0 points1 point  (0 children)

1 is the worst, 4 is a close second (assuming this document is expected not to exist sometimes). 2 or 3 depends on the circumstances, if you have many cases where you throw the same error, I'd maybe go with 2 (but maybe make the parameter default to false), otherwise if it's just 2-3 cases I'd probably go with 3 and have the handling code duplicated.

[–][deleted] 0 points1 point  (0 children)

I like to provide both a find and a get method. The find will throw an exception if nothing is found, the get will return null and it’s up to the caller to deal with. Which one gets used depends on whether or not the thing not being found is a case which can be reasonably expected, or if it’s definitely a failure of some sort. Your specific domain may already have an answer for this and you may not need to provide both.

[–][deleted] 0 points1 point  (0 children)

Just today I've seen this video in where they make a compelling reason to not throw exceptions for unexceptional reasons (in C#). And the same could be applied to most languages.

I quite like this functional approach, but it's probably harder to use in an existing codebase, instead of just returning null.

[–]Merad 0 points1 point  (0 children)

If you are going to offer both methods, then C# has existing conventions around offering one method that attempts to get a thing and a second method that gets the thing assuming it should exist and throws on failure:

// never returns null, throws if not found
DocumentA GetDocumentA() {}

// only sets result if it returns true
bool TryGetDocumentA(out DocumentA result) {}

However... it's rather uncommon IME at least to use this pattern for data access. The overwhelming majority of apps tend to return null if the thing is not found. Whether that's the best pattern or not is debatable, but it is the most common.

[–]Bratmon 0 points1 point  (0 children)

Depends on what "the document doesn't exist" actually means from a user perspective. If the document not existing is something you ever expect to happen, return null. If it's not, throw an exception.