<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Carlos Fernando Arboleda Garcés on Medium]]></title>
        <description><![CDATA[Stories by Carlos Fernando Arboleda Garcés on Medium]]></description>
        <link>https://medium.com/@carboleda?source=rss-e6b6a26bd0c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hMJ5Nplx-ns4-QJKq-U-Eg.jpeg</url>
            <title>Stories by Carlos Fernando Arboleda Garcés on Medium</title>
            <link>https://medium.com/@carboleda?source=rss-e6b6a26bd0c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:46:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carboleda/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From zero to hero in LLM function calling with Google Gemini and Typescript]]></title>
            <link>https://carboleda.medium.com/from-zero-to-hero-in-llm-function-calling-with-google-gemini-and-typescript-efb916aee60f?source=rss-e6b6a26bd0c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb916aee60f</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[genai-function-calling]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Carlos Fernando Arboleda Garcés]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 03:45:53 GMT</pubDate>
            <atom:updated>2025-01-29T03:45:53.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W7mc-iVQ7rAoyiF0" /><figcaption>Photo by <a href="https://unsplash.com/@antoinebarres?utm_source=medium&amp;utm_medium=referral">Antoine Barrès</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, you’ll learn everything you need to know to start taking advantage of the function calling capabilities of the Flash 1.5 model and the Gemini for Node.js SDK. However, some concepts are also applicable to other models and SDKs such as GPT.</p><p>Ok, let’s start from the beginning. You’ve probably heard that LLMs are frozen in time with respect to the information that was used to train them, and because of this LLMs cannot give you the most up-to-date answers on certain topics, but more importantly, they cannot give you answers using real-time information such as weather or exchange rates.</p><p>While RAG is outside the scope of this story, it could be used to provide the LLM with more up-to-date information or even private information so that the LLM can provide more accurate answers. However, RAG does not solve the problem of using real-time information to provide answers and this is where the function calling comes to the rescue.</p><h3>What is function calling?</h3><p>It’s a technique that allows LLMs to interface with external systems and tools. LLMs are fine-tune to detect when a function needs to be called and then output JSON containing arguments to call the function. Bellow you can find some of its more important facts:</p><ul><li><strong>Consistent output: </strong>It provides ready-to-use structured output in different formats such as JSON, XML or just plain text. Thus, it integrates seamlessly with the downstream</li><li><strong>Live data:</strong> Provide the LLM with real-time information by using the function response structured format</li><li><strong>Complete transactions:</strong> Ability to take action on behalf of the user through interfaces like APIs, after receiving the function call whatever task can be executed</li></ul><p>Oh and just for your information, when using LLM function calling it doesn’t actually call your function 🫠. But do not worry, we will go into more details later.</p><h3>How function calling works?</h3><p>I’ll take you through the life cycle of a single function call, so bellow you’ll find a flow diagram and the and after that an detail explanation for each step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ma33jNp4CYNhvIlMW27IoQ.png" /><figcaption>Function calling life cycle</figcaption></figure><p><strong>1</strong> — The application instantiate the model and include in the configuration the declaration for the function (tool) the model can use to get real time information, in this case the current time</p><pre>function getCurrentTime({ timeZone }) {<br>  const now = new Date();<br>  const date = now.toLocaleDateString(&quot;en-US&quot;, { timeZone });<br>  const time = now.toLocaleTimeString(&quot;en-US&quot;, { timeZone });<br>  return `${date} ${time}`;<br>}<br><br>const functions = {<br>  getCurrentTime,<br>};<br><br>const tools: Tools[] = [<br>  {<br>    functionDeclarations: [<br>      {<br>        name: &quot;getCurrentTime&quot;,<br>        description: `Get the current time in a specific location`,<br>        parameters: {<br>          type: SchemaType.OBJECT,<br>          properties: {<br>            timeZone: {<br>              type: SchemaType.STRING,<br>              description:<br>                &quot;Timezone in IANA format. Example America/Bogotá, Europe/Berlin&quot;,<br>            },<br>          },<br>          required: [&quot;timeZone&quot;],<br>        },<br>      },<br>    ],<br>  },<br>];<br><br>const model = genAI.getGenerativeModel(<br>   { model: &quot;gemini-1.5-flash-latest&quot;, tools },<br>   { apiVersion: &quot;v1beta&quot; }<br>);</pre><p><strong>2 </strong>— The user sends a prompt to the application</p><pre>const prompt = {<br>   role: &quot;user&quot;,<br>   parts: [<br>     {<br>       text: &quot;What time is it in Cali, Colombia?&quot;,<br>     },<br>   ],<br>};<br><br>const result = await model.generateContent({<br>   contents: [prompt],<br>});</pre><p><strong>3</strong> — The model identifies the function needed to fulfill the request and returns a function call to that function, this call includes the function name and the arguments extracted from the user prompt or from model knowledge itself</p><pre>// Gemini model function call<br>{<br>  &quot;content&quot;: {<br>    &quot;parts&quot;: [<br>      {<br>        &quot;functionCall&quot;: {<br>          &quot;name&quot;: &quot;getCurrentTime&quot;,<br>          &quot;args&quot;: { &quot;timeZone&quot;: &quot;America/Bogotá&quot; }<br>        }<br>      }<br>    ],<br>    &quot;role&quot;: &quot;model&quot;<br>  }<br>}</pre><p><strong>4</strong> — The application receives the function call and proceeds with its invocation. Then, creates a <a href="https://github.com/google-gemini/generative-ai-js/blob/2ae06ff0790307d2ee542f67bdabe25e234651c4/docs/reference/server/generative-ai.content.md"><em>Content</em></a> object to encapsulate the function response</p><pre>const response = functions[name](args); // -&gt; getCurrentTime(&quot;America/Bogotá&quot;)<br>const functionResponse = {<br>  role: &quot;function&quot;,<br>  parts: [<br>    {<br>      functionResponse: {<br>        name,<br>        response: {<br>          content: response,<br>        },<br>      },<br>    },<br>  ],<br>};</pre><p><strong>5 </strong>— The application sends a new message to the model including the function response. The model proceses the function responses, then creates a response in natural language, and finally that natural language response is sent to the application and presented to the user</p><pre>const request = {<br>   contents: [prompt, content, functionResponse],<br>};<br><br>const res = await model.generateContent(request);<br>console.log(res.response.text());<br>// It&#39;s 11:20:33 AM in Cali, Colombia.</pre><p>Amazing right!? You can find the whole file of this example in the <a href="https://github.com/carboleda/gemini-function-calling-examples/blob/main/1.intro/index.ts">1.intro</a> directory of my <a href="https://github.com/carboleda/gemini-function-calling-examples/tree/main">Github repository</a> where I have created a bunch of examples for you.</p><h4>Data Structures and Schemas</h4><p>As you probably noticed, in the first step we used structures to declare our <em>getCurrentTime</em> function. These data structures and schemas are based on the Open API specification and help us easily describe our function to the LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8B7LUao5dDblfnapeyOBA.png" /><figcaption>How you declare your functions using Data Structures and Schemas</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cjjUVWzfdZ9EyCxzDBD1A.png" /><figcaption>What you receive when the LLM responds with a function call</figcaption></figure><p>I don’t want to make this story too long so you can find a whole list of examples for this topic in the <a href="https://github.com/carboleda/gemini-function-calling-examples/tree/main/2.data-structures">2.data-structures</a> directory.</p><h3>Optimizing the performance</h3><p>Probably the most exciting example you will find in the repository is the <a href="https://github.com/carboleda/gemini-function-calling-examples/tree/main/4.sql-talk-app">4.sql-talk-app</a>. This is a simple example that shows up how using function calling we can talk in natural language to our data source (in this case a SQLite database). At the same time, this example presents to opportunities of performance optimization that are basically related to how to reduce the calls to the Gemini API in our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ZWIZgdPJ7NOJFUEcP5RMQ.png" /><figcaption>Example of how, using chat history, subsequence requests requiring similar tables do not generate additional function calls to obtain the tables and schemas</figcaption></figure><blockquote>Before moving forward, make sure you have reviewed the sql-talk-app example so that you can easily understand the following explanations.</blockquote><h4><strong>What is the issue</strong></h4><p>Each prompt you send to the application will require the model to get all the table names and the schema for each required table, so that it can build the queries.</p><p>For example the prompt “Generate a list of the students” will require to get the schema for the table student. And the prompt <em>“Generate a list of the students enrolled in English Literature”</em> will require to get the schema for student, course and student_course tables.</p><p>Now let’s see how the following features can help us solve this issue, dramatically save cost, and speed up our applications.</p><h4><strong>Parallel function calling</strong></h4><p>Considering that for each prompt the LLM needs the table names and the schemas, this feature makes the LLM capable to send multiple function calls and receiving multiple functions response at the same time. Otherwise, the application would have to chain the function calls, it means that you get the first function call response, return the API data to Gemini, get a second function call response, return the API data to Gemini, and so on.</p><p>As usual, you will find examples related to this topic in the <a href="https://github.com/carboleda/gemini-function-calling-examples/tree/main/3.parallel-function-calling">3.parallel-function-calling</a> directory of the repository as well as a link to a more detailed documentation.</p><h4><strong>Chat history</strong></h4><p>By using <em>ChatSession</em> with the history, we can drastically reduce the API calls and as well as the hits to the database. For example, if we add the response for the <em>getTables</em> function call to the history, this function call will not be invoked for the subsequent prompts since the LLM will take it from the context (history). And the same will apply to the calls to <em>getTableSchema.</em></p><p>To get this working, we also need to modify our system instructions adding something like <em>“…If the tables or table schema are available in the history, use them to reduce the calls to the database. Otherwise, use the available tools to get the information.”</em></p><p>Thanks for coming to the end of this story, if you find this story and the shared <a href="https://github.com/carboleda/gemini-function-calling-examples/tree/main">repository</a> helpful do not forget to give a star to the repository and share with your friends. Also leave a clap here, I would appreciate it and it will help this story to reach more people!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb916aee60f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top-Down approach to get started with AI]]></title>
            <link>https://carboleda.medium.com/top-down-approach-to-get-started-with-ai-9af56476fdc5?source=rss-e6b6a26bd0c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af56476fdc5</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Carlos Fernando Arboleda Garcés]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 20:57:59 GMT</pubDate>
            <atom:updated>2024-05-17T02:45:50.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top-Down approach to get started with Generative AI and ML — Learning journey</h3><h4>AI is progressing at big steps, should we start learning theory or get into practice ASAP? That’s the question!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuqIyA9ML6IGWJNEvpHz2g.jpeg" /><figcaption><a href="https://www.pexels.com/photo/wall-e-die-cast-model-981588/">Photo by Nubia Navarro (nubikini) from Pexels</a></figcaption></figure><p>As software engineers or developers, we mainly focus on programming backend or web/mobile applications. Probably in the last two years you have felt overwhelmed with how fast Artificial Intelligence (AI) is making progress, and maybe you didn’t think you were going to see this AI revolution. Likely all the news around AI and Machine Learning (ML) piqued your curiosity, the ability for computers to learn on their own seemed like magic, but above all how fast those models are improving! However, you don’t know where to start or simply diving headfirst into algorithms and complex math is overwhelming for you. If this sounds familiar to you, keep reading since here we will discover the power of the Top-Down learning approach to begin our AI journey without failing in the attempt.</p><p>Artificial Intelligence can feel like a labyrinth — exciting possibilities branch out in every direction, but where do you begin? The answer might lie in your learning approach. Here, we explore the Top-Down approach with a pragmatic focus. Although this is just the beginning of my journey, I want to share experiences and leave some memories through the process, hoping they can help you to find your own direction in the world of AI.</p><p>As stated before, possibilities branch out in every direction. That’s why, before delving deeper into the Top-Down approach it’s important to do a quick research and define a goal. Let’s use my own example, and say my goal is to learn Generative AI because we can use all the tools and models available to leverage the power of AI. Machine Learning would be a step forward, to create or fine-tune models.</p><h4><strong>The Top-Down Approach: Big Picture First</strong></h4><p>While most of the books, posts and online courses use the Bottom-Top approach and encourage you to start learning linear algebra, calculus and statistics (we know this is pretty important). In the Top-Down approach you may focus on learning theoretical and general concepts like AI and its subsets (Machine Learning, Deep Learning, etc), prompt design and prompt engineering. And then you care about learning linear algebra, statistics, etc. This approach will be beneficial for you if you don’t have enough time or simply you want to start playing around AI as soon as possible. However, it’s ok if you want to try the Bottom-Up.</p><p>Thanks to the democratization of AI, nowadays it’s not reserved only for researchers and doctors in the area anymore, and anyone with an internet connection can have access to a tool that allows them to leverage the power of AI.</p><h3>The Roadmap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VC8ExsIPz6BuJ455" /><figcaption>Photo by <a href="https://unsplash.com/@jerrykavan?utm_source=medium&amp;utm_medium=referral">Jaromír Kavan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now, let me share my point of view about how a possible roadmap based on the Top-Down approach to get started with Generative AI will look like. However, it’s worth noting that this may change depending on your current knowledge and your goal:</p><ol><li>Theoretical understanding of key concepts. <em>e.g: </em><a href="https://en.wikipedia.org/wiki/Artificial_intelligence"><em>AI</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Machine_learning"><em>ML</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Deep_learning"><em>DL</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Neural_network"><em>NLP</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Foundation_model"><em>FM</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Large_language_model"><em>LLM</em></a><em>.</em> The main idea here is to know those words or concepts that are used in almost every reading.</li><li>Prompt design/engineering including Zero, one, and few shots prompting, prompt chaining, etc.</li><li>Python fundamentals.</li><li>Use Generative AI APIs.</li><li>Jupyter Notebook.</li><li>If you already know Python you may want to go further and learn the basics of Pandas, Numpy and Matplotlib. This libraries are widely used in ML.</li><li>Understanding of key technical components in Generative AI. e.g: <em>Vector Database, Fine-tuning, Embeddings, etc.</em></li><li>LangChain.</li><li>TensorFlow and Keras.</li></ol><p>Only after the previous topics I would consider delving deeper into the ones that the Bottom-Top approach would have initially focused on. From my point of view the mathematics topics would be the most boring part. However, after understanding the relevance of mathematics in this field from a pragmatic standpoint; it may be easier and more interesting to learn. Therefore, some things might make more sense.</p><p>A long the journey the key is to balance the theory and the practice so that we don’t get bored and fall asleep each time we try to study (this happen to me when I start studying at 10pm after putting my daughter to bed 😬), we need to get hooked and embrace this process to increase the chances of success.</p><h3>Takeaways</h3><ul><li>Make a quick research to identify the state-of-the-art and the topics you need to learn. Remember that AI is moving really fast so <em>don’t let too much water go under the bridge</em>.</li><li>Before you begin your learning journey, define a clear, measurable and achievable goal.</li><li>Try to mix theory and practice at each stage so as not to become overwhelmed with so much theory. Furthermore, we can gain hands-on experience about what we‘re studying.</li></ul><h3>References</h3><ol><li>Juan Guillermo Gomez, Henry Ruiz, <a href="https://open.spotify.com/episode/1T48oFbjFBqlroXQelPrl4?si=57K9NrXbR0-a4eb_M9A_gA">Snippets Tech Podcast: Machine Learning — Que es? — Con Henry Ruiz</a> (2024), Spotify</li><li><a href="https://www.cloudskillsboost.google/paths/118">Introduction to Generative AI Learning Path</a> (2024), Google Cloud Skills Boost</li><li>Elvis Saravia, <a href="https://www.promptingguide.ai/">Prompt Engineering Guide</a> (2024), <em>DAIR.AI</em></li><li>Jason Brownlee, PhD (2020), <a href="https://machinelearningmastery.com/4-steps-to-get-started-in-machine-learning/">4-Steps to Get Started in Applied Machine Learning</a>, Machine Learning Mastery</li><li>Adel Nehme, VP of Media at DataCamp (2023), <a href="https://www.datacamp.com/blog/how-to-learn-ai">How to Learn AI From Scratch in 2024</a>, DataCamp Blog</li><li><a href="https://cloud.google.com/learn/what-is-artificial-intelligence">What is Artificial Intelligence (AI)?</a> (2024), Google Cloud Learn</li><li>Kaggle, <a href="https://www.kaggle.com/learn">Gain the skills you need to do independent data science projects</a> (2024), Kaggle Learn</li></ol><p>This is just the first of many contents that I plan to share about the Gen AI learning journey, so stay tuned and let me know in the comments which approach you would use and what would you change to the proposed roadmap. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af56476fdc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Improve the Jest Performance in CI Environments When Using TypeScript]]></title>
            <link>https://medium.com/better-programming/how-to-improve-the-jest-performance-in-ci-environments-when-using-typescript-66a186cb5cd4?source=rss-e6b6a26bd0c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/66a186cb5cd4</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Carlos Fernando Arboleda Garcés]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 13:10:42 GMT</pubDate>
            <atom:updated>2022-08-30T13:10:42.772Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tips to rid your projects of stuck test cases and out of memory errors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lqit3x9qjIQRLHP2QS_UcA.png" /><figcaption>Icons from <a href="https://www.iconfinder.com/search?q=thunder&amp;price=free">iconfinder.com</a> and <a href="https://freeicons.io/profile/3">freeicons.io</a></figcaption></figure><p>Every single developer or developer team must make decisions when building a new project, and in this case, we are talking about Node.js projects. When talking about JavaScript development, one of the best decisions you can make is to use TypeScript since this will give you extra tools to write a more clear and maintainable code.</p><p>Another good decision is to add a test framework or library to your project, and it’s not a secret that Jest is currently the most used framework and is a good choice since it has a powerful built-in assertion library.</p><p>And the last but not least important thing we shall add is a pipeline to ensure we are not introducing errors and everything is working well before each merge or release. Let&#39;s use Jenkins for this task, although it could be any other option.</p><p>At this point, you have already met the three main characters of this story: <a href="https://www.typescriptlang.org/">TypeScript</a>, <a href="https://jestjs.io/">Jest.js</a>, and <a href="https://www.jenkins.io/">Jenkins</a>. Let’s get started.</p><h3>The Problem</h3><p>Everything started because it was asked to update the project dependencies since some vulnerabilities were detected and because it had been a long time since the last update. After this process, I had the following dependencies updated (just to mention the most relevant):</p><pre>typescript     from 3.9.7  to 4.7.4<br>jest           from 26.4.2 to 28.1.1<br>ts-jest        from 26.3.0 to 28.0.5</pre><p>Then, when I pushed the changes and Jenkins ran the tests, two different issues in two different moments were identified:</p><ol><li>The test stage got stuck at a random test case at every pipeline execution and was never finished.</li><li>After implementing a workaround for the first issue and merging the changes to another feature branch with some extra code and tests, the following error was printed in the stage’s log “JavaScript heap out of memory error.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAtnLfqJxidWhzH3WN4WjQ.png" /><figcaption>JavaScript heap out of memory error</figcaption></figure><p>Besides that, it’s important to say that before the dependencies update, the test stage took 1.59 minutes for unit tests and 3.26 minutes for the e2e test. Keep these numbers in mind for later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*8Kd6eMPu4KZ9RwfdGS4X0Q.png" /><figcaption>CI pipeline time for test stages</figcaption></figure><h3>The Workaround for “Stuck Test Cases”</h3><p>As you can see in the answers to this <a href="https://stackoverflow.com/questions/62885390/my-jests-tests-are-leaking-memory-how-can-i-fix-this">Stack Overflow question</a>, the first and most used approach you can find when you look for information about how to fix this problem is related to the number of threads used by Jest to run the tests. You can change the default behavior by using two different options:</p><ul><li><a href="https://jestjs.io/docs/cli#--runinband">— runInBand</a>: This runs all the tests serially and uses the main process rather than creating more threads.</li><li><a href="https://jestjs.io/docs/cli#--maxworkersnumstring">— maxWorkers</a>: This allows you to set how many threads can be used to run the tests. This defaults to the number of the cores available on your machine minus one for the main thread.</li></ul><p>Therefore, I added the option — runInBand to my package.json test script to avoid Jest running more than one test at a time, meaning the process needs less memory. However, this also means it will take longer to finish. This solved the first issue, but we must deal with the JavaScript heap out-of-memory error.</p><h3>Digging Deeper, Looking for the Root Cause of “Out of Memory Error”</h3><p>To have a better understanding of the problem, the first thing that I did, was to get more profiling information from the test execution. I achieved this by updating the test package.json script to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9f72bdec45c3fd0dccd31d35b6f6aae/href">https://medium.com/media/b9f72bdec45c3fd0dccd31d35b6f6aae/href</a></iframe><p>This allows me to run the tests individually and get information about how much memory was allocated after running each test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*YrsLi11XJ1n_LJz-Vv7Gxw.png" /><figcaption>Jest — logHeapUsage option</figcaption></figure><p>At this point, I realized that Jest was consuming more memory than the available in the Jenkins container and that it took a long time to start running the first test.</p><p>My first alternative was to speed up the test using <a href="https://swc.rs/">SWC</a>, which promises to speed up the compilation up to 20x compared to <a href="https://babeljs.io/">Babel</a>. However, I had several problems setting it up because it seemed unable to process circular dependencies well.</p><p>Then, while googling for another option, I ended up in a <a href="https://huafu.github.io/ts-jest/">ts-jest</a> configuration option called <a href="https://huafu.github.io/ts-jest/user/config/isolatedModules#example">Isolated Modules</a>. In short, it disables TypeScript type-checking resulting in less memory consumption and a lower execution time.</p><h3>Final Solution</h3><p>I guess you have concerns about type-checking since we are not using TypeScript to disable it at first. But no worries, we just need to disable it in the CI environment. As you can see in the scripts below, we need to disable the type-checking for the CI script by sending an environment variable. Then you only need to be sure you are using the test:ci when configuring your pipeline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/183063d95a231818949e706a1542386f/href">https://medium.com/media/183063d95a231818949e706a1542386f/href</a></iframe><p>Then let me show you two images of the test execution using the normal test and CI test so that you can see the differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*r3s_u5Hrf9Lugi0qgpqLwg.png" /><figcaption>Without optimization — normal test script (npm run test)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*VkX7WhVz-Mui9-0LB0IElA.png" /><figcaption>With optimization — CI test script (npm run test:ci)</figcaption></figure><p>If we look at the three steps in the previous images and make a comparison between each one, we can see the following:</p><ol><li>The first test executed: Startup time and the consumed memory are 3,065s, and 170MB less in the CI script correspondingly</li><li>The last test executed: The final heap size is 167MB less in the CI script</li><li>Execution summary: The execution lasted 11,375s less in the CI script</li></ol><p>Finally, let me show you that after the improvement, the tests are running more than 50% faster in the CI environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*GyJUfR-9LoldP6dgdxsZ3w.png" /><figcaption>CI pipeline time for test stages after the improvement</figcaption></figure><p>Thanks for reading! I hope that this article has been helpful. All constructive feedback is welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a186cb5cd4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-improve-the-jest-performance-in-ci-environments-when-using-typescript-66a186cb5cd4">How To Improve the Jest Performance in CI Environments When Using TypeScript</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Cherry-Pick — Selecting Specific Commits to Merge]]></title>
            <link>https://medium.com/better-programming/git-cherry-pick-selecting-specific-commits-to-merge-f1bf245e052a?source=rss-e6b6a26bd0c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1bf245e052a</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Carlos Fernando Arboleda Garcés]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 21:46:46 GMT</pubDate>
            <atom:updated>2023-12-13T14:14:05.537Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git Cherry-Pick — Selecting Specific Commits to Merge</h3><h4>How to merge branches by picking specific commits</h4><figure><img alt="Git branches" src="https://cdn-images-1.medium.com/max/1024/0*IRjmXSa0pY-jxa31" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>As you know, when you are working with <a href="https://git-scm.com/">Git</a> and need to do a merge between two branches, every commit in the <em>source</em> branch will be merged in the <em>target</em> branch without exception. Well, I’m going to tell you a scary story about this very topic and how I managed to solve it.</p><p>Recently, I joined a new software company called <a href="https://patagonian.it/">Patagonian</a>. A few days after I started there, the project manager assigned a task to me that belongs to a bigger task (<a href="https://www.productboard.com/glossary/epics">an epic task</a>).</p><p>When I finished working on my task, I created a pull request, did a merge to the develop branch, and continued with my next task. A few days later, we needed to make a release to staging and then to production, but… an incomplete epic task was merged to develop and would be part of the next release.</p><p>Therefore, we could not do a normal release by merging develop to staging. Actually, we needed to exclude the epic task’s commits from the release. Can you imagine my worry?</p><p>Fortunately, my teammates had already solved this before and had an ace up their sleeve: <a href="https://git-scm.com/docs/git-cherry-pick">git cherry-pick</a>. This Git command makes it possible to apply existing commits to another branch by picking the specific commits that you need.</p><h3>cherry-pick</h3><p>As you can read in the official documentation, the cherry-pick command allows you to choose the specific existing commits to include in another branch.</p><p>To make this easier to understand, I will use a graphical example. Imagine you have a repository with some commits in your develop branch, but some of the changes are part of an incomplete feature that was merged by error (green cherries). In that case, you need to pass only the commits related to finished features (red cherries) to the main branch.</p><figure><img alt="Diagram showing how cherry-pick works" src="https://cdn-images-1.medium.com/max/1024/1*-SvC2ke1DMZ-yidcDyralg.png" /><figcaption>Illustration of cherry-pick command.</figcaption></figure><p>Here are some screenshots that show how to create a cherry-pick using <a href="https://www.sourcetreeapp.com/">Sourcetree</a>. Continue reading the terminal explanation if you want to understand how it works.</p><figure><img alt="Selecting commits to be included in cherry-pick command" src="https://cdn-images-1.medium.com/max/985/1*QEk3Wz1XnxSHrYC_M4zMDA.png" /><figcaption>Selecting commits to be included in cherry-pick command</figcaption></figure><figure><img alt="Setting up and creating cherry-pick using Sourcetree" src="https://cdn-images-1.medium.com/max/463/1*EcmlV_f_uDznpiXFJAP29w.png" /><figcaption>Set up and create cherry-pick using Sourcetree</figcaption></figure><h3>How Can I Use This With Terminal?</h3><p>If you are terminal lover, maybe you will want to do this process using your pretty terminal. Well, consider the following steps.</p><p>Firstly, you have to create a new branch named main_cherry_pick from your target branch main. This branch will be used to apply the selected commits and then merge them into the main branch.</p><p>Secondly, you need to know the commit IDs that you want to include. In the develop branch, execute the next <a href="https://git-scm.com/book/en/v2/Git-Basics-Viewing-the-Commit-History">log command</a> that will show the hash and massage for each commit:</p><pre>git log --pretty=format:&quot;%h %s&quot; </pre><p>You should see something like this:</p><figure><img alt="Result of Git log command" src="https://cdn-images-1.medium.com/max/752/1*_s8YbIXZ6T-vZG7mkgqbRQ.png" /><figcaption>Result of Git log command</figcaption></figure><p>The next step is to check out the target branch. Then copy the needed IDs and execute the cherry-pick command. In this case, I will copy the commit IDs related to files 1, 2, 3, 5, and 6, omitting files 4, 4.1, and 4.2 since those belong to an incomplete feature.</p><pre>git checkout main_cherry_pick<br>git cherry-pick 12670fd 14b185a df931e3 1441727 2296bb0</pre><p>If you don’t have any conflict, you will see one commit confirmation for each selected/included commit in your cherry-pick command:</p><figure><img alt="Output" src="https://cdn-images-1.medium.com/max/704/1*PqECTsLQr9VnwIYgXKWFIw.png" /></figure><p>Finally, you need to push the changes in your main_cherry_pick to the remote branch. Then you have to do a normal merge from main_cherry_pick into the main branch.</p><h3>Conclusion</h3><p>What I have explained here is the most basic use of git cherry-pick. There are several options that you can check out in the official documentation:</p><ul><li><a href="https://git-scm.com/docs/git-cherry-pick">Git - git-cherry-pick Documentation</a></li><li><a href="https://github.com/carboleda/git-cherry-pick">carboleda/git-cherry-pick</a></li></ul><p>Thanks for reading! I hope that this article has been helpful. All constructive feedback is welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1bf245e052a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/git-cherry-pick-selecting-specific-commits-to-merge-f1bf245e052a">Git Cherry-Pick — Selecting Specific Commits to Merge</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web scraping en Node.js para humanos usando scrape-it]]></title>
            <link>https://carboleda.medium.com/web-scraping-en-node-js-para-humanos-usando-scrape-it-3c469bcb786?source=rss-e6b6a26bd0c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c469bcb786</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[cheeriojs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Carlos Fernando Arboleda Garcés]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 21:20:24 GMT</pubDate>
            <atom:updated>2020-04-11T21:20:24.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ug9Ku1WdWYaCHLD6P7XXFQ.png" /><figcaption>Imagen oficial de scrape-it</figcaption></figure><h3>Web scraping en NodeJs para humanos usando scrape-it</h3><p>El web scraping es una práctica en la que a través de un script de código accedemos a una página web como si de un visitante habitual se tratase y obtenemos la información que se encuentra en la página accediendo a los elementos html. Esto es generalmente útil cuando queremos obtener información de un sitio web que no provee un API oficial.</p><p>Aún no será parte de este post, a través del web scraping también es posible generar eventos sobre los elementos de la página simulando las acciones que haría un usuario, lo cual se puede lograr usando un headless browser como <a href="https://github.com/puppeteer/puppeteer">Puppeteer</a>.</p><p><em>El web scraping puede ser considerado un delito dependiendo de la información a la que estás accediendo, el uso que le estés dando a la misma y el fin con el que lo hagas. Yo no soy experto en delitos informáticos así que asegurate de no meterte en problemas.</em></p><h3>¿Cómo funciona web scraping?</h3><p>En esencia, el web scraping para extraer información tiene dos fases:</p><ol><li>Obtener el contenido de la página web a través de una petición HTTP GET.</li><li>Pasar el contenido de la página a la librería de scraping para que lo interprete y así podamos comenzar a hacer queries mediante selectores CSS.</li></ol><p>El web scraping puede hacerse en diferentes lenguajes y lo cierto es que deberíamos elegir el que mejor se adapte lo que queramos hacer. Por sus características hay tendencia a utilizar lenguajes como Python, Perl, Java y <strong>Javascript (NodeJS)</strong>.</p><p>Como ya te podrás dar cuenta, en este caso vamos a utilizar Javascript con <a href="https://nodejs.org/">Node.js</a>, aquí tenemos diferentes opciones para hacer scraping como lo son <a href="https://cheerio.js.org/"><em>cheerio</em></a>, <a href="https://www.npmjs.com/package/noodlejs">noodlejs</a>, <a href="https://www.npmjs.com/package/osmosis">osmosis</a> y en el que nos vamos enfocar en este post<a href="https://www.npmjs.com/package/scrape-it"> <strong>scrape-it</strong></a>.</p><h3>Veamos un ejemplo con una librería de bajo nivel</h3><p>Tomemos como referencia el siguiente html que usaremos para hacer el scraping, este html es una lista de presentaciones que tienen elementos con información de titulo, descripción y un enlace.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6ff7fb029b5fcee234ab2366395c01f/href">https://medium.com/media/b6ff7fb029b5fcee234ab2366395c01f/href</a></iframe><p>Ahora bien, si hiciéramos el scraping utilizando la librería cheerio tendríamos un código como el siguiente:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcd4d52126d05637973b55b082e498ab/href">https://medium.com/media/bcd4d52126d05637973b55b082e498ab/href</a></iframe><p>Como te darás cuenta usando una librería de bajo nivel como cheerio, es necesario ejecutar manualmente cada selector para obtener la información del elemento. Entonces imagina que tienes una gran página con varios niveles de profundidad y mucha información… <strong>😨</strong></p><h3>Ahora usemos scrape-it</h3><p>Después de ver la forma tradicional de hacer scraping, por fin conoceremos al protagonista de este post...</p><p><em>Scrape-it</em> es una librería de NodeJs creada por <a href="https://github.com/IonicaBizau">Ionică Bizău (Johnny B.)</a> que agrega una capa de abstracción sobre cheerio para facilitar muchísimo la extracción de información de la página web sin tenernos que preocupar de varios conceptos relacionados con la manipulación del <a href="https://developer.mozilla.org/es/docs/Glossary/DOM">DOM</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/217abf071aa0d6821f6aa26b0da7f8fa/href">https://medium.com/media/217abf071aa0d6821f6aa26b0da7f8fa/href</a></iframe><p>El resultado será un JSON similar a este:</p><pre>[<br>  {<br>    &quot;title&quot;: &quot;Trabajo remoto&quot;,<br>    &quot;description&quot;: &quot;En esta presentación compartiré...&quot;,<br>    &quot;link&quot;: &quot;/carboleda/remote-work&quot;<br>  }<br>  ...<br>]</pre><p>Como puedes ver scrape-it es muy intuitivo, y es que solo debemos identificar los selectores y definir en un objeto la estructura los atributos donde que queremos que se guarde la información al finalizar el scraping. Scrape-it tambien nos provee entre otras funcionalidades, una función <a href="https://www.npmjs.com/package/scrape-it#params-1"><em>convert</em></a> que podemos usar para convertir el valor obtenido del elemento.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTJO5x5QQM72Q0weWXN%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTJO5x5QQM72Q0weWXN%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FTJO5x5QQM72Q0weWXN%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/b68aedb6cc2b50c1bb58b21e4a64aefc/href">https://medium.com/media/b68aedb6cc2b50c1bb58b21e4a64aefc/href</a></iframe><h4>Algunos enlaces de interés sobre scrape-it por si quieres profundizar</h4><ul><li><a href="https://github.com/IonicaBizau/scrape-it">IonicaBizau/scrape-it</a></li><li><a href="https://scrape-it.saasify.sh/">scrape-it</a></li><li><a href="https://ionicabizau.net/blog/30-how-to-write-a-web-scraper-in-nodejs">How to write a web scraper in Node.js</a></li></ul><blockquote>Todos los créditos de scrape-it son para Ionică Bizău (Johnny B.), este post solo pretende destacar el gran trabajo hecho con esta librería y que muchas más personas la conozcan.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c469bcb786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git patch — Aplicando parches con estilo (No copy/paste)]]></title>
            <link>https://carboleda.medium.com/git-patch-aplicando-parches-con-estilo-no-copy-paste-e63f3de2e61?source=rss-e6b6a26bd0c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e63f3de2e61</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[sourcetree]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[bitbucket]]></category>
            <category><![CDATA[atlassian]]></category>
            <dc:creator><![CDATA[Carlos Fernando Arboleda Garcés]]></dc:creator>
            <pubDate>Wed, 20 Nov 2019 22:01:01 GMT</pubDate>
            <atom:updated>2019-11-20T22:01:01.267Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Git patch — Aplicando parches con estilo (No copy/paste)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOofjb2Xa9-1OUNq47jPoQ.png" /><figcaption>Icons made by <a href="https://www.flaticon.com/authors/freepik">Freepik</a> and <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="http://www.flaticon.com/">Flaticon</a></figcaption></figure><p>Llevo varios años utilizando Git y no tenía ni idea de que esto se podía hacer, pero la necesidad me llevo a encontrar la solución ojeando un poco en las opciones del <a href="https://www.sourcetreeapp.com/">Sourcetree</a> (un cliente Git muy popular en Mac OS) y con una rápida búsqueda en internet. Así que voy a contarles por que llegué a necesitar del git patch…</p><p>Hace un par de días le estaba ayudando a uno de mis compañeros de equipo a implementar una solución para una de sus tareas del sprint. Cuando terminé la implementación que quería sugerirle, necesitaba pasarle los cambios para que él los revisara e hiciera las respectivas pruebas. Lo primero que pensé fue en pasarle cada línea de código que cambié y decirle donde la ponía ya que no eran muchos cambios; lo segundo fue hacer un commit sobre su branch para que él bajara los cambios, pero esa no era mi tarea así que no me pareció pertinente. Así que me puse a revisar en las opciones del Sourcetree y vi algo que decía “Create Patch” y al explorarlo un poco noté que era lo que necesitaba y me pareció genial!</p><p>Te dejo un par de capturas de pantalla de como es la creación de un patch desde Sourcetree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*VUjWyNVBk9zAf-JvKRCdGA.png" /><figcaption>Opciones para crear y aplicar patch. Tomado de <a href="https://www.sourcetreeapp.com/">Sourcetree</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*QI_U9kLpnvMriIhe7gqC8g.png" /><figcaption>Crear un patch a partir de la copia de trabajo actual. Tomado de <a href="https://www.sourcetreeapp.com/">Sourcetree</a></figcaption></figure><h3><strong>Pero cómo lo puedo usar en la terminal??</strong></h3><p>Esta misma pregunta me la hice rápidamente, ya que mi compañero utiliza Linux y Sourcetree solo está para Mac OS. Una búsqueda rápida en San Google me dio la respuesta y es súper fácil de utilizar en su forma más básica:</p><ul><li><strong>Generar un archivo con todos los cambios de la copia de trabajo actual:</strong></li></ul><pre>&gt; git diff &gt; changes.patch</pre><ul><li><strong>Aplicar un archivo patch sobre una copia de trabajo:</strong></li></ul><pre>&gt; git apply changes.patch</pre><p>Lo que te he explicado aquí es el uso más básico de git patch, pero hay una gran cantidad de configuraciones y diferentes usos que se le puede dar. Por eso a continuación te dejo enlaces a la documentación oficial:</p><ul><li><a href="https://git-scm.com/docs/git-format-patch">Git - git-format-patch Documentation</a></li><li><a href="https://git-scm.com/docs/git-apply">Git - git-apply Documentation</a></li><li><a href="https://git-scm.com/docs/git-diff">Git - git-diff Documentation</a></li></ul><p>Espero te sea de mucha utilidad… Si te ha gustado este post, recomiendalo 👏, comenta y comparte!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e63f3de2e61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrando Android de Java a Kotlin]]></title>
            <link>https://carboleda.medium.com/migrando-android-de-java-a-kotlin-a832e8d67205?source=rss-e6b6a26bd0c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a832e8d67205</guid>
            <category><![CDATA[mobil]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Carlos Fernando Arboleda Garcés]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 02:18:36 GMT</pubDate>
            <atom:updated>2019-01-26T05:36:19.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*bFKThmnrLySX7HRCKCyEmg.jpeg" /><figcaption>Imagen de Ruben Tejera. (<a href="https://rubentejera.com/por-que-usar-kotlin/">https://rubentejera.com/por-que-usar-kotlin/</a>)</figcaption></figure><p>Kotlin fue anunciado durante el Google I/O de 2017 como el lenguaje de programación oficial para desarrollar aplicaciones en Android y gracias a su capacidad de interoperar con Java, simplicidad y versatilidad, se está convirtiendo en el lenguaje más utilizado a la hora de programar en Android.</p><p>En este post te explico las características principales de Kotlin y algunas recomendaciones para que comiences a utilizarlo en tus proyectos sin morir en el intento.</p><h3><strong>Qué es Kotlin?</strong></h3><p>Kotlin es un lenguaje de programación de tipado estático que corre sobre la JVM (Java Virtual Machine), desarrollado por JetBrains (los mismos de IntelliJ y Android Studio), con capacidad para interoperar 100% con Java y además puede ser compilado a JavaScript.</p><h3>Por qué migrar de Java a Kotlin?</h3><p>Google estableció que Kotlin es el lenguaje oficial en Android y hoy en día no saber Kotlin te pone en desventaja en el mercado. Y además, tiene una sintaxis que te permite escribir código fuente hasta en un 40% menos de líneas que en Java. Y no puedo dejar de mencionar que la curva de aprendizaje es muy corta!</p><p>Desde hace unos meses comencé la migración de Java a Kotlin, principalmente motivado por la interoperabilidad con Java y la capacidad de controlar las variables nulas de una forma muy fácil, lo cual me permitiría migrar de forma progresiva; Pero me encontré con un universo de posibilidades…</p><h3>Ahora vamos a ver algunas cosas cool de Kotlin!</h3><p>Antes de comenzar en conveniente mencionar algunas particularidades de Kotlin:</p><ol><li>Todo objeto es un <strong>Any</strong>, el nodo raíz de la jerarquía.</li><li>Para la definición de variables se utiliza <strong>val</strong> o <strong>var</strong>, y opcionalmente en frente y separado de <strong>:</strong> (dos puntos ) se define el tipo de dato.</li><li>Se habla de funciones en lugar de métodos.</li><li>Todo miembro de una clase (atributo o función) por defecto es público.</li><li>Kotlin tiene su propio compilador (<em>genera archivos .class</em>).</li><li>Toda expresión o función por defecto devuelve un <strong>Unit</strong> (es como <em>void</em> en java).</li></ol><ul><li><a href="https://kotlinlang.org/docs/reference/null-safety.html"><strong>Null Safety</strong></a><strong> ( ?</strong>,<strong> .?</strong>,<strong> !!</strong>,<strong> ?: )</strong></li></ul><p>Ahora podemos controlar con más facilidad el famoso <em>NullPointerException.</em></p><pre>var a: String = &quot;abc&quot;<br>a = null // error de compilación</pre><p>Para permitir nulos debemos declarar la variable como <em>String</em><strong><em>?</em></strong></p><pre>var a: String<strong>?</strong> = &quot;abc&quot;<br>a = null // ok</pre><p>Para acceder de forma segura a una variable que permite valores nulos, debemos usar la sintaxis .<strong>?</strong></p><pre>val l = a<strong>?.</strong>length // Si b es null el length también devolverá null</pre><p>El operador <strong>!!</strong> permite convertir cualquier variable que soporte valores nulos a non-null al momento de accederla.</p><pre>val l = a!!<strong>.</strong>length //Si b es null se lanzará un NullPointerException</pre><p>El operador Elvis <strong>?:</strong> es una contracción del famoso operador ternario que podemos usar en diferentes lenguajes.</p><pre>int l = a != null ? a.length : -1 // Java<br>val l = a?.length <strong>?:</strong> -1 // (Kotlin) Operador Elvis</pre><ul><li><strong>Expresiones</strong></li></ul><p>En Kotlin los condicionales pueden retornar valores directamente.</p><pre>val l = if(a != null) a.length else -1</pre><pre>val l2 = when(a) {<br>    null -&gt; -1<br>    else -&gt; a.length<br>}</pre><ul><li><a href="https://kotlinlang.org/docs/reference/data-classes.html"><strong>Data class</strong></a></li></ul><p>Nunca antes fue tan fácil definir clases (<a href="https://es.wikipedia.org/wiki/Plain_Old_Java_Object">POJO</a>), Kotlin hace el trabajo sucio por nosotros infiriendo el constructor de clase y las funciones get() / set(). Y heredando de <em>Any</em> las funciones equals() / hasCode() y copy()</p><pre>// Definición<br>data class Usuario (<br>    var nombre: String,<br>    var edad: Int,<br>    var ciudad: String<br>)</pre><pre>// Uso del data class<br>val unUsuario = Usuario(&quot;Carlos&quot;, 30, &quot;Cali&quot;)</pre><ul><li><strong>Parámetros nombrados y valores por defecto</strong></li></ul><p>Con Kotlin podemos olvidarnos de tener que sobrecargar constructores o funciones, ya que podemos declarar uno solo con todos los parámetros e invocarlo pasando solo los necesarios.</p><pre>// Definición<br>data class Usuario (<br>    var nombre: String,<br>    var edad: Int,<br>    val ciudad: String? = &quot;Cali&quot; // Definimos un valor por defecto<br>)</pre><pre>// Uso del data class<br>val usuario1 = Usuario(&quot;Carlos&quot;, 30)<br>val usuario2 = Usuario(nombre = &quot;Carlos&quot;, edad = 30)</pre><ul><li><strong>Template string</strong></li></ul><p>Para darle formato a una cadena (String) insertando valores dinámicos, en Java debemos utilizar <em>String.format</em>, mientras que en Kotlin podemos insertar los valores directamente en la cadena (String) o incluso utilizar expresiones.</p><pre>val saludo = &quot;Hola <strong>$</strong>nombre&quot; //Variable<br>mTextView.setText(&quot;Hola <strong>$</strong>nombre, tu nombre tiene <strong>${</strong>nombre.length<strong>}</strong> caracteres&quot;) // Expresión</pre><p>También es posible usar cadenas de String de multiples líneas.</p><pre>val info = <strong>&quot;&quot;&quot;</strong><br>    Nombre: $nombre<br>    Edad: $edad<br>    Ciudad: $ciudad<br>    <strong>&quot;&quot;&quot;</strong><br>mTextView.setText(info)</pre><ul><li><strong>Property sintax</strong></li></ul><p>Utilizando property sintax podemos omitir el uso explícito de las funciones <em>set</em> y <em>get</em> para simplemente asignar u obtener el valor de la variable como si se tratara de una variable pública.</p><pre>// De manera convencional con los get y set<br>usuario.setNombre(&quot;Carlos Fernando&quot;)<br>mTextView.setText(usuario.getNombre())</pre><pre>// Con property sintax<br><strong>usuario.nombre</strong> = &quot;Carlos Fernando&quot; // set<br>mTextView.text = <strong>usuario.nombre</strong> // get</pre><ul><li><a href="https://kotlinlang.org/docs/reference/typecasts.html#smart-casts"><strong>Smart casting</strong></a></li></ul><p>El compilador detecta cuando verificamos el tipo de una variable y realiza el cast automático en caso de ser necesario.</p><pre>fun demo(a: Any) {<br>    if (a <strong>is</strong> String) {<br>        mTextView.text = a // x es casteada a String automaticamente<br>    }<br>}</pre><ul><li><a href="https://kotlinlang.org/docs/reference/coding-conventions.html#lambdas"><strong>Lambdas</strong></a></li></ul><p>Los lambdas son un herramienta potente de Kotlin que permite simplificar nuestro código al reducir el código necesario para declarar un callback y permitirnos pasar funciones como parámetros sin necesidad de crear interfaces.</p><pre>when (c) {<br>    true -&gt; yes()<br>    false <strong>-&gt; {</strong><br>        not()<br>        println(&quot;c es igual a false&quot;)<br>    <strong>}</strong><br>}</pre><pre>var contador = 0<br>boton.addClickListener <strong>{</strong><br>    contador++<br>    mTextView.text = &quot;Clicks $contador&quot;<br><strong>}</strong></pre><pre>fun setOnClickListener(listener: (view: View) -&gt; Unit) <strong>{}</strong></pre><ul><li><a href="https://kotlinlang.org/docs/tutorials/android-plugin.html"><strong>Extensions</strong></a><strong> — View Binding</strong></li></ul><p>Utilizando el plugin <em>kotlin-android-extensions</em> podremos acceder a las widgets o vistas de nuestros layouts directamente y sin necesidad de utilizar el muy conocido <em>findViewById()</em>.</p><pre><strong>import kotlinx.android.synthetic.main.activity_main.*</strong></pre><pre>class MainActivity : Activity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        <br>        // En lugar de findViewById&lt;TextView&gt;(R.id.textView)<br>        mTextView.text = &quot;Hola, mundo!&quot;<br>    }<br>}</pre><h3>Y qué pasa si ya tengo un proyecto Android en Java?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*iXG027k5mLp4LJXiOeTRyw.gif" /></figure><p><strong>No te preocupes!</strong> Para esto Android Studio tiene un haz bajo la manga. Y es que tiene una opción que nos permite convertir el código Java a Kotlin en dos clics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*Q-9CllZ_k5Tidu4rt7eCMg.png" /></figure><p>Una vez presionamos sobre la opción comenzará a convertir el archivo y después nos preguntará si también queremos actualizar las referencias a ese archivo.</p><blockquote><strong>IMPORTANTE:</strong> Como ya sabemos, Kotlin puede interoperar con Java así que al convertir los archivos debemos revisar minuciosamente cada invocación de métodos/funciones de Java a Kotlin, ya que si una variable es pasada como null a un método que la recibe como non-null obtendremos un error como el siguiente:</blockquote><pre>java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull</pre><p>Veamos un ejemplo:</p><pre>// Kotlin<br>class Mensaje {<br>    //La forma correcta sería: <em>fun mostrar(text: </em>String<strong><em>?</em></strong><em>) {</em><br>    fun mostrar(text: String) { //java.lang.IllegalArgumentException<br>        //Hacer algo<br>    }<br>}</pre><pre>// Java<br>Mensaje.mostrar(null);</pre><p>Yo comencé la migración de una de mis aplicaciones hace un par de meses y actualmente he migrado un 40% a Kotlin obteniendo excelentes resultados. Logré mejorar la estabilidad de la aplicación al utilizar el <strong><em>null safety</em></strong> y simplificar el código fuente usando <strong><em>data class</em></strong><em>, </em><strong><em>lambdas</em></strong><em>,</em><strong><em>View Bindings</em></strong><em> y varias más</em>.</p><p>Si vas a comenzar a migrar un proyecto, te recomiendo que lo hagas de forma progresiva a medida que va necesitando modificar el código existente. No frenes el proyecto hasta migrar todo porque será mucho más desgastante y además puede verse afectado el proyecto. Recuerda que Kotlin puede funcionar perfectamente con Java, así que puedes tomarlo con calma.</p><p>Te dejo los enlaces a dos cursos gratuitos de <a href="https://www.udacity.com/">Udacity</a> sobre Kotlin, el primero te permitirá conocer las todas características del lenguaje y el en segundo puedes ver más en detalle como migrar una aplicación de Java a Kotlin.</p><ul><li><a href="https://www.udacity.com/course/kotlin-bootcamp-for-programmers--ud9011">Kotlin Bootcamp for Programmers | Free Courses | Udacity</a></li><li><a href="https://www.udacity.com/course/kotlin-for-android-developers--ud888">Kotlin for Android Developers | Free Courses | Udacity</a></li></ul><p>Si te ha gustado este post, recomiendalo 👏, comenta y comparte!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a832e8d67205" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>