[erlang-questions] Trouble with Erlang's lenient comparisons

Gordon Guthrie gordon@REDACTED
Wed Apr 13 12:27:34 CEST 2011


> I've inherited someone else's code base; sometimes I forget that a
> function returns a tuple and I up comparing it with an integer or
> similar, and get weird behaviour and hard-to-find bugs as a result.

The key here is always to check return types whenever you call a function.

You should be thinking 'if there is an error how do I make it appear
as quickly as possible?'.

So with function returns you don't want to pass them round in a mush
of generic variables until the error surfaces 20 fn calls from when it
appeared.

Also check for bad input to functions by using guards like:

fun(A, B, C) when is_list(A), is_integer(B), is_record(C, recC) ->

This will force errors to appear quicker if you do have a mushy
untyped variable error.

Always code the happy path and make everything else an error. If a fn
is designed as the second paramter should be an integer and not a
float then use pattern matching/guards to make it so...

Use the dialyzer to pick up cases when you have let this sort of thing
happen, and write specs to tell dialyzer, yourself and your co-workers
you intentions with functions:
http://www.erlang.org/doc/reference_manual/typespec.html

Gordon


On 13 April 2011 10:08, JohnyTex <ekeroth.christoffer@REDACTED> wrote:
> Hello! :)
> I'm a newbie Erlang programmer, and I've really liked my experience so
> far. However, I've made mistakes related to Erlang's type system a
> couple of times now, more specifically the fact that you can compare
> different types with each other without Erlang complaining.
>
> I've inherited someone else's code base; sometimes I forget that a
> function returns a tuple and I up comparing it with an integer or
> similar, and get weird behaviour and hard-to-find bugs as a result.
>
> What's the best way to prevent this? I will try writing some unit
> tests later today with EUnit, and I'm generating PLTs for Dialyzer as
> I write this, but I was wondering if there are any other tools or
> "best practices" that could help me to write more "type safe" code?
>
> Thanks in advance! :)
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>



-- 
Gordon Guthrie
CEO hypernumbers

http://hypernumbers.com
t: hypernumbers
+44 7776 251669



More information about the erlang-questions mailing list