Slide 1

Slide 1 text

CODE SMELLS IN ELIXIR CODE BEAM EU 2023

Slide 2

Slide 2 text

ELAINE NAOMI WATANABE twitter.com/elaine_nw speakerdeck.com/elainenaomi linkedin.com/in/elainenaomi B.Sc. in Computer Engineering M.Sc. in Computer Science Senior Software Engineer @ TheRealReal Yesterday 11°C Berlin Germany GMT+2 Last Saturday 23°C São Paulo Brazil GMT-3

Slide 3

Slide 3 text

https://speakerdeck.com/elainenaomi

Slide 4

Slide 4 text

CODE SMELLS

Slide 5

Slide 5 text

Code smells are sub-optimal design choices that can degrade different aspects of code quality Yamashita, Aiko, and Steve Counsell. "Code smells as system-level indicators of maintainability: An empirical study." Journal of Systems and Software 86.10 (2013): 2639-2653.

Slide 6

Slide 6 text

They are indicators of software design flaws that could potentially affect maintenance Yamashita, Aiko, and Steve Counsell. "Code smells as system-level indicators of maintainability: An empirical study." Journal of Systems and Software 86.10 (2013): 2639-2653.

Slide 7

Slide 7 text

Alternative Classes with Different Interfaces Loops Lazy Element Speculative Generality Temporary Field Message Chains Middle Man Insider Trading Large Class Data Class Refused Bequest Comments Mysterious Name Duplicated Code Long Function Long Parameter List Global Data Mutable Data Divergent Change Shotgun Surgery Feature Envy Data Clumps Primitive Obsession Repeated Switches 2018

Slide 8

Slide 8 text

REFACTORING

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

https://martinfowler.com/books/refactoring.html https://en.wikipedia.org/wiki/Code_refactoring REFACTORING A controlled technique for improving the design of an existing code base.

Slide 11

Slide 11 text

Small behavior-preserving transformations

Slide 12

Slide 12 text

CATALOG OF REFACTORINGS Replace Inline Code with Function Call Replace Loop with Pipeline Replace Nested Conditional with Guard Clauses Replace Parameter with Query Replace Primitive with Object Replace Query with Parameter Replace Subclass with Delegate Replace Superclass with Delegate Replace Temp with Query Replace Type Code with Subclasses Separate Query from Modifier Slide Statements Split Loop Split Phase Split Variable Substitute Algorithm Change Function Declaration Change Reference to Value Change Value to Reference Collapse Hierarchy Combine Functions into Class Combine Functions into Transform Consolidate Conditional Expression Decompose Conditional Encapsulate Collection Encapsulate Record Encapsulate Variable Extract Class Extract Function Extract Superclass Extract Variable Hide Delegate Inline Class Inline Function Inline Variable Introduce Assertion Introduce Parameter Object Introduce Special Case Move Field Move Function Move Statements into Function Move Statements to Callers Parameterize Function Preserve Whole Object Pull Up Constructor Body Pull Up Field Pull Up Method Push Down Field Push Down Method Remove Dead Code Remove Flag Argument Remove Middle Man Remove Setting Method Remove Subclass Rename Field Rename Variable Replace Command with Function Replace Conditional with Polymorphism Replace Constructor with Factory Function Replace Derived Variable with Query Replace Function with Command https://refactoring.com/catalog/ 2018

Slide 13

Slide 13 text

Identify a code smell To fix now? Apply refactoring Run tests Yes No Finish

Slide 14

Slide 14 text

HISTORY 💾

Slide 15

Slide 15 text

22 Code smells 72 Refactoring techniques 1999

Slide 16

Slide 16 text

Mainly focused on object-oriented programming languages

Slide 17

Slide 17 text

So, is it not an issue for functional programming languages?

Slide 18

Slide 18 text

So, is it not an issue for functional programming languages?

Slide 19

Slide 19 text

OOP + FP 2018 18+ years later 24 code smells 61 refactoring techniques

Slide 20

Slide 20 text

Erlang/OTP Code Smells

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

Elixir Code Smells

Slide 23

Slide 23 text

Prof. Marco Tulio Valente Prof. Lucas Francisco da Matta Vegi Federal University of Minas Gerais (UFMG) Belo Horizonte, Minas Gerais, Brazil

Slide 24

Slide 24 text

https://homepages.dcc.ufmg.br/~mtov/pub/2022-icpc-era.pdf

Slide 25

Slide 25 text

Elixir Brasil: Code Smells, Refactoring and Elixir (in Portuguese) https://www.youtube.com/watch?v=3-1PCurON4Q https://speakerdeck.com/elainenaomi/elixir-brasil-2020-code-smells-refactoring-e-elixir One of my talks was part of the data sources analyzed in the grey literature review

Slide 26

Slide 26 text

https://homepages.dcc.ufmg.br/~mtov/pub/2023-emse-code-smells-elixir.pdf

Slide 27

Slide 27 text

The Elixir Community Contribution https://doi.org/10.1007/s10664-023-10343-6

Slide 28

Slide 28 text

https://github.com/lucasvegi/Elixir-Code-Smells

Slide 29

Slide 29 text

https://doi.org/10.1007/s10664-023-10343-6

Slide 30

Slide 30 text

CODE SMELLS IN ELIXIR

Slide 31

Slide 31 text

TRADITIONAL CODE SMELLS

Slide 32

Slide 32 text

EXAMPLE #1 Duplicated Code

Slide 33

Slide 33 text

defmodule ShoppingCart do def calculate_shipping(zip_code, subscription) do if (Enum.member?([3, 4], subscription.id)) do 0 else 10.0 * Location.calculate(zip_code) end end def apply_discount(total, subscription) do if (Enum.member?([3, 4], subscription.id)) do total * 0.9 else total end end end

Slide 34

Slide 34 text

defmodule ShoppingCart do def calculate_shipping(zip_code, subscription) do if (Enum.member?([3, 4], subscription.id)) do 0 else 10.0 * Location.calculate(zip_code) end end def apply_discount(total, subscription) do if (Enum.member?([3, 4], subscription.id)) do total * 0.9 else total end end end Duplicated business rule

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

Rewriting with pattern matching…

Slide 37

Slide 37 text

defmodule ShoppingCart do def calculate_shipping(_zip_code, %{id: 3}), do: 0.0 def calculate_shipping(_zip_code, %{id: 4}), do: 0.0 def calculate_shipping(zip_code, _), do: 10.0 * Location.calculate(zip_code) def apply_discount(total, %{id: 3}), do: total * 0.95 def apply_discount(total, %{id: 4}), do: total * 0.9 def apply_discount(total, _), do: total end

Slide 38

Slide 38 text

defmodule ShoppingCart do def calculate_shipping(_zip_code, %{id: 3}), do: 0.0 def calculate_shipping(_zip_code, %{id: 4}), do: 0.0 def calculate_shipping(zip_code, _), do: 10.0 * Location.calculate(zip_code) def apply_discount(total, %{id: 3}), do: total * 0.95 def apply_discount(total, %{id: 4}), do: total * 0.9 def apply_discount(total, _), do: total end Enum.member?([3, 4], subscription.id) Duplicated business rule

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

Applying a refactoring…

Slide 41

Slide 41 text

defmodule Subscription do defstruct [:id, :shipping_tax, :discount_rate] def available_subscriptions do [ %Subscription{id: 3, shipping_tax: 0.0, discount_rate: 0.95}, %Subscription{id: 4, shipping_tax: 0.0, discount_rate: 0.9} ] end end Encapsulating the rules, centralizing them in one single place

Slide 42

Slide 42 text

defmodule ShoppingCart do def calculate_shipping(_zip_code, %{id: 3}), do: 0.0 def calculate_shipping(_zip_code, %{id: 4}), do: 0.0 def calculate_shipping(zip_code, _), do: 10.0 * Location.calculate(zip_code) def apply_discount(total, %{id: 3}), do: total * 0.95 def apply_discount(total, %{id: 4}), do: total * 0.9 def apply_discount(total, _), do: total end

Slide 43

Slide 43 text

defmodule ShoppingCart do def calculate_shipping(_, %Subscription{shipping_tax: shipping_tax}), do: shipping_tax def calculate_shipping(zip_code, _), do: 10.0 * Location.calculate(zip_code) def apply_discount(total, %Subscription{discount_rate: discount_rate}), do: total * discount_rate def apply_discount(total, _), do: total end Now, the subscription type is transparent for this module

Slide 44

Slide 44 text

EXAMPLE #2 Long Parameter List

Slide 45

Slide 45 text

defmodule User do def create_user( name, email, password, username, status, active?, admin? ) do # ... end end

Slide 46

Slide 46 text

defmodule User do def create_user( name, email, password, username, status, active?, admin? ) do # ... end end

Slide 47

Slide 47 text

Applying a refactoring…

Slide 48

Slide 48 text

defmodule User do def create_user( name, email, password, username, status, active?, admin? ) do # ... end end

Slide 49

Slide 49 text

defmodule User do def create_user(user) do # ... end end It can be a map %{}

Slide 50

Slide 50 text

defmodule User do def create_user(%User{} = user) do # ... end end or a new struct :)

Slide 51

Slide 51 text

defmodule User do def create_user(%User{} = user) do # ... end end new_user = %User{ name: "Elaine", email: "[email protected]", password: "123", username: "elainenaomi", status: 1, active?: true, admin?: false } User.create_user(new_user)

Slide 52

Slide 52 text

ELIXIR-SPECIFIC CODE SMELLS

Slide 53

Slide 53 text

EXAMPLE #1 Using exceptions for control-flow

Slide 54

Slide 54 text

defmodule Report do def print_status(value) do if is_integer(value) do #... "Result..." else raise RuntimeError, message: "Invalid argument. It is not integer!" end end end

Slide 55

Slide 55 text

defmodule Report do def print_status(value) do if is_integer(value) do #... "Result..." else raise RuntimeError, message: "Invalid argument. It is not integer!" end end end

Slide 56

Slide 56 text

defmodule Client do # Client forced to use exceptions for control-flow. def status(arg) do try do value = Report.print_status(arg) "All good! #{value}." rescue e in RuntimeError -> reason = e.message "Uh oh! #{reason}." end end end

Slide 57

Slide 57 text

defmodule Client do # Client forced to use exceptions for control-flow. def status(arg) do try do value = Report.print_status(arg) "All good! #{value}." rescue e in RuntimeError -> reason = e.message "Uh oh! #{reason}." end end end

Slide 58

Slide 58 text

Applying a refactoring…

Slide 59

Slide 59 text

defmodule Report do def print_status(value) do if is_integer(value) do #... "Result..." else raise RuntimeError, message: "Invalid argument. It is not integer!" end end end

Slide 60

Slide 60 text

defmodule Report do def print_status(value) do if is_integer(value) do #... {:ok, "Result..."} else {:error, "Invalid argument. It is not integer!" end end end Error Monad

Slide 61

Slide 61 text

defmodule Client do # Client forced to use exceptions for control-flow. def status(arg) do try do value = Report.print_status(arg) "All good! #{value}." rescue e in RuntimeError -> reason = e.message "Uh oh! #{reason}." end end end

Slide 62

Slide 62 text

defmodule Client do # Client forced to use exceptions for control-flow. def status(arg) do case Report.print_status(arg) do {:ok, value} -> "All good! #{value}." {:error, reason} -> "Uh oh! #{reason}." end end end

Slide 63

Slide 63 text

EXAMPLE #2 Complex Extractions in Clauses

Slide 64

Slide 64 text

def drive(%User{name: name, age: age}) when age >= 18 do "#{name} can drive" end def drive(%User{name: name, age: age}) when age < 18 do "#{name} cannot drive" end Extracting values for further usage and pattern/guard checking

Slide 65

Slide 65 text

Applying a refactoring…

Slide 66

Slide 66 text

def drive(%User{age: age} = user) when age >= 18 do %User{name: name} = user "#{name} can drive" end def drive(%User{age: age} = user) when age < 18 do %User{name: name} = user "#{name} cannot drive" end Extracting only pattern/guard-related variables

Slide 67

Slide 67 text

def drive(%User{age: age} = user) when age >= 18 do "#{user.name} can drive" end def drive(%User{age: age} = user) when age < 18 do "#{user.name} cannot drive" end Using dot notation for accessing struct properties

Slide 68

Slide 68 text

Elixir 1.16 will contain the complete catalog of code smells in Elixir They will be called "anti-patterns"

Slide 69

Slide 69 text

https://hexdocs.pm/elixir/main/what-anti-patterns.html

Slide 70

Slide 70 text

Anti-pattern structure Name Unique, To facilitate communication Problem How it can harm code quality What impacts it can have for developers Example Code + textual description Refactoring Suggested changes to improve code quality

Slide 71

Slide 71 text

Anti-pattern structure Name Unique, To facilitate communication Problem How it can harm code quality What impacts it can have for developers Example Code + textual description Refactoring Suggested changes to improve code quality

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

IN PROGRESS

Slide 74

Slide 74 text

Catalog of Refactorings

Slide 75

Slide 75 text

https://homepages.dcc.ufmg.br/~mtov/pub/2023-icsme-nier-elixir.pdf

Slide 76

Slide 76 text

Elixir Community ++ Research with Elixir

Slide 77

Slide 77 text

https://github.com/lucasvegi/Elixir-Refactorings

Slide 78

Slide 78 text

Slide 79

Slide 79 text

WHAT'S NEXT?

Slide 80

Slide 80 text

Tooling

Slide 81

Slide 81 text

Not all code smells are detectable by automating tools

Slide 82

Slide 82 text

hexdocs.pm/credo Improving

Slide 83

Slide 83 text

Developer’s experience and system’s knowledge play an important role in the identification of some smells. F. Palomba, G. Bavota, M. Di Penta, R. Oliveto and A. De Lucia, "Do They Really Smell Bad? A Study on Developers' Perception of Bad Code Smells," 2014 IEEE International Conference on Software Maintenance and Evolution, Victoria, BC, Canada, 2014, pp. 101-110, doi: 10.1109/ICSME.2014.32.

Slide 84

Slide 84 text

A.I.? GH Copilot ChatGPT etc.

Slide 85

Slide 85 text

Metrics?

Slide 86

Slide 86 text

Cyclomatic complexity

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

ABC Software Metric

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

WRAPPING UP

Slide 91

Slide 91 text

History Traditional and Elixir-specific code smells Impact of code smells over time Refactoring techniques

Slide 92

Slide 92 text

Code smells != Bugs

Slide 93

Slide 93 text

Code smells → Potential design flaws

Slide 94

Slide 94 text

It's about the impact on the software maintenance and evolvability

Slide 95

Slide 95 text

Understability and changeability matter

Slide 96

Slide 96 text

Understability and changeability matter If you'd like to scale your team

Slide 97

Slide 97 text

Understability and changeability matter If you wish to take time off :)

Slide 98

Slide 98 text

Research indicates that almost 60% of programmers’ time is spent understanding code, rather than writing code. From The Programmer's Brain - Felienne Hermans

Slide 99

Slide 99 text

Automated tests + Refactoring =

Slide 100

Slide 100 text

https://martinfowler.com/bliki/TestCoverage.html

Slide 101

Slide 101 text

https://martinfowler.com/articles/practical-test-pyramid.html

Slide 102

Slide 102 text

To keep in mind: you don't need to fix ALL code smells

Slide 103

Slide 103 text

No content

Slide 104

Slide 104 text

Prefer duplication over the wrong abstraction Sandi Metz https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction

Slide 105

Slide 105 text

Refactoring != Revolution

Slide 106

Slide 106 text

It's all about accumulative improvements

Slide 107

Slide 107 text

https://martinfowler.com/bliki/DesignStaminaHypothesis.html design payoff line no design good design cumulative functionality time

Slide 108

Slide 108 text

Developer productivity Product evolvability Quality of end-product Self-improvement etc "Do developers care about code smells? An exploratory survey" A. Yamashita and L. Moonen, 2013 doi: 10.1109/WCRE.2013.6671299.

Slide 109

Slide 109 text

#

Slide 110

Slide 110 text

Legacy code in Elixir

Slide 111

Slide 111 text

How is your codebase in Elixir?

Slide 112

Slide 112 text

Is it EASY TO CHANGE?

Slide 113

Slide 113 text

speakerdeck.com/elainenaomi elainenaomi.dev Muito obrigada illustrations from undraw.co translation: thank you so much! Don't forget to check and participate in the discussions about the catalog of refactorings