boddhisattva
Dear Reader,
Greetings! I’ve implemented a solution to a Sales Tax problem using Elixir via this github repo: GitHub - boddhisattva/sales_tax: This is a program that calculates sales tax and prints receipt details as part of a purchase of a set of Items · GitHub. Kindly follow the instructions in the README to get up and running with the app if you’re trying to set this up in your local computer.
I’d consider myself as a beginner level Elixir developer and thereby I’d really appreciate any feedback on how I could improve my solution further.
I’ve attempted to share some of my code related design decisions through this section. It would be great to hear your thoughts on how this code can be further improved in.
I’ve also attempted to add Dialyzer hex package to my code and I get the below results in the output. I’m currently also attempting to understand the Dialyzer output in some more detail as well. If there are any thoughts that you’d like to share based on the below output from the dialyzer hex package with reference to the code on github, I’d be glad to hear your thoughts on this as well.
lib/receipt_csv_parser.ex:15: Invalid type specification for function ‘Elixir.ReceiptCsvParser’:read_line_items/1. The success typing is (binary() | maybe_improper_list(binary() | maybe_improper_list(any(),binary() | ) | char(),binary() | )) -> [any()] lib/receipt_csv_parser.ex:38: Function parse_item/1 has no local return lib/receipt_csv_parser.ex:56: Function update_other_item_details/1 has no local return lib/receipt_csv_parser.ex:59: The call ‘Elixir.Item’:‘imported?’(Vitem@1::#{’ struct ':=‘Elixir.Item’, ‘basic_sales_tax_applicable’:=‘true’, ‘imported’:=‘false’, ‘name’:= , ‘price’:=float(), ‘quantity’:=integer()}) breaks the contract (‘Elixir.Item’) -> boolean() lib/receipt_generator.ex:46: Invalid type specification for function ‘Elixir.ReceiptGenerator’:generate_details/1. The success typing is (atom() | #{‘items’:= , ‘sales_tax’:=float(), ‘total’:=float(), => }) -> ‘ok’ lib/sales_tax.ex:20: Invalid type specification for function ‘Elixir.SalesTax’:main/1. The success typing is ([binary()]) -> ‘ok’ lib/sales_tax.ex:48: The created fun has no local return lib/shopping_cart.ex:33: Invalid type specification for function ‘Elixir.ShoppingCart’:initialize_cart_product/2. The success typing is (number(),atom() | #{‘basic_sales_tax_applicable’:= , ‘imported’:= , ‘name’:= , ‘price’:=number(), ‘quantity’:=number(), => }) -> #{’ struct ':=‘Elixir.Item’, ‘basic_sales_tax_applicable’:= , ‘imported’:= , ‘name’:= , ‘price’:=float(), ‘quantity’:=_} lib/shopping_cart.ex:76: Invalid type specification for function ‘Elixir.ShoppingCart’:update/3. The success typing is (#{‘items’:=[any()], ‘sales_tax’:=number(), ‘total’:=number(), => },atom() | #{‘price’:=float(), ‘quantity’:=number(), => },number()) -> #{‘items’:=[any(),…], ‘sales_tax’:=number(), ‘total’:=float(), => }
Thank you for your time.
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #elixirconf-us
- #ai
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
hlx
After taking a quick look at your code I would suggest you take a look at Decimal for your calculations. You can find many articles on why you should not use Float.
david_ex
You’re not specifying the types and specs correctly. See how you should be doing that here.
For example, in
lib/receipt_csv_parser.exthe spec forread_line_items/1should be@spec read_line_items(String.t) :: list(String.t). The main error of the spec you have isStringdoesn’t mean anything. The string type is given byString.t/0In the same vein,
Itemisn’t a type. You need to define it’s type like this (e.g.):Then, back in
lib/receipt_csv_parser.exyou can fix the spec forimported?/1by making it@spec imported?(Item.t) :: boolean.boddhisattva
Thank you @hlx, I didn’t know about the Decimal Package in Elixir until now . I’m familiar that in Ruby we have something called as Big Decimal Class to deal with such things related to Money.
I’ll definitely take a look at this package in more detail, thank you for bringing that up
boddhisattva
Thank you @david_ex
, I’ve attempted to fix the typespecs in this PR. It would be great if you could review that PR and share your thoughts.
I’m currently still getting 2 more errors with regard to the type specs in
shopping_cart.exwhich I’m finding it difficult to debug. I’m getting the below errors with regard to that file when running the updated type specs with the dialyzer package. Those errors are:Any ideas on what I could be doing wrong here?
Also it feels like there isn’t much detailed documentation how to use typespecs with custom types. Any suggestions on where I could learn more on the best practices to adhere to when using typespecs with custom types would be really helpful. Thank you!
david_ex
For the issue on line 56, dialzyer is telling you what the problem is:
ShoppingCart.initialize_cart_product/2takes anumber/0as the first argument, but you’re giving it the return value ofSalesTaxCalculator.calculate_total_sales_tax/1which is afloat/0per the specs you defined.Regarding the “no local return” error, this often means that the body of the function can raise an error (in which case no return value would be provided). To find out what the issue is, try commenting lines (or replacing them with dummy lines that ensure the types work in your code) to find the line causing triggering the dialyzer issue. Then, either fix your code/specs, or add
no_returnas a possible return value.boddhisattva
Thank you for taking the time out to answer my question @david_ex. It’s an interesting thing what you’ve brought up and I didn’t think that dialyzer would take in to account what we’re returning from
SalesTaxCalculator.calculate_total_sales_tax/1The code for that method looks like below:
This way it could return a Float or a number(i.e., it would return
0). I tried changing the type spec for the above method to:@spec calculate_total_sales_tax(Item) :: numberin this commit and In the ShoppingCart Module I retained things like below:Now both of them have the same type for
total_sales_tax_from_one_itemwhich isnumber. With this, I’m still getting the below error:Any thoughts on what I could be potentially missing? Thank you.
david_ex
Your problem is what dialyzer is telling you: you’re not allowed to call
initialize_cart_product/2with(number(), Item)because the spec says it accepts(number(), input_item()).Indeed, if you look at the definition of
input_item/0in shopping_cart.ex and compare to theitem/0in receipt_csv_parser.ex (which is what you’re passing to initialize the cart product), you’ll see they don’t match (theirpriceandquantitytypes differ).Some general tips:
you should put all of your modules within a top-level namespace unless you have a good reason not to do so (e.g.
Itemshould beSalesTax.Item). Alias them where they’re used if you’re worried about long module names. Otherwise, any project using your code is going to have a conflict if they (e.g.) also define anItemstruct. See here. Note that nothing forces you to do it, but it’s a good convention to follow.you should probably use
String.tinstead ofbinary: they’re the same to analysis tools, butString.tmakes it more obvious what you’re working with.you’re sprinkling typing information all over your code. This makes it hard to understand and (as you’re finding out) hard to maintain.
For your specific case, I would suggest doing this:
Then, everywhere else (e.g. here) use that value in your specs:
If you want to differentiate items before/after processing, you can declare additional “sub-types” in item.ex, e.g.:
boddhisattva
Hi @david_ex ,
Firstly, please accept my sincere apologies for a late response, I got caught up with a few things of late.
Thanks a lot for your time and valuable suggestions
. I finally got a
passed successfullymessage from dialyzer thanks to your inputs. I’ve made the related changes to typespecs as part of this commitI’m completely with you on the naming conventions in terms of adding a top-level namespace and that would definitely prevent conflicts in the future.
It’s a good point that using
String.t()instead ofbinarywould make things more obvious.With regard to your point on sprinkling typing information all over the code. The intention of using typespecs is to make things easier for readers to understand the parameter types and the return types with regard to each function prototype. Do you see potential areas where I could present relevant information with regard to using typespecs without over using it ? I’d really appreciate any specific examples where I could the code more concise on this regard to understand your point more clearly.
Thank you once again for your valuable time and feedback
It definitely helped me to improve my code further.
david_ex
To be clear, I don’t think you can “overuse” types. The problem with your code is that there were several instances of types with the same/similar names and they weren’t properly documented. In fact, the situation was confusing enough that you made mistakes yourself when writing the specs, so it will definitely be confusing for any other programmers.
What I mean is that types are like code. They should ideally mean one specific thing, should exist in one place, and should be documented clearly. So for a given “shape” of data, define a typespec for it in one single place, and have all specs that work with that data “reuse” the typespec by referring to it: don’t declare it again in the same module.
If you need different typespecs for similar but different data (e.g. item before processing VS item after processing), then absolutely declare 2 different types but make sure their names are clear, and they’re properly documented.
boddhisattva
Thanks to your wonderful suggestions @david_ex I’ve been able to gain valuable insights on how do I write better typespecs with regard to my code. I’ve attempted to add all possible changes in this PR based on the discussions that we’ve had through some of the earlier threads on this post.
If you think that there’s still scope for any further improvement to the updated version of how I’ve used typespecs, please do let me know.
Thank you for sharing your experience of how one could use typespecs more efficiently