0

I have a code, which basically validates the input fields by parsing the JSON Into Dict(user_data()). and then checking which fields might have entered wrong and storing into errors

 errors = {}
 for key, value in user_data().items():
    if key in ["value1", "value2"]:
        if validator1(value) == False
              errors[key] = False
    elif key in ["value3", "value4"]:
        if validator2(value) == False
              errors[key] = False
    elif key in ["value5"]:
        if validator3(value) == False
              errors[key] = False
     ..........
     ..........
return errors

Is there a better way to refactor this code, and coding in this manner will it affect maintaining the code in future? Thanks

1 Answer 1

3

You could maintain a dictionary showing which validators apply to which values:

validators = {"value1": validator1, "value2": validator1, "value3": validator2, ...}

And then replace your code with just:

errors = {}
for key, value in user_data().items():
    if validators[key](value) == False
        errors[key] = False
return errors
Sign up to request clarification or add additional context in comments.

4 Comments

suppose there are validators with different number of arguments!! In that case I should have multiple if statements right ?
In that case the question is, what do you need to pass as the other arguments? Presumably they're fixed for a particular key - so in that case your validators dict can have a value like lambda val: validator1(val, theOtherArgument). And you can extract those into named functions if it's easier, particularly if you'll be doing a lot of this.
It worked !! using lambda.Thanks I am unable to get this point And you can extract those into named functions if it's easier Thanks !!
I just meant that if you don't like using lambdas (Python's syntax for anonymous functions is imo rather annoying compared to some other languages) you could define separate functions which do the same job (calling a validator with its own argument and whichever other arguments are needed).

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.