Pattern matching confusion

When I have a function like this:

def foo(bar) do
  if bar do
    "conditional processing"
  end

  "general processing"
end

it can be refactored to

def foo( %{condition} = bar) do
  "conditional processing"
  "general processing"
end
def foo(bar) do
  "general processing"
end

Now, I don’t like that I have to change “general processing” in two places, so I can put it in a function:

def foo( %{condition} = bar) do
  "conditional processing"
  general_processing()
end
def foo(bar) do
  general_processing()
end
def general_processing() do
  "general processing"
end

Problem is now there are 3 functions instead of 1, and sometimes there is only one line to put in the third function.

My ideea is to mark somehow blocks of code that are twins. Modifying in one, will change the second too:

def foo( %{condition} = bar) do
  "conditional processing"
  "general processing" #marked-345234
end
def foo(bar) do
  "general processing" #marked-345234
end

How the marking would be done I don’t know. It might need the possibility to see all the marks at some point. This markings can be seen as hidden functions.

So what about this idea?

Why not move conditional processing into a separate function instead of general processing? That way the shared logic (general) is written once, and the conditional – as many times as there are conditions, hopefully without any other repetitions.

def foo(bar) do
  conditional_processing(bar)
  "general processing"
end

def conditional_processing(%{condition: condition} = bar) do
  # ...
end
def conditional_processing(_bar), do: nil

So what about this idea?

It could be done as an extension to an IDE (like “change all in scope” in xcode 9), but I doubt it should be implemented into the language.

3 Likes

Oh so this is how pattern matching is done :)) I was doing it the other way around.

2 Likes