4

I have the below method, which I need to check for whether the arguments are empty or null.

    public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
    {
        _Where = " WHERE " + field + " " + operat + " @" + field + "1 " + andOr + " " + field2 + " " + operat2 + " @" + field2 + "2 ";
        _Params.Add(field + "1", value);
        _Params.Add(field2 + "2", value2);
        return this;
    }

I have found the string.IsNullOrWhiteSpace method however this would require this much code:

                   if (string.IsNullOrWhiteSpace(field))
            throw new ArgumentException("field Cannot be null or be empty");

        if (string.IsNullOrWhiteSpace(operat))
            throw new ArgumentException("operat Cannot be null or be empty");

        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException("value Cannot be null or be empty");

        if (string.IsNullOrWhiteSpace(andOr))
            throw new ArgumentException("andOr Cannot be null or be empty");

        if (string.IsNullOrWhiteSpace(field2))
            throw new ArgumentException("field2 Cannot be null or be empty");

        if (string.IsNullOrWhiteSpace(operat2))
            throw new ArgumentException("operat2 Cannot be null or be empty");

        if (string.IsNullOrWhiteSpace(value2))
            throw new ArgumentException("value2 Cannot be null or be empty");

Is there any way of shortening this?

Also, I have tried creating a custom method for this task, however it throws an exception in the custom method instead of the Where() method which makes it tricky to debug.

6
  • You could create a static metod: ValidateParameterNotEmpty(string name, string value). You would reduce the number of lines to 1/3 Commented Mar 5, 2016 at 17:06
  • The validation you will need to do to prevent SQL injection will be a lot more work so I would make this second priority. Commented Mar 5, 2016 at 17:07
  • 2
    If the field is null or empty, nothing will appear when throwing ArgumentException your way. Did you mean to use nameof? Commented Mar 5, 2016 at 17:07
  • I did actually try something like that but found when it threw the exception the debugger went to the method ValidateParameterNotEmpty() instead of the Where() method. Of course, if I use that method in multiple places it could make it tricky to debug. @xanatos Commented Mar 5, 2016 at 17:10
  • @GediminasMasaitis yes sorry that's a mistake. Although I don't believe I can use nameof() as I am not using c#6. I will amend it to what I now have. Commented Mar 5, 2016 at 17:19

5 Answers 5

7

You could check the value one by one or creating intermediate function to do that.

Alternatively, my suggestion is: you could put all the inputs in an array and use LINQ Any to check all of them at once:

public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
{
    string[] inputs = {field, operat, value, andOr, field2, operat2, value2}
    if (inputs.Any(x => string.IsNullOrWhiteSpace(x))){
        //throw exception
    }
    //continue with your method, all inputs are OK
}
Sign up to request clarification or add additional context in comments.

1 Comment

very interesting method . wp
1

What I can suggest is this:

private string _nullChecker(string _value){
   if (string.IsNullOrWhiteSpace(_value))
            throw new ArgumentException(_value + "Cannot be null or be   empty");
   return _value;
}

then, in your Where string statement

_Where = " WHERE " + _nullChecker(field) + " " + __nullChecker(operat) + " @" + _nullChecker(field) + "1 " + _nullChecker(andOr) + " " + _nullChecker(field2) + " " + _nullChecker(operat2) + " @" + _nullChecker(field2) + "2 ";

Not sure with this though. Haven't checked it with actual code. :) Hope this helps

1 Comment

Or it might be an extension method.
0

You could do this:

int? GetLength(string s) {
    return s == "" ? -1 : s?.Length;
}

// s1, s2 and so on are your parameters
int? lengthSum = GetLength(s1) + GetLength(s2); // and so on
int wholeLength = (s1 + s2).Length; // and so on
if(lengthSum == wholeLength) {
    // No parameter is null or empty
}

Comments

0

Firstly, you can use simple libraries to do argument validation. Check out this one called Argument Validator, which has handy functions that will reduce your overall code by half.

Here is an example on how you could do it using the argument validator library:

public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
{
    var inputs = new string[] {field, operat, value, andOr, field2, operat2, value2};
    foreach(var input in inputs)
    {
        Throw.IfNullOrEmpty(input, nameof(input)));
    }
}    

Comments

0

I think I found a "branch" of what your are doing. There is less code below to check and the error is thrown within the function.

There is a great article of Adam Storr about arguments' checking here

For the lazy one you will find a use of extension methods, permitting to check argument in one line inside a try/catch.

It allows to check independently all arguments, and give a customed feedback

public returnType MyFunction(string arg1, string arg2, int arg3)
{
    try
    {
        // Check that the arguments are not null or empty
        _ = arg1.Valid() ?? throw new ArgumentNullException("Argument 1 not valid");
        _ = arg2.Valid() ?? throw new ArgumentNullException("The argument 2 must be provided");
        _ = arg3.Valid() ?? throw new ArgumentNullException("I need arg3 to work");
    }
    catch(ArgumentNullException)
    {
    //Treat the error
    }

And the implementation of the .Valid() method takes place in another files place wherever you want (stored in a TypeExtension file in this case) :

 public static class TypeExtensions
    {
        /// <summary>
        /// String method extension that return null if the string is null or empty.<br/>
        /// Otherwise return the value itself
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object Valid(this string value)
        {
            return (!string.IsNullOrWhiteSpace(value)) ? value : null;
        }

        /// <summary>
        /// int method extension that return null if the int is null or 0 <br/>
        /// Otherwise return the value itself
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object Valid(this int? value)
        {
            if (value is null or 0)
                return null;
            else
                return value;
        }
    }

So the argument inherit of the method Valid() by its type. The "null-coalescing operator" (??) means "if the value is null give what is next" The discard "_" means that no matter what is return it won't be stored in the memory.

So with the association of both you can check the argument, and if the check return null, throw an exception.

It is for the twisted mind I agree, but I didn't find a "cleaner" way so far. Maybe with decorator ?

I hope it might help !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.