defimpl of a protocol where some functions specific, others common

32 views
Skip to first unread message

Traun Leyden

unread,
Apr 23, 2013, 1:43:45 AM4/23/13
to elixir-l...@googlegroups.com

I have two implementations of the WhizBang protocol:

defimpl WhizBang, for: Foo do

   do_something_specific(foo) do
      # Foo-specific code
   end

   do_something_common(foo) do
      expression1
      expression2
      etc..
   end

end


defimpl WhizBang, for: Bar do

   do_something_specific(bar) do
      # Bar-specific code
   end

   do_something_common(bar) do
      expression1
      expression2
      etc..
   end

end

Is there a recommended way to factor out the code in do_something_common() so it's not duplicated in the various defimpl's?

Currently my plan is to factor this code out into a common "helper" module and delegate the function call to the helper, eg:

do_something_common(foo_or_bar) do
      Helper.do_something_common(foo_or_bar)
end

Or is there a more elegant way?



José Valim

unread,
Apr 23, 2013, 10:07:00 AM4/23/13
to elixir-l...@googlegroups.com
 
Or is there a more elegant way?

This is the only way so far. :)

Dave Thomas

unread,
May 19, 2013, 5:21:41 PM5/19/13
to elixir-l...@googlegroups.com
You can use defdelegate to make it slightly neater:  https://gist.github.com/pragdave/5609055


Dave







--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages