Emily

Emily

My First Elixir Module: How Can I Make This Code Cleaner?

Well, after the mess my last project in Python ended up being, I’m committed this time to make the cleanest code possible.

Before I get any bad habits, I’d appreciate a second set of eyes on the code below.

If you see any bad directions I’m going down, or ways to make the code cleaner, I’d really appreciate being set on the right track now.

(See code in full context below.)

How would I make this code cleaner? (Pipeline operator? Recursion maybe?)

def calc_pyramid_prices_percents(prices, initial_percent) do

    total_column_percent = calc_total_column_percent(prices, initial_percent)
    total_pyramid_percent = calc_total_pyramid_percent(total_column_percent)
    [ initial_price | _ ] = prices
    total_distance = calc_total_distance(prices, initial_price)

    Enum.map(prices, fn(price) -> calc_price_percent(price, initial_price, \
        total_distance, initial_percent, total_pyramid_percent) end)
end

Is there a cleaner way to do this?

def calc_max_initial_percent(prices) do
    inverted_prices = Enum.reverse(prices)
    [d] = Enum.take((calc_pyramid_prices_percents(inverted_prices, 0)), -1) # get last price percent.
    d # Return only the number.
end

Do you see any red flags or better coding practices that should have been followed in the code in full context?

defmodule PyramidCalculator do
    @moduledoc """
    Calculates a price percents adding up to 100 that form a pyramid shape
    based on the relative distance of each price point from the initial price point.

    If initial percent is greater then number of prices / 100, an inverted pyramid is returned.

    ## IMPORTANT
    The first price in the price list must be the highest or lowest price in the list.
    List is returned unsorted.  Sort list ascending or descending order before invoking the pyramid calculator.
    """

    @doc """
    Returns a list of percents for each price point that would look like a pyramid
    based on the relative distance of each price point from the initial price point.
    
    ## Examples:

        ## Normal pyramid example:
        iex> prices = [1, 2, 3]
        iex> initial_percent = 10
        iex> PyramidCalculator.calc_pyramid_prices_percents(prices, initial_percent)
        [10.0, 33.33333333333333, 56.666666666666664]

        ## Inverted pyramid example:
        iex> prices = [1, 2, 3]
        iex> initial_percent = 40
        iex> PyramidCalculator.calc_pyramid_prices_percents(prices, initial_percent)
        [40.0, 33.333333333333336, 26.666666666666668]

        ## Asymentrical pyramid price point distances example:
        iex> prices = [1, 3, 7, 22]
        iex> initial_percent = 5
        iex> PyramidCalculator.calc_pyramid_prices_percents(prices, initial_percent)
        [5.0, 10.517241379310345, 21.551724137931036, 62.93103448275862]

    """
    def calc_pyramid_prices_percents(prices, initial_percent) do

        total_column_percent = calc_total_column_percent(prices, initial_percent)
        total_pyramid_percent = calc_total_pyramid_percent(total_column_percent)
        [ initial_price | _ ] = prices
        total_distance = calc_total_distance(prices, initial_price)

        Enum.map(prices, fn(price) -> calc_price_percent(price, initial_price, \
            total_distance, initial_percent, total_pyramid_percent) end)
    end

    @doc """
    Calculates the maximum the initial percent can be so that the final
    price point percent in the prices list is zero.

    ## Examples:

        iex> prices = [1, 2, 3]
        iex> PyramidCalculator.calc_max_initial_percent(prices)
        66.66666666666666

        iex> prices = [5, 10, 15, 20]
        iex> PyramidCalculator.calc_max_initial_percent(prices)
        50.0
    """
    def calc_max_initial_percent(prices) do
        inverted_prices = Enum.reverse(prices)
        [d] = Enum.take((calc_pyramid_prices_percents(inverted_prices, 0)), -1) # get last price percent.
        d # Return only the number.
    end

    @doc """
    Calculates a perfect column-shaped price percents based on number of price points.

    ## Examples:

        iex> prices = [1, 2, 3]
        iex> PyramidCalculator.calc_column_percent(prices)
        33.333333333333336

        iex> prices = [5, 11, 25, 44]
        iex> PyramidCalculator.calc_column_percent(prices)
        25.0
    """
    def calc_column_percent(prices), do: 100 / Enum.count(prices)

    defp calc_total_column_percent(prices, initial_percent), do: Enum.count(prices) * initial_percent
    
    # In case of an inverted pyramid, returns a negative total.
    # Which means pyramid percent will be subtracted from the
    # total column percent rather then added, on the final 
    # price percent calculation.
    defp calc_total_pyramid_percent(total_column_percent), do: 100 - total_column_percent
    
    defp calc_price_percent(price, initial_price, total_distance, \
        initial_percent, total_pyramid_percent) do
     
        ratio = calc_price_pyramid_ratio(initial_price, price, total_distance)  
        price_pyramid_percent = calc_price_pyramid_percent(ratio, total_pyramid_percent)

        initial_percent + price_pyramid_percent
    end

    defp calc_price_pyramid_ratio(initial_price, price, total_distance),  \
        do: abs(price - initial_price) / total_distance

    defp calc_price_pyramid_percent(ratio, total_pyramid_percent), do: ratio * total_pyramid_percent

    defp calc_total_distance(prices, initial_price), do: _sum_distance(prices, initial_price, 0)
    
    defp _sum_distance([], _initial_price, total_distance), do: total_distance
        
    defp _sum_distance( [ price_head | price_tail ], initial_price, total_distance) do
        _sum_distance(price_tail, initial_price, (total_distance + abs(price_head - initial_price)))
    end
end

Most Liked

JEG2

JEG2

Author of Designing Elixir Systems with OTP

I just felt compelled to point out that this is a life long mission. It’s often a worthy road to travel, but don’t be frustrated if you never arrive. The journey’s the important bit.

Also, there are sometimes good reasons to sacrifice clean code. Try not to get to hung up on the path to purity.

:slight_smile:

bbense

bbense

You’ve written a perfectly straightforward translation of a typical procedural language module into Elixir. So as far as that goes I can’t find much to “fix” in the module.

However, there’s a kind of larger problem at the architectural level. The way that I find most useful to design Elixir programs is to think of data and the transformations required on that data. What data needs to be “together” to flow through the program? Where can I cleanly split the data groupings into smaller data groups with their own local transformations?

One of the outcomes of thinking this way is to have modules with a specified purpose and function signatures that follow the pattern of

def transformation( thing_to_transform, data_needed_to_specify_the_transform) 

Function signatures ( or arities ) much higher than 3 or 4 or lots of foo/3, foo/4 functions in a module are a warning sign that you might need to re-think how you’re constructing your code.[1] Without the larger context of the application which uses your module, it’s hard to say for sure, but to me it really feels like there is an abstraction one level above that is needed to clean up this code. Or it could just be me overthinking it, with too much coffee and too much time waiting for S3 to sync.

This is a great post about design in Elixir.

Latest Erlangist Blog Post

One minor last point, you don’t need to start private functions with an underscore. Since
the underscore has special meaning on variable names, I’d encourage you not to use
it elsewhere.

[1]- Or it might mean you’re writing some truly generic functionality like GenServer.

globalkeith

globalkeith

Wise words!

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

We're in Beta

About us Mission Statement