afeygin
afeygin

Reputation: 1283

What to name a variant of a Get() method?

I am developing an API for a repository-like abstraction. I have two methods:

// Throws an exception if object cannot be found
MyObj Get(MyIdType id);

// Returns false if object cannot be found; no exception
bool TryGet(out MyObj obj);

There is a requirement for a third variant: one that returns null if object cannot be found, and does not throw an exception.

// Returns null if object cannot be found; no exception
MyObj ?????(MyIdType id);

I'm stuck as on what to name it. GetOrDefault has been ruled out as confusing. GetIfNotNull has been suggested, but also seems unclear. GetOrNull is the most promising so far.

Does anyone have any other suggestions, or know of any public APIs whose conventions I can follow?

Upvotes: 1

Views: 453

Answers (6)

steve_c
steve_c

Reputation: 6255

I would opt to not have a Get method that behaves differently in two situations. Why not have the Get return null for all cases. Why throw an exception at all?

I would opt to leave it up to user code to throw an exception if a null value is returned, if required.

See this question for further guidance related to when to throw exceptions.

Upvotes: 3

IAbstract
IAbstract

Reputation: 19881

In my opinion, you should stick with:

MyObj Get(MyIdType id);

Instead of throwing an exception here, simply return null. If there is a definite requirement to throw an exception or optionally, null, I would try:

MyObj Get (MyIdType id, bool ReturnDefault = false) // if .net 4

I don't particularly like this option - but sometimes requirements will override what we think feels right or natural.

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

I'd keep only bool TryGetXXXXX(out T value) variant on your interface and provide the rest as extension methods to it. It makes your interface itself very compact, but at the same time as useful as client wants.

Upvotes: 0

phoog
phoog

Reputation: 43046

You could try GetObjectOrReturnDefaultValue or, since you know it's a reference type GetObjectOrReturnNull. It's long and ugly, but it's not ambiguous.

Upvotes: 0

Oded
Oded

Reputation: 499062

How about: GetOrDefault

The ...OrDefault is fairly standard in LINQ.

Upvotes: 1

Connell
Connell

Reputation: 14411

I'd go with GetOrDefault (as you suggested yourself) based on the LINQ extension method FirstOrDefault.

Maybe GetValue and GetValueOrDefault would sound better though.

Upvotes: 2

Related Questions