[erlang-questions] Idiomatically handling multiple validation checks

Technion technion@REDACTED
Tue Dec 6 06:56:59 CET 2016


Hi,


Someone who's written more could well point out this is heresy but I find verify* functions very convenient to write if I make them an Erlang assertion. eg:


isone(A)->
    A = 1.
istwo(A) ->
    A = 2.


Compare that with a case A of.. for each function. Much more complex verifies still work very well with a binary pattern match. Then I can write a verify like this:


verify(Data) ->

    try
        isone(Data),
        istwo(Data) % As many verify functions as needed here
    of
        _ -> true
    catch
        error:{badmatch, _} -> false
    end.


________________________________
From: erlang-questions-bounces@REDACTED <erlang-questions-bounces@REDACTED> on behalf of qp <quantumpotato@REDACTED>
Sent: Tuesday, 6 December 2016 10:16:16 AM
To: Erlang/OTP discussions
Subject: [erlang-questions] Idiomatically handling multiple validation checks

Hi, I am new to Erlang and wrote this code for validating that the Name, Action & Target atoms passed in to validRequest are all valid.

validRequest(valid, valid, Target) ->
  case validName(Target) of
      true -> true;
      false -> false
  end;
validRequest(valid, Action, Target) ->
  case validAction(Action) of
      true -> validRequest(valid, valid, Target);
      false -> false
  end;
validRequest(Name, Action, Target) ->
  case validName(Name) of
      true -> validRequest(valid, Action, Target);
      false -> false
  end.

I've since refactored into

validRequest(Name, Action, Target) ->
  validName(Name) and validAction(Action) and validName(Target).

I'm curious what a more idiomatic way of writing this would be? I've seen a mix of styles using booleans for return values and tuples, with errors listed. I don't think that's needed here but I'm just curious how you would handle multiple validation checks, especially if they were more complicated than this example. Thank you!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20161206/ef166ac1/attachment.htm>


More information about the erlang-questions mailing list