Reusing Struct for Modules in Elixir

What mechanisms exist to reuse a structure: Define a structure with all the fields of another structure plus some of its own.

I have structures like this:

defmodule VideoView do
  defstruct name: nil, description: nil, video_link: nil, ...
end

defmodule ImagesView do
  defstruct name: nil, description: nil, images: [], ...
end

defmodule Model3DView do
  defstruct name: nil, description: nil, model: nil, ...
end

There are 7 of them. In my UML, they all inherit from View, which has nameand description. I would like all of them to share these common fields, especially if I decide to add or remove a common field, this can be a real pain with the current method.

+4
source share
3 answers

Like others, you have to think twice whether you really have benefited so much from reusing structures.

, . defstruct :

defmodule View do
  @common_fields [name: nil, description: nil]
  def common_fields, do: @common_fields
  defstruct @common_fields
end

View , :

defmodule View do
  def common_fields do
    [name: nil, description: nil]
  end
end

:

defmodule VideoView do
  defstruct View.common_fields ++ [video_link: nil, ...]
end

defmodule ImagesView do
  defstruct View.common_fields ++ [images: [], ...]
end

defmodule Model3DView do
  defstruct View.common_fields ++ [model: nil, ...]
end
+10

, 1. , , , . Elixir __struct__/0, .

, , , , .

use OtherModule

, .

Elixir - , . . .

, , , . -

defstruct other_module: struct(Other_Module), foo: nil , bar: 1 

Elixir - , , .

+2
  • Struct:

. , . , . .

. , .

  1. :

. . . FP , .

:

defmodule FReuseExample do
   def func1 do
      IO.puts "func1"
   end

   def func2 do
      IO.puts "func2"
   end

   def my_varying_func(f) do
      f.()
   end
end

:

FReuseExample.my_varying_func(&FReuseExample.func1/0)

, , func2, :

FReuseExample.my_varying_func(&FReuseExample.func2/0)

The fact is that I do not need an inheritance hierarchy. I can just pass the behavior that I need as a parameter to the function. The original goal of inheritance was to change the behavior according to the more specific type that was used. If I can go into the behavior directly, I no longer need inheritance to get this.

+1
source

Source: https://habr.com/ru/post/1609497/


All Articles