[Proposal] Defstruct could set read only properties

35 views
Skip to first unread message

Pedro Carvalho

unread,
Oct 25, 2022, 3:52:01 PM10/25/22
to elixir-lang-core
defstruct foo [
:a,
 property: b , fn  x -> a*2 end


when foo[:b] is called  the function would be invoked by overriding the acess operator,
this way you can get more redability in your code than Foo.calculate_b(a) and simply overriding fetch on the module

an.le...@gmail.com

unread,
Oct 27, 2022, 12:03:50 PM10/27/22
to elixir-l...@googlegroups.com
Hey Pedro,

In Elixir, data has no behavior associated with it. Data is just data. Functions are where the behavior is encapsulated. So, a feature like "dynamic access" fields like the one you propose would clash with this core idea. There are also some other issues:
  • Having Foo.calculate_b(a) is also explicit and predictable, compared to having foo[:b] be dynamic.
  • What if you had side-effects in the access function, like changing some state or writing to a file? Then, every call to foo[:b] would perform those side effects implicitly.
  • The particular example you provided wouldn't work, since you can't reliably have function values at compile time (like the fn used there).

Thanks anyways for the proposal!

Andrea

--
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.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/d9b4a1bd-5bc1-48d1-9575-95557e56cc3an%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages