How do I elegantly check many conditions in Erlang?

前端 未结 4 1812
清歌不尽
清歌不尽 2020-12-23 15:28

So when a user sends a request to register an account, they send their username, password, email, and other info. The registration function must verify all of their data. An

4条回答
  •  悲&欢浪女
    2020-12-23 15:55

    User = get_user(),
    
    Check_email=fun(User) -> not is_valid_email(User#user.email) end,
    Check_username=fun(User) -> is_invalid_username(User#user.name) end,
    
    case lists:any(fun(Checking_function) -> Checking_function(User) end, 
    [Check_email, Check_username, ... ]) of
     true -> % we have problem in some field
       do_panic();
     false -> % every check was fine
       do_action()
     end
    

    So it isn't 5 level deep any more. For real program i guess you should use lists:foldl for accumulate error message from every checking function. Because for now it simple says 'all fine' or 'some problem'.

    Note that in this way add or remove checking condition isn't a big deal

    And for "Is there an equivalent of a return statement..." - look at try catch throw statement, throw acts like return in this case.

提交回复
热议问题