This blog explains the power of “with” statement in Elixir and how it assists the developers to write simple codes
Prior to With Statement, we have to use only If statement /Case statement which is also useful but when it comes to nested If / Case statement, it will be difficult to manage / and complexity increases
The solution to reduce the complexity is With Statement.
We can have multiple sequence of statements within one with statement. It would be easier to explain with an example.
Consider the below example
The first sequence of statement is
The right hand side of the statement will call the function get_admin_user_by_user_id(user_id) and this function will return some values
The returned value of the function get_admin_user_by_user_id(user_id) will be pattern matched with (ok, admin_user). If the pattern is matched then the control is passed on to the next sequence of statement which is as shown below
If the above function Argon2.verify_pass(plain_text_password, admin_user[“password”] passes true then this will be patten matched and if it is a match then it will go to the next statement which is do statement. It will execute the statements given in the do statement
If for any reason, the pattern cannot be matched for any one of the statement, then the contol passes on to else statement and the statements given in the else statement will be executed.
As a pictorial representation below is how the with statement executed