Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finish function higher in hierarchy

Tags:

c#

I am tired of writing:

if(objectA!=null) 
return;

or:

if(objectB==null) 
return;

So I was hope to shorten this snippet, to something like this:

Returns.IfNull(objectA);

it is pretty match the same length but usually there are few objects to check and adding params as parameter can shorten:

if(objectA==null || objectB!=null || objectC!=null) 
return;

to:

Returns.IfNull(objectA,objectB,objectC);

Basically function IfNull have to get access to function one step higher in stack trace and finish it. But that's only idea, I don't know if it's even possible. Can I find simililar logic in some lib?

like image 325
Twelve Avatar asked Jul 19 '11 20:07

Twelve


2 Answers

No, you are essentially asking the function to exit the function higher than itself which isn't desirable nor really possible unless you throw an exception (which isn't returning per se).

So, you can either do your simple and concise if-null-return checks, or what you may want to do there instead is to throw a well defined exception, but I don't recommend exceptions for flow-control. If these are exceptional (error) circumstances, though, then consider throwing an ArgumentNullException() and handling it as appropriate.

You could write some helper methods to throw ArgumentNullException() for you, of course, to clean it up a bit:

    public static class ArgumentHelper
    {
        public static void VerifyNotNull(object theObject)
        {
            if (theObject == null)
            {
                throw new ArgumentNullException();
            }
        }

        public static void VerifyNotNull(params object[] theObjects)
        {
            if (theObjects.Any(o => o == null))
            {
                throw new ArgumentNullException();
            }
        }
    }

Then you could write:

public void SomeMethod(object obj1, object obj2, object obj3)
{
    ArgumentHelper.VerifyNotNull(obj1, obj2, obj3);

    // if we get here we are good!
}

But once again, this is exceptions and not a "return" of the previous method in the stack, which isn't directly possible.

like image 154
James Michael Hare Avatar answered Sep 18 '22 13:09

James Michael Hare


You are asking for something that only the language designer can fix for you. I have proposed one thing by myself. The .? operator does return from the current method with the default return value when the argument left to it is null.

return appSettings.?GetElementKey(key).?Value ?? "";

Perhaps we will see it some day in C# 6?

like image 26
Alois Kraus Avatar answered Sep 18 '22 13:09

Alois Kraus