1

I'm kind of in an impasse here.

Lets say I have module A which exposes some methods returning objets and module B that uses said methods from Module A. Module A will have situations when it will have to return Nothing.

The problem is: Of course I don't want to return Nothing. Many, many books, top-coders and heuristics will tell you. However, the use of exception is not allowed due to massive use of Module A. That would apparently kill performances.

At last, we do not want to use auto-instanciated objet and have to check inside state to know if it's in fact Nothing (like a check-null...)

What would be an alternative for Module A to expose it can return something empty (or nothing) and for everyone using it like Module B to be needed to check such case (like signed exceptions try-catch)?

Any help will be really appreaciated! I'm pretty much out of solution and I want to do something clean that will be able to evoluation without causing unwanted behaviours and errors. Thanks

Xavier Huppé
  • 544
  • 1
  • 4
  • 17
  • 1
    Who says it's wrong to return a null reference? You either return a reference to an object or return a null reference. An alternative is to create a `TryXXX` method with a byref parameter and a boolean return type. – Bjørn-Roger Kringsjå Oct 28 '15 at 20:07
  • *"Of course I don't want to return Nothing. Many, many books, top-coders and heuristics will tell you"* . . . where do you get these books? :o) – T.S. Oct 28 '15 at 20:11
  • Also see this http://stackoverflow.com/questions/12165730/performance-hit-of-checking-for-null – T.S. Oct 28 '15 at 20:23

2 Answers2

1

This is highly opinion based. I personally consider this totally acceptable for method to return nothing

Dim user as MyUser = myClass.GetUser(id)
If user Is Nothing Then 
    ' Do something when GetUser fails to retrieve a user
End If

Other common thing some people prefer to do is to return boolean from every function

Dim user as MyUser 
If Not myClass.GetUser(id, user) Then
    ' Do something when GetUser fails to retrieve a user
End If

Both methods are totally valid and you can use one or another depending on current needs. One thing that less acceptable by anyone, and with good reason, is exception-based programming.

T.S.
  • 18,195
  • 11
  • 58
  • 78
0

The reason why null/nothing is often discouraged is because it forces the clients to null-check, which is a bad practice.

However this depends on case-by-case basis, whether returning Nothing is meaningful to your problem domain.

Another approach, which is more OOP is to use NullObject pattern --- clients can then safely call methods on the returned object without worrying whether it is actually Nothing or not.

Peter Uhnak
  • 9,617
  • 5
  • 38
  • 51