<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Marinsborg.com</title>
    <description>The latest articles on DEV Community by Marinsborg.com (@marinsborg).</description>
    <link>https://dev.to/marinsborg</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F347818%2F04b3d5d7-f4b2-42f9-baf6-e0e4bd8f4de7.jpg</url>
      <title>DEV Community: Marinsborg.com</title>
      <link>https://dev.to/marinsborg</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/marinsborg"/>
    <language>en</language>
    <item>
      <title>Learn Python functions &amp; create a simple project</title>
      <dc:creator>Marinsborg.com</dc:creator>
      <pubDate>Thu, 12 Jan 2023 20:46:31 +0000</pubDate>
      <link>https://dev.to/marinsborg/learn-python-functions-create-a-simple-project-25f</link>
      <guid>https://dev.to/marinsborg/learn-python-functions-create-a-simple-project-25f</guid>
      <description>&lt;p&gt;Functions are key elements of programming. They are used in most programming languages. &lt;/p&gt;

&lt;p&gt;Functions allow you to break your code into smaller pieces. That way your code is easier to manage and easier to understand. &lt;/p&gt;

&lt;p&gt;Functions also enable you to reuse code in multiple places in your application. That way you save time and make your code easier to read. &lt;/p&gt;

&lt;p&gt;In the first half of this post, we will explain what are Python functions, how to define them, and how to call them. &lt;/p&gt;

&lt;p&gt;In the second part of this post, we will create a small application in which we will use Python functions. That way you can see functions in action.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to define a Python function?
&lt;/h2&gt;

&lt;p&gt;Python function is defined using a keyword &lt;code&gt;def&lt;/code&gt;followed by the name of the function and parentheses. Inside parentheses, you define zero or more arguments. &lt;/p&gt;

&lt;p&gt;Arguments (also called parameters) are inputs that are used inside the function to perform a specific task. &lt;/p&gt;

&lt;p&gt;Let’s show an example of a simple Python function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;subtract&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we defined a function with the name ‘subtract’. That function takes two arguments ‘a’ and ‘b’. Then function subtracts those numbers and saves the result to a variable named result. In the last line, the function returns the result. &lt;/p&gt;

&lt;p&gt;As you can see the code for the function goes inside a block indented under the definition line.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to call a Python function?
&lt;/h2&gt;

&lt;p&gt;Once you have defined a function, you call it by its name and pass the required arguments in the parentheses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;var&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subtract&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;#it would print 5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep in mind that you need to pass the arguments in the same order as in the definition of the function. &lt;/p&gt;

&lt;p&gt;Otherwise, you will get an error or unwanted result. &lt;/p&gt;

&lt;p&gt;Same function with different order of passed arguments:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;var&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subtract&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;#it would print -5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Default values for arguments
&lt;/h2&gt;

&lt;p&gt;Python functions also enable you to define a default value for each argument. &lt;/p&gt;

&lt;p&gt;That way you can call the function without passing that argument and the function will use the default value instead. &lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;say_hi&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;'user'&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s"&gt;"Hi "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;

&lt;span class="n"&gt;sayHi&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Joe"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;#function will return "Hi Joe"
&lt;/span&gt;&lt;span class="n"&gt;sayHi&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;#function will return "Hi user"
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the function ‘say_hi’ takes one argument ‘name’. &lt;/p&gt;

&lt;p&gt;That argument has the default value of ‘user’. &lt;/p&gt;

&lt;p&gt;This function can be called by passing an argument and it will use that value. Also, this function can be called without an argument and it will use the value ‘user’ instead.&lt;/p&gt;

&lt;h2&gt;
  
  
  Simple quiz game
&lt;/h2&gt;

&lt;p&gt;In this part of the post, we will use the knowledge about Python functions from above and create a simple quiz game. &lt;/p&gt;

&lt;p&gt;The quiz game will ask the user multiple questions and keep track of their score.&lt;/p&gt;

&lt;p&gt;First, we'll need to define a list of questions and a list of answers. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;questions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;"What is the capital of France?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"What is the capital of Italy?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"What is the capital of Spain?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"What is the capital of Germany?"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;answers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;"Paris"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"Rome"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"Madrid"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"Berlin"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we'll need to use a loop to iterate through the questions and ask the user for an answer. Here's how to do that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;questions&lt;/span&gt;&lt;span class="p"&gt;)):&lt;/span&gt;
    &lt;span class="n"&gt;question&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;questions&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;answers&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="n"&gt;user_answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;user_answer&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Correct!"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Incorrect. The correct answer is:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Your score is:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;score&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code will ask the user each of the questions in the &lt;code&gt;questions&lt;/code&gt; list and check if their answer is correct by comparing it to the corresponding answer in the &lt;code&gt;answers&lt;/code&gt; list. &lt;/p&gt;

&lt;p&gt;If the user's answer is correct, it will print "Correct!", and if it is incorrect, it will print "Incorrect" and show the correct answer.&lt;/p&gt;

&lt;p&gt;After asking all questions, it will print how many correct answers the player had.&lt;/p&gt;

&lt;p&gt;Now let’s introduce Python functions and make this code more readable.&lt;/p&gt;

&lt;p&gt;First, let’s create a function that will ask a question, take the user’s answer and compare it with the actual answer. &lt;/p&gt;

&lt;p&gt;We also called &lt;code&gt;.lower()&lt;/code&gt; function for the user’s answer and actual answer so we can ignore casing. If we did not do that, the function would return ‘False’ if the user for example typed ‘pARis’.&lt;/p&gt;

&lt;p&gt;The function will return ‘True’ if the user answered right and ‘False’ otherwise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;ask_question_and_check_answer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="s"&gt;"""Asks the user a question and returns True if their answer is correct, False otherwise."""&lt;/span&gt;
    &lt;span class="n"&gt;user_answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;user_answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;user_answer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;user_answer&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the rest of the code, let’s create a new function that will call &lt;code&gt;ask_question_and_check_answer&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_quiz&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;questions&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;answers&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="s"&gt;"""Runs a quiz game with the given questions and answers."""&lt;/span&gt;
    &lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;questions&lt;/span&gt;&lt;span class="p"&gt;)):&lt;/span&gt;
        &lt;span class="n"&gt;question&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;questions&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;answers&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;ask_question_and_check_answer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Correct!"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Incorrect. The correct answer is:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;score&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;run_quiz function&lt;/code&gt; takes a list of questions and a list of answers as input, and uses the &lt;code&gt;ask_question_and_check_answer&lt;/code&gt; function to ask the user each of the questions. &lt;/p&gt;

&lt;p&gt;It keeps track of the user's score and returns the final score when the quiz is finished.&lt;/p&gt;

&lt;p&gt;Let’s also write a function that will print the quiz result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;pretty_print_results&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;score&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="s"&gt;"""Prints the final results of the quiz game."""&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"You scored"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;score&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"out of"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Congratulations! You got a perfect score!"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;total&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.75&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Congratulations! You passed with a high score."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Unfortunately, you did not pass. Better luck next time."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;pretty_print_results&lt;/code&gt; takes a score and a total as input, and prints the final results of the quiz game. You can set parameters for the score any way you like.&lt;/p&gt;

&lt;p&gt;And in the end, you just need to call those two functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Run the quiz and print the results
&lt;/span&gt;&lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;run_quiz&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;questions&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;answers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;pretty_print_results&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;score&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;questions&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There you have it. Simple quiz application that is created with three Python functions. &lt;/p&gt;

&lt;p&gt;Now you can add more questions and answers or if you want a challenge you can find some quiz API and get questions and answers from there. &lt;/p&gt;

&lt;p&gt;The complete solution is &lt;a href="https://github.com/marinsborg/python-functions"&gt;hosted on our GitHub&lt;/a&gt;. Feel free to download it or fork it and play with it. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, we showed what is Python function, how to define one, and how to call it. &lt;/p&gt;

&lt;p&gt;Functions are key elements of programming. They are used in most programming languages.&lt;/p&gt;

&lt;p&gt;Understanding how to define and use functions is an important skill for any programmer.&lt;/p&gt;

&lt;p&gt;If you have any question or suggestion, feel free to post it in the comments or you can find me on &lt;a href="https://twitter.com/marinsborg"&gt;Twitter&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Also if you like the content and want to stay updated on the new content you can &lt;a href="https://marinsborg.com/learn-coding/"&gt;subscribe to my newsletter&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;You will also get a FREE eBook - "learn programming from zero to your first Python program"&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7gd_i1rB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://marinsborg.com/wp-content/uploads/2022/11/3d-book-cover-trimmed.png.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7gd_i1rB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://marinsborg.com/wp-content/uploads/2022/11/3d-book-cover-trimmed.png.webp" width="554" height="869"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>python</category>
      <category>tutorial</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Choose the best programming language to learn first and where to learn them</title>
      <dc:creator>Marinsborg.com</dc:creator>
      <pubDate>Mon, 12 Dec 2022 16:11:41 +0000</pubDate>
      <link>https://dev.to/marinsborg/choose-the-best-programming-language-to-learn-first-beginners-guide-3g49</link>
      <guid>https://dev.to/marinsborg/choose-the-best-programming-language-to-learn-first-beginners-guide-3g49</guid>
      <description>&lt;p&gt;As a beginner in the world of programming, choosing the best &lt;a href="https://marinsborg.com/learn-coding/" rel="noopener noreferrer"&gt;programming language to learn&lt;/a&gt; first can be overwhelming. With so many options available, it's difficult to know how to start.&lt;/p&gt;

&lt;p&gt;Luckily, there is no wrong answer. Every programming language is just a tool. With programming language, you give instructions to a computer to accomplish some task.&lt;/p&gt;

&lt;p&gt;It is the same with cars. A car is also a tool that transport people and card from place A to place B. Can you answer what is the best car? Is it a Lambo? Or Ferrari?&lt;/p&gt;

&lt;p&gt;What if you have four children that you need to drive somewhere? In that case, the best car is a minivan.&lt;/p&gt;

&lt;p&gt;To really choose the best programming language, you need to consider what are your goals with programming. Do you want to have a programming career or is it just a hobby?&lt;/p&gt;

&lt;p&gt;If it is a programming career, then it is a good idea to know what programming language is wanted in your area. Open job boards and check.&lt;/p&gt;

&lt;p&gt;You also need to consider what kind of applications you want to work with. Do you want to make games? Or are you interested in mobile applications? Maybe web applications are your thing. Machine learning is a hot topic these days. There are so many options to choose from.&lt;/p&gt;

&lt;p&gt;But don’t worry, in this post, we will list popular programming languages and where to learn them for free.&lt;/p&gt;

&lt;h2&gt;
  
  
  Python
&lt;/h2&gt;

&lt;p&gt;Python is a popular, versatile language that is known for its simplicity and readability. It is a general-purpose programming language. Python has a large number of libraries that can be used for various branches of the industry.&lt;/p&gt;

&lt;p&gt;It is a very easy language to learn, it uses indentation instead of curly braces and it does not need to use semicolons. Since it is easy to learn, it is often the language of choice of people that are not programmers like scientists, mechanical engineers, accountants, etc. &lt;/p&gt;

&lt;p&gt;It has a large and supportive community, making it a great language for beginners to learn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Used for:&lt;/strong&gt; data science, data visualization, machine learning, task automation, web development (server-side), game development, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources to learn from:&lt;/strong&gt; &lt;a href="https://marinsborg.com/learn-coding/" rel="noopener noreferrer"&gt;Start with our eBook&lt;/a&gt;, &lt;a href="https://automatetheboringstuff.com/" rel="noopener noreferrer"&gt;Automate the boring stuff with Python&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript
&lt;/h2&gt;

&lt;p&gt;JavaScript or JS for short is a popular language that is used to develop interactive web pages or applications. About 97% of pages use JS on the client side to control web page behavior. It is usually used in combination with HTML and CSS for frontend development. &lt;/p&gt;

&lt;p&gt;It also has a large number of libraries that help you easily solve various types of tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Used for:&lt;/strong&gt; frontend web development, backend web development (node.js), game development (browser games), mobile applications (react native), cross-platform desktop applications (electronjs)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources to learn from:&lt;/strong&gt; &lt;a href="https://www.edx.org/course/javascript-introduction" rel="noopener noreferrer"&gt;eDx&lt;/a&gt;,  &lt;a href="https://www.theodinproject.com/paths/full-stack-javascript?" rel="noopener noreferrer"&gt;The Odin Project&lt;/a&gt; - it is a page that offers a full-stack JavaScript path for free. &lt;/p&gt;

&lt;h2&gt;
  
  
  Java
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;(Do not confuse Java with JavaScript, they are not similar at all)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Java is an object-oriented, general-purpose programming language. Java was and still is a pretty popular language mainly because of the Java virtual machine (JVM) that enables to run Java code on many different types of devices.&lt;/p&gt;

&lt;p&gt;It is commonly used for building large-scale, enterprise-level applications. It was also the main programming language to build Android applications until Kotlin become more popular.&lt;/p&gt;

&lt;p&gt;Java has a syntax that is similar to C and C++ but it is not a low-level language as those two are.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Used for:&lt;/strong&gt; web development (server-side) - good for large enterprise applications, desktop applications (Windows and Linux), mobile development (Android apps - however, &lt;a href="https://en.wikipedia.org/wiki/Kotlin_(programming_language)" rel="noopener noreferrer"&gt;Kotlin&lt;/a&gt; is now more popular for Android developers)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources to learn from:&lt;/strong&gt; &lt;a href="https://www.learnjavaonline.org/" rel="noopener noreferrer"&gt;learnjavaonline.org&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Kotlin
&lt;/h2&gt;

&lt;p&gt;Kotlin is a general-purpose, cross-platform programming language that was developed to be used on the Java virtual machine (JVM). It was designed to be a modern and more powerful version of Java, with improved performance and more useful features for developers.&lt;/p&gt;

&lt;p&gt;Because it runs on the JVM, Kotlin code can be used alongside existing Java code and libraries, making it a popular choice for Android app development. Many developers find Kotlin to be more concise and easier to read and write than Java, &lt;strong&gt;making it a good language to learn for beginners&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Used for:&lt;/strong&gt; mobile development (Android apps, but also iOS apps), web development (server-side, similar to Java) &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources to learn from:&lt;/strong&gt; &lt;a href="https://hyperskill.org/tracks/18" rel="noopener noreferrer"&gt;JetBrains Academy&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  C
&lt;/h2&gt;

&lt;p&gt;C# is a general-purpose language that is widely used for building a variety of applications, including web, mobile, desktop, and gaming applications. C# is similar to other popular programming languages like Java. It was developed by Microsoft and in the past, it was mostly used for developing applications for Microsoft systems. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Used for:&lt;/strong&gt; web development (server-side), desktop applications (Windows), game development (Unity), mobile development (Xamarin)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources to learn from:&lt;/strong&gt;  &lt;a href="https://dotnet.microsoft.com/learn/csharp" rel="noopener noreferrer"&gt;Microsoft's official page&lt;/a&gt; - it has a bunch of video tutorials and documentation&lt;/p&gt;

&lt;h2&gt;
  
  
  Golang
&lt;/h2&gt;

&lt;p&gt;Golang, also known as Go, is a programming language that was developed by Google. It is a general-purpose language that is designed to be fast, simple, and easy to use. &lt;/p&gt;

&lt;p&gt;One of the key features of Golang is its support for concurrency, which allows developers to write programs that can easily run multiple tasks at the same time. This makes it well-suited for building systems that need to handle a lot of data or traffic.&lt;/p&gt;

&lt;p&gt;Golang is also known for its strong focus on security and reliability, making it a popular choice for building secure and robust software.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Used for:&lt;/strong&gt; infrastructure, web development (server-side), data science, machine learning&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources to learn from:&lt;/strong&gt; &lt;a href="http://www.golangbootcamp.com/book/" rel="noopener noreferrer"&gt;Golang BootCamp&lt;/a&gt; - book that has everything you need to know to start with Golang&lt;/p&gt;

&lt;h2&gt;
  
  
  Swift
&lt;/h2&gt;

&lt;p&gt;Swift is a programming language that was developed by Apple. It is a modern, powerful language that is used for building a wide range of applications, including iOS, macOS, watchOS, and tvOS apps. &lt;/p&gt;

&lt;p&gt;Swift is known for being fast, easy to use, and safe, with a focus on writing clean, readable code.&lt;/p&gt;

&lt;p&gt;Swift also has a strong focus on performance, making it well-suited for building apps that need to be fast and responsive. Many developers find Swift to be a good language to learn because it is powerful and versatile, yet still easy to understand.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Used for:&lt;/strong&gt; mobile development (iOS) and other apps for Apple hardware&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources to learn from:&lt;/strong&gt; &lt;a href="https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html" rel="noopener noreferrer"&gt;Official documentation&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What would be the best programming language to learn?
&lt;/h2&gt;

&lt;p&gt;If you still can’t decide, don’t worry. We would recommend starting to learn Python. It is a popular, simple, and broadly used programming language. &lt;/p&gt;

&lt;p&gt;You can use Python for your hobby projects and later you can easily find a job if you know it.&lt;/p&gt;

&lt;p&gt;If you change your mind in the future and want to learn some other language, you can do that easily. &lt;/p&gt;

&lt;p&gt;The knowledge that you get learning one programming language can be applied to any other language. If you know how to drive a Ford, you’ll know how to drive Honda.&lt;/p&gt;

&lt;h2&gt;
  
  
  Free eBook and newsletter
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb3fdf2eg2sm5eyzmwlt4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb3fdf2eg2sm5eyzmwlt4.jpg" alt="eBook cover image" width="800" height="517"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you liked this post and want to see more of this, consider subscribing to our newsletter. We only send useful, beginner friendly information and once you subscribe you will get a free eBook that helps you start with programming titled "Learn programming: from zero to your first Python program". &lt;/p&gt;

&lt;p&gt;&lt;a href="https://marinsborg.com/learn-coding/" rel="noopener noreferrer"&gt;You can check all details here.&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>cybersecurity</category>
      <category>learning</category>
    </item>
    <item>
      <title>5 lessons for beginners I learned working 5 years in the industry</title>
      <dc:creator>Marinsborg.com</dc:creator>
      <pubDate>Mon, 16 May 2022 21:03:20 +0000</pubDate>
      <link>https://dev.to/marinsborg/5-lessons-for-beginners-i-learned-working-5-years-in-the-industry-3png</link>
      <guid>https://dev.to/marinsborg/5-lessons-for-beginners-i-learned-working-5-years-in-the-industry-3png</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Five years ago I got my first job. Many things have changed since that. I learned a lot of new things and gained working and career experience. I changed several jobs, met many new people, and work on different kinds of projects. Today I will give you five tips from that period that you can use in your career.&lt;/p&gt;

&lt;h2&gt;
  
  
  Learn concepts, not definitions
&lt;/h2&gt;

&lt;p&gt;After finishing school, university, or boot camp, some people still have that ‘school’ mentality when they start to work. Most of the time, at school, you are learning things to get good grades or to pass an exam. Usually, you forget most things after a few days.&lt;/p&gt;

&lt;p&gt;This is not how you should do at your job. You don’t need to learn definitions or even read everything from documentation or books. You should understand concepts in a more general way so you can apply that knowledge in the future. You will not have any tests and you will not be fired if you don’t know the answers to everything. You will have time to learn about some things that are important for your job.&lt;/p&gt;

&lt;p&gt;When you are reading and learning about some topic you should learn it in a way that you can easily explain that topic to somebody else. Sometimes you will have to make a presentation about your research and explain it to your team or even to the whole company. You can check any tech talk on YouTube to get a general idea about it. &lt;/p&gt;

&lt;h2&gt;
  
  
  Google is your friend
&lt;/h2&gt;

&lt;p&gt;It really is. Everybody is using it. Whatever you don’t know, look that up on Google. Maybe don’t look up your medical symptoms, it will tell you that you are pregnant. &lt;/p&gt;

&lt;p&gt;But seriously, knowing how to use Google is an excellent skill to have and it makes you independent of help from other people. If you are stuck on some task, try to google other people's ideas or check if somebody implemented something similar in another programming language.  &lt;/p&gt;

&lt;p&gt;If your IDE threw you some error message, you should copy it and paste it into Google. There is a high chance that others had the same error and somebody wrote a solution to that. &lt;/p&gt;

&lt;p&gt;There are so many other things you will use Google for. I already wrote about some tips for better Googling in &lt;a href="https://www.marinsborg.com/beginner-developer-skills/"&gt;my previous post&lt;/a&gt;, you should check it up.&lt;/p&gt;

&lt;h2&gt;
  
  
  Learn to say NO
&lt;/h2&gt;

&lt;p&gt;May is mental health awareness month and there are some things about the workplace that we need to talk about more.&lt;/p&gt;

&lt;p&gt;It is really hard for some people to say ‘no’ without feeling anxious, guilty, bad, or uncomfortable. Especially if they just started working on a new job. People don’t want to say ‘no’ because they are afraid of other people's reactions. That is usually mentally exhausting. However, you need to know that it is not your thing to worry about how other people will react to ‘no’. If you don’t say ‘no’, people will (unknowingly) abuse that, usually for their own benefit.&lt;/p&gt;

&lt;p&gt;Of course, I am not saying that you should say ‘no’ to everything but only to things that you know are not right and you know 100% it should be another way round. &lt;/p&gt;

&lt;p&gt;Also, you can’t just say ‘no’ without any explanation. I would suggest you use one of two templates, depending on the situation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;No, (I won’t do that) because I think...&lt;/li&gt;
&lt;li&gt;Yes, (I will do that) IF...&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first one is used when you know that something is wrong. In that case, you need to explain in detail why it is wrong until you prove other people wrong. You need to have good arguments about why you think something is wrong and also sometimes you can propose a better solution.&lt;/p&gt;

&lt;p&gt;The second one is technically a ‘yes’ but you need to request conditions to be fulfilled before you start doing that. Until conditions are fulfilled, it is still ‘no’. &lt;/p&gt;

&lt;p&gt;I will give you some examples, so it will be clear: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;“No, we should not deploy the new version of the application on Friday because there is nobody in the office during the weekend in case something goes wrong.”&lt;/li&gt;
&lt;li&gt;“No, I will not hardcode something in the database because it will probably cause problems in the future”&lt;/li&gt;
&lt;li&gt;“Yes, I will change that button if you open a ticket for that and the designer sends me a new design.”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you can see, you would get in trouble in the future if you said ‘yes’ in the examples. There is a high chance that things like this would repeat in the future because other people are used to that. Don’t hesitate to say ‘no’ when you think you are right. Be patient and explain your arguments in a kind way.&lt;/p&gt;

&lt;h2&gt;
  
  
  Don’t stay overtime voluntarily
&lt;/h2&gt;

&lt;p&gt;This one is pretty simple. If your contract says that you need to work 8 hours per day then don’t stay overtime if you don’t need to. Of course, there will be times when the deadline is near and something is not done yet so your whole team will work overtime. But in that scenario, somebody asked you to work overtime and you will be compensated for that.&lt;/p&gt;

&lt;p&gt;Staying overtime on your own rarely benefits you, even if you don’t have anything better to do. Everything can wait for the next morning. Your free time and rest are very important. Your time on this planet is a limited resource, don’t gift it to some company.&lt;/p&gt;

&lt;h2&gt;
  
  
  Leave for a better opportunity
&lt;/h2&gt;

&lt;p&gt;This is something that I did very often. You come to some company, things are going fine at the beginning, you are enjoying your time there. However, after some time you notice that some things are not okay anymore. Things can go ‘wrong’ pretty fast. It can be poor management decisions, lack of people and overworking, low salary compared to the job market, etc. &lt;/p&gt;

&lt;p&gt;It does not matter what is the cause of the problems. I would suggest you talk with your superiors, point to them about those problems and ask them to fix that. If they don’t fix those problems or if they promise to fix them but always delay then I would just leave. &lt;/p&gt;

&lt;p&gt;I know that changing jobs is not the most pleasant thing in the world but you are doing that to improve your situation. This is especially important for people who stay at their first job for a long time, no matter if the situation would be better if they change the job. Don’t ignore red flags and step out of your comfort zone for a bit. The grass sometimes really is greener on the other side. &lt;/p&gt;

&lt;p&gt;I already wrote a lot about this problem in my previous post - &lt;strong&gt;&lt;a href="https://www.marinsborg.com/change-your-job/"&gt;When is the time to change your job?&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Resources
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://psychcentral.com/lib/saying-no-kindly-and-then-letting-go#1"&gt;Psychcentral&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href="https://www.marinsborg.com/beginner-developer-skills/"&gt;What skills are good to know as a beginner developer?&lt;/a&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pcmag.com/how-to/google-search-tips-youll-want-to-learn"&gt;Google search tips&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.marinsborg.com/change-your-job/"&gt;When is the time to change your job?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>beginners</category>
      <category>career</category>
      <category>codenewbie</category>
      <category>discuss</category>
    </item>
    <item>
      <title>URL Shortener: Java &amp; Spring complete tutorial</title>
      <dc:creator>Marinsborg.com</dc:creator>
      <pubDate>Wed, 04 May 2022 20:16:10 +0000</pubDate>
      <link>https://dev.to/marinsborg/url-shortener-java-spring-complete-tutorial-1aif</link>
      <guid>https://dev.to/marinsborg/url-shortener-java-spring-complete-tutorial-1aif</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;For more posts like this, follow me on &lt;a href="https://twitter.com/marinsborg"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A URL shortener is a service that is used to create short links from very long URLs. Usually, short links have the size of one third or even one-fourth of the original URL, which makes them easier to type, present, or tweet. Clicking on a short link user will be automatically redirected to the original URL. &lt;/p&gt;

&lt;p&gt;There are many URL shortening services available online, like tiny.cc, bitly.com, cutt.ly, etc. Implementing a URL shortening service is not a complex task, and it is often part of system design interviews. In this post, I will try to explain the process of implementing the service.&lt;/p&gt;

&lt;h2&gt;
  
  
  Theory
&lt;/h2&gt;

&lt;p&gt;Before implementation, it is always a good idea to write down what it is needed to be done in the form of functional and non-functional requirements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Functional requirements:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Users need to be able to enter a long URL. Our service should save that URL and generate a short link. &lt;/li&gt;
&lt;li&gt;  Users should have the option to enter the expiration date. After that date passed, the short link should be invalid.&lt;/li&gt;
&lt;li&gt;  Clicking on the short link should redirect the user to the original long URL.&lt;/li&gt;
&lt;li&gt;  Users should create an account to use the service. Service can have a usage limit per user*&lt;/li&gt;
&lt;li&gt;  User is allowed to create his own short link*&lt;/li&gt;
&lt;li&gt;  Service should have metrics, for example, most visited links*&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Non-functional requirements:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Service should be up and running 100% of the time&lt;/li&gt;
&lt;li&gt;  Redirecting should not last longer than two seconds&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;*Requirements are optional&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Url conversion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's say that we want to have a short link with a maximum length of 7. The most important thing in a URL shortener is the conversion algorithm. URL conversion can be implemented in several different ways, and each way has its pros and cons.&lt;/p&gt;

&lt;p&gt;One way of generating short links would be hashing the original url with some hash function (for example &lt;a href="https://en.wikipedia.org/wiki/MD5"&gt;MD5&lt;/a&gt; or &lt;a href="https://en.wikipedia.org/wiki/SHA-2"&gt;SHA-2&lt;/a&gt;). When using a hash function it is sure that different inputs will result in different outputs. The result of the hash is longer than seven characters, so we would need to take the first seven characters. But, in this case, there could be a collision because the first seven characters could already be in use as a short link. Then, we take the next seven characters, until we find a short link that is not used.&lt;/p&gt;

&lt;p&gt;The second way of generating a short link is by using &lt;a href="https://en.wikipedia.org/wiki/SHA-2"&gt;UUIDs&lt;/a&gt;. The probability that a UUID will be duplicated is not zero, but it is close enough to zero to be negligible. Since a UUID has 36 characters, that means that we have the same problem as above. We should take the first seven characters and check if that combination is already in use.&lt;/p&gt;

&lt;p&gt;Third way would be converting numbers from &lt;a href="https://en.wikipedia.org/wiki/Decimal"&gt;base 10&lt;/a&gt; to base 62. A base is a number of digits or characters that can be used to represent a particular number. Base 10 are digits [0-9] which we use in everyday life and base 62 are [0-9][a-z][A-Z]. This means that, for example, number in base 10 with four digits would be the same number in base 62 but with two characters.&lt;/p&gt;

&lt;p&gt;Using base 62 in url conversion with a maximum length of seven characters allows us to have 62^7 unique values for short links.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So how base 62 conversion works?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We have a base 10 number that we want to convert to base 62. We are going to use the following algorithm:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    while(number &amp;gt; 0)
    remainder = number % 62
    number = number / 62
    attach remainder to start of result collection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that, we just need to map numbers from the result collection to the base 62 Alphabet = [0,1,2,...,a,b,c...,A,B,C,...].&lt;/p&gt;

&lt;p&gt;Let's see how this works with a real example. In this example, let's convert 1000 from base 10 to base 62.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    1st iteration:
        number = 1000
        remainder = 1000 % 62 = 8
        number = 1000 / 62 = 16
        result list = [8]
    2nd iteration:
        number = 16
        remainder = 16 % 62 = 16
        number = 16 / 62 = 0
        result list = [16,8]
        There is no more iterations since number = 0 after 2nd iteration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mapping [16,8] to base 62 would be g8. This means that 1000base10 = g8base62.&lt;/p&gt;

&lt;p&gt;Converting from base 62 to base 10 is also simple:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    i = 0
    while(i &amp;lt; inputString lenght)
        counter = i + 1
        mapped = base62alphabet.indexOf(inputString[i]) // map character to number based on its index in alphabet
        result = result + mapped * 62^(inputString lenght - counter)
        i++
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Real example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    inputString = g8
    inputString length = 2
    i = 0
    result = 0
    1st iteration
        counter = 1
        mapped = 16 // index of g in base62alphabet is 16
        result = 0 + 16 * 62^1 = 992
    2nd iteration
        counter = 2
        mapped = 8 // index of 8 in base62alphabet is 8
        result = 992 + 8 * 62^1 = 1000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implementation
&lt;/h2&gt;

&lt;p&gt;Note: The whole solution is on my &lt;a href="https://github.com/marinsborg/UrlShortener-API"&gt;Github&lt;/a&gt;. I implemented this service using Spring boot and MySQL.&lt;/p&gt;

&lt;p&gt;We are going to use our database's auto-increment feature. The auto-incrementing number is going to be used for base 62 conversion. You can use any other database that has an auto-increment feature.&lt;/p&gt;

&lt;p&gt;First, visit &lt;a href="https://start.spring.io/"&gt;Spring initializr&lt;/a&gt; and select Spring Web and MySql Driver. After that click on Generate button and download zip file. Unzip the file and open the project in your favorite IDE.&lt;br&gt;
Every time I start a new project, I like to create some folders to logically divide my code. My folders in this case are controller, entity, service, repository, dto, and config.&lt;/p&gt;

&lt;p&gt;Inside the entity folder, let's create a &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/entity/Url.java"&gt;Url.java&lt;/a&gt; class with four attributes: id, longUrl, createdDate, expiresDate.&lt;/p&gt;

&lt;p&gt;Notice that there is no short link attribute. We won't save short links. We are going to convert the id attribute from base 10 to base 62 every time there is a GET request. This way, we are saving space in our database.&lt;/p&gt;

&lt;p&gt;The LongUrl attribute is the URL we should redirect to once a user accesses a short link. The created date is just to see when the longUrl is saved (it is not important) and expiresDate is there if a user wants to make a short link unavailable after some time. &lt;/p&gt;

&lt;p&gt;Next, let's created a &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/service/BaseConversion.java"&gt;BaseService.java&lt;/a&gt; in the service folder. BaseService contains methods to convert from base 10 to base 62 and vice versa.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;allowedString&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;allowedCharacters&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;allowedString&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toCharArray&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;allowedCharacters&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Like I mentioned before, if we want to use base 62 conversions, we need to have a base 62 alphabet, which in this case, is called allowedCharacters. Also, the value of the base variable is calculated from the length of the allowed characters in case we want to change the allowed characters.&lt;/p&gt;

&lt;p&gt;The encode method takes a number as input and returns a short link. The decode method takes a string (short link) as an input and returns a number. The algorithms should be implemented as they were explained above.&lt;/p&gt;

&lt;p&gt;After that, inside the repository folder, let's create &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/repository/UrlRepository.java"&gt;UrlRepository.java&lt;/a&gt; file, which is just an extension of JpaRepository and it gives us a lot of methods like 'findById', 'save', etc. We don't need to add anything else to this.&lt;/p&gt;

&lt;p&gt;Then, let's create a UrlController.java file in the controller folder. The controller should have one POST method for creating short links and one GET method for redirecting to the original URL.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="nd"&gt;@PostMapping&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"create-short"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;convertToShortUrl&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@RequestBody&lt;/span&gt; &lt;span class="nc"&gt;UrlLongRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;urlService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;convertToShortUrl&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"{shortUrl}"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getAndRedirect&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@PathVariable&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;shortUrl&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;url&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;urlService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getOriginalUrl&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortUrl&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;status&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpStatus&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;FOUND&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;location&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="no"&gt;URI&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;create&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;POST method has a &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/dto/UrlLongRequest.java"&gt;UrlLongRequest&lt;/a&gt; as its request body. It is just class with longUrl and expiresDate attributes.&lt;/p&gt;

&lt;p&gt;The GET method takes a short url as a path variable and then gets and redirects to the original url.&lt;br&gt;
At the top of the controller, UrlService is injected as a dependency, which will be explained next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/service/UrlService.java"&gt;UrlService.java&lt;/a&gt; is where most logic is and is the service used by the controller. ConvertToShortUrl is used by the POST method from the controller. It just creates a new record in the database and gets an id. That id is then converted to a base 62 short link and returned to the controller.&lt;/p&gt;

&lt;p&gt;GetOriginalUrl is a method used by the GET method from the controller. It first converts a string to base 10, and the result of that is an id. Then, it gets a record from the database by that id and throws an exception if it does not exist. After that, it returns the original URL to the controller. &lt;/p&gt;

&lt;p&gt;And that is it for part one. In the next part I will focus on some more 'advanced' stuff.&lt;/p&gt;
&lt;h2&gt;
  
  
  'Advanced' topics
&lt;/h2&gt;

&lt;p&gt;In this part, I will talk about Swagger documentation, &lt;em&gt;dockerization&lt;/em&gt; of application, application cache and MySql scheduled event.&lt;/p&gt;
&lt;h2&gt;
  
  
  Swagger UI
&lt;/h2&gt;

&lt;p&gt;Every time you develop an API, it is good to document it in some way. Documentation makes APIs easier to understand and use. The API in this project is documented using Swagger UI.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://swagger.io/tools/swagger-ui/"&gt;Swagger UI&lt;/a&gt; allows anyone to visualize and interact with the API’s resources without having any of the implementation logic in place. It’s automatically generated, with the visual documentation making it easy for back end implementation and client-side consumption.&lt;/p&gt;

&lt;p&gt;There are several steps that we need to do to include Swagger UI in the project.&lt;/p&gt;

&lt;p&gt;First, we need to add Maven dependencies to the pom.xml file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;    &lt;span class="nt"&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;io.springfox&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;springfox-swagger2&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;version&amp;gt;&lt;/span&gt;2.9.2&lt;span class="nt"&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;io.springfox&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;springfox-swagger-ui&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;version&amp;gt;&lt;/span&gt;2.9.2&lt;span class="nt"&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For reference, you can see the complete pom.xml file &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/pom.xml"&gt;here&lt;/a&gt;.&lt;br&gt;
After adding the Maven dependencies, it is time to add Swagger configuration.&lt;br&gt;
Inside the config folder, we need to create a new class - &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/config/SwaggerConfig.java"&gt;SwaggerConfig.java&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="nd"&gt;@Configuration&lt;/span&gt;
    &lt;span class="nd"&gt;@EnableSwagger2&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SwaggerConfig&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Bean&lt;/span&gt;    
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Docket&lt;/span&gt; &lt;span class="nf"&gt;apiDocket&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;   
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Docket&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;DocumentationType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SWAGGER_2&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;  
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;apiInfo&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;metadata&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;    
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;select&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;    
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;apis&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;RequestHandlerSelectors&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;basePackage&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"com.amarin"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;    
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;    
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;ApiInfo&lt;/span&gt; &lt;span class="nf"&gt;metadata&lt;/span&gt;&lt;span class="o"&gt;(){&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;ApiInfoBuilder&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;title&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Url shortener API"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;    
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;description&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"API reference for developers"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;    
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;version&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"1.0"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;    
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;    
        &lt;span class="o"&gt;}&lt;/span&gt;  
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At the top of the class, we need to add a couple of annotations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;@Configuration&lt;/strong&gt; indicates that a class declares one or more &lt;strong&gt;&lt;a class="mentioned-user" href="https://dev.to/beans"&gt;@beans&lt;/a&gt;&lt;/strong&gt; methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;@EnableSwagger2&lt;/strong&gt; indicates that Swagger support should be enabled.&lt;/p&gt;

&lt;p&gt;Next, we should add &lt;strong&gt;Docket&lt;/strong&gt; bean which provides the primary API configuration with sensible defaults and convenience methods for configuration.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;apiInfo()&lt;/strong&gt; method takes the ApiInfo object where we can configure all necessary API information - otherwise, it uses some default values. To make code cleaner, we should make a private method that will configure and return the ApiInfo object and pass that method as a parameter the of &lt;strong&gt;apiInfo()&lt;/strong&gt; method. In this case it is the &lt;strong&gt;metadata()&lt;/strong&gt; method.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;apis()&lt;/strong&gt; method allows us to filter packages that are being documented.&lt;/p&gt;

&lt;p&gt;Now Swagger UI is configured and we can start documenting our API. Inside &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/controller/UrlController.java"&gt;UrlController&lt;/a&gt;, above every endpoint, we can use &lt;a href="https://github.com/swagger-api/swagger-core/wiki/Annotations#apioperation"&gt;@ApiOperation&lt;/a&gt; annotation to add description. Depending on your needs you can use some other &lt;a href="https://github.com/swagger-api/swagger-core/wiki/Annotations"&gt;annotations&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It is also possible to document &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/dto/UrlLongRequest.java"&gt;DTOs&lt;/a&gt; and using &lt;a href="https://github.com/swagger-api/swagger-core/wiki/Annotations#apimodelproperty"&gt;@ApiModelProperty&lt;/a&gt; which allows you to add allowed values, descriptions, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Caching
&lt;/h2&gt;

&lt;p&gt;According to Wikipedia, a &lt;strong&gt;&lt;a href="https://en.wikipedia.org/wiki/Cache_(computing)"&gt;cache&lt;/a&gt;&lt;/strong&gt; is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere.&lt;/p&gt;

&lt;p&gt;The most frequently used type of cache is &lt;strong&gt;in-memory cache&lt;/strong&gt; which stores cached data in RAM. When data is requested and found in the cache, it is served from RAM instead of from a database. This way, we avoid calling costly backend when a user requests data.&lt;/p&gt;

&lt;p&gt;A URL shortener is a type of application that has more read requests than write requests which means it is an ideal application to use cache.&lt;/p&gt;

&lt;p&gt;To enable caching in Spring Boot application, we just need to add &lt;a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/EnableCaching.html"&gt;@EnableCaching&lt;/a&gt; annotation in &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/UrlShortenerApiApplication.java"&gt;UrlShortenerApiApplication&lt;/a&gt; class.&lt;/p&gt;

&lt;p&gt;After that, in the &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/java/com/amarin/urlshortenerapi/controller/UrlController.java"&gt;controller&lt;/a&gt; we need to set the &lt;a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html"&gt;@Cachable&lt;/a&gt; annotation above GET method. This annotation automatically stores the result of the method call to the cache. In the @Cachable annotation, we set the &lt;strong&gt;value&lt;/strong&gt; parameter which is the name of the cache and the &lt;strong&gt;key&lt;/strong&gt; parameter which is the cache key. In this case for the cache key, we are going to use 'shortUrl' because we are sure it is unique. &lt;strong&gt;Sync&lt;/strong&gt; parameter is set to true to ensure only a single thread is building the cache value.&lt;/p&gt;

&lt;p&gt;And that is it - our cache is set and when we first load the URL with some short link, the result will be saved to cache and any additional call to the endpoint with the same short link will retrieve the result from the cache instead of from the database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Dockerization
&lt;/h2&gt;

&lt;p&gt;Dockerization is the process of packaging an application and its dependencies in a &lt;a href="https://en.wikipedia.org/wiki/Docker_(software)"&gt;Docker&lt;/a&gt; container. Once we configure Docker container, we can easily run the application on any server or computer that supports Docker.&lt;/p&gt;

&lt;p&gt;The first thing we need to do is to create a Dockerfile. A &lt;a href="https://docs.docker.com/engine/reference/builder/"&gt;Dockerfile&lt;/a&gt; is a text file that contains all the commands a user could call on the command line to assemble an image.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight docker"&gt;&lt;code&gt;    FROM openjdk:13-jdk-alpine   
    COPY ./target/url-shortener-api-0.0.1-SNAPSHOT.jar /usr/src/app/url-shortener-api-0.0.1-SNAPSHOT.jar    
    EXPOSE 8080    
    ENTRYPOINT ["java","-jar","/usr/src/app/url-shortener-api-0.0.1-SNAPSHOT.jar"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;FROM&lt;/strong&gt; - This is where we set a base image for the build base. We are going to use OpenJDK v13 which is a free and open-source version of Java. You can find other images for your base image at &lt;a href="https://hub.docker.com/"&gt;Docker hub&lt;/a&gt; which is a place for sharing docker images.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COPY&lt;/strong&gt; - This command copies files from the local filesystem (your computer) to the filesystem of the container at the path we specified. So we are going to copy the JAR file from the target folder to /usr/src/app folder in the container. I will explain creating the JAR file a bit later.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;EXPOSE&lt;/strong&gt; - Instruction that informs Docker that the container listens on the specified network ports at runtime. The default protocol is TCP and you can specify if you want to use UDP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ENTRYPOINT&lt;/strong&gt; - This instruction allows you to configure a container that will run as an executable. Here we need to specify how Docker will run out an application. The command to run an application from the .jar file is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    java -jar &amp;lt;app_name&amp;gt;.jar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so we put that 3 words in an array and that is it.&lt;/p&gt;

&lt;p&gt;Now when we have Dockerfile we should build the image from it. But like I mentioned before, we first need to create .jar file from our project so the COPY command in Dockerfile can work properly. To create executable .jar we are going to use &lt;a href="https://maven.apache.org/"&gt;maven&lt;/a&gt;. We need to make sure we have Maven inside our &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/pom.xml"&gt;pom.xml&lt;/a&gt;. If Maven is missing, we can add it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;build&amp;gt;&lt;/span&gt;    
    &lt;span class="nt"&gt;&amp;lt;plugins&amp;gt;&lt;/span&gt;    
        &lt;span class="nt"&gt;&amp;lt;plugin&amp;gt;&lt;/span&gt;    
            &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.springframework.boot&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;    
            &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;spring-boot-maven-plugin&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;    
        &lt;span class="nt"&gt;&amp;lt;/plugin&amp;gt;&lt;/span&gt;    
    &lt;span class="nt"&gt;&amp;lt;/plugins&amp;gt;&lt;/span&gt;    
&lt;span class="nt"&gt;&amp;lt;/build&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that, we should just run the command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    mvn clean package
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that is done, we can build a Docker image. We need to make sure we are in the same folder where a Dockerfile is so we can run this command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    docker build -t url-shortener:latest .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;-t&lt;/strong&gt; is used to tag an image. In our case, that means that the name of the repository will be url-shortener and a tag will be the latest. Tagging is used for the versioning of images. After that command is done, we can make sure we created an image with the command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    docker images  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will give us something like this&lt;/p&gt;

&lt;p&gt;&lt;a href="/img/posts/url-shortener/docker-ps.png" class="article-body-image-wrapper"&gt;&lt;img src="/img/posts/url-shortener/docker-ps.png" alt=""&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;For the last step, we should build our images. I say images because we will also run MySQL server in a docker container. Database container will be isolated from the application container. To run MySQL server in docker container simply run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    $ docker run --name shortener -e MYSQL_ROOT_PASSWORD=my-secret-pw -d -p 3306:3306 mysql:8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see the documentation on &lt;a href="https://hub.docker.com/_/mysql"&gt;Docker hub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;When we have a database running inside a container, we need to configure our application to connect to that MySQL server. Inside &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/src/main/resources/application.properties"&gt;application.properties&lt;/a&gt; set spring.datasource.url to connect to the 'shortener' container.&lt;/p&gt;

&lt;p&gt;Because we made some changes in our project it is required to pack our project into a .jar file using Maven and build the Docker image from the Dockerfile again.&lt;/p&gt;

&lt;p&gt;Now that we have a Docker image, we should run our container. We do that with the command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    docker run -d --name url-shortener-api -p 8080:8080 --link shortener url-shortener
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;-d&lt;/strong&gt; means that a Docker container runs in the background of your terminal.&lt;br&gt;
&lt;strong&gt;--name&lt;/strong&gt; lets you set the name of your container&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;-p host-port:docker-port&lt;/strong&gt; - This is simply mapping ports on your local computer to ports inside container. In this case, we exposed port 8080 inside a container and decided to map it to our local port 8080&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;--link&lt;/strong&gt; with this we link our application container with database container to allow containers to discover each other and securely transfer information about one container to another container. It is important to know that this flag is now &lt;strong&gt;legacy&lt;/strong&gt; and it will be removed in the near future. Instead of links, we would need to create a network to facilitate communication between two containers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;url-shortener&lt;/strong&gt; - is the name of the docker image we want to run.&lt;/p&gt;

&lt;p&gt;And with this, we are done - in browser visit &lt;a href="http://localhost:8080/swagger-ui.html"&gt;http://localhost:8080/swagger-ui.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now you can publish your image to DockerHub and easily run your application on any computer and server.&lt;/p&gt;

&lt;p&gt;There are two more things I want to talk about to improve our Docker experience. One is multi-stage build and the other is docker-compose.&lt;/p&gt;

&lt;h3&gt;
  
  
  Multi-stage build
&lt;/h3&gt;

&lt;p&gt;With &lt;a href="https://docs.docker.com/develop/develop-images/multistage-build/"&gt;multi-stage builds&lt;/a&gt;, you use multiple &lt;strong&gt;FROM&lt;/strong&gt; statements in your Dockerfile. Each &lt;strong&gt;FROM&lt;/strong&gt; instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don’t want in the final image.&lt;/p&gt;

&lt;p&gt;Multi-stage builds are good for us to avoid manually creating .jar files every time we make some change in our code. With multi-stage builds, we can define one stage of the build that will do the Maven package command and the other stage will copy the result from the first build to the filesystem of a Docker container.&lt;/p&gt;

&lt;p&gt;You can see the complete Dockerfile &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/Dockerfile"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Docker-compose
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://docs.docker.com/compose/"&gt;Compose&lt;/a&gt; is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.&lt;/p&gt;

&lt;p&gt;With docker-compose, we will pack our application and database into &lt;strong&gt;single configuration file&lt;/strong&gt; and then run everything at once. This way we avoid running MySQL container and then linking it to the application container every time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/docker-compose.yml"&gt;Docker-compose.yml&lt;/a&gt; is pretty much self-explanatory - first we configure MySQL container by setting image mysql v8.0 and credentials for the MySSQL server. After that, we configure the application container by setting build parameters because we need to build an image instead of pulling it like we did with MySQL. Also, we need to set that application container depends on the MySQL container.&lt;/p&gt;

&lt;p&gt;Now we can run the whole project with only one command:&lt;br&gt;
&lt;strong&gt;docker-compose up&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  MySql scheduled event
&lt;/h2&gt;

&lt;p&gt;This part is &lt;strong&gt;optional&lt;/strong&gt; but I think somebody might find this useful anyway.  I talked about the expiration date of the short link which can be user-defined or some default value. For this problem, we can set a scheduled event inside our database. This event would run every x minutes and would delete any row from the database where the expiration date is lower than the current time. Simple as that. This works well on a small amount of data in the database.&lt;/p&gt;

&lt;p&gt;Now I need to warn you about a couple of issues with this solution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;First&lt;/strong&gt; - This event will remove records from the database but it will not remove data from the cache. Like we said before, the cache will not look inside the database if it can find matching data there. So even if data no longer exists in the database because we deleted it, we can still get it from the cache.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Second&lt;/strong&gt; - In my &lt;a href="https://github.com/marinsborg/UrlShortener-API/blob/develop/database/even_scheduler_delete.sql"&gt;example script&lt;/a&gt; I set that event runs every 2 minutes. If our database becomes huge then it could happen that event does not finish execution within its scheduling interval, the result may be multiple instances of the event executing simultaneously.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>tutorial</category>
      <category>codenewbie</category>
      <category>java</category>
    </item>
  </channel>
</rss>
