<?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 Matthew Wong on Medium]]></title>
        <description><![CDATA[Stories by Matthew Wong on Medium]]></description>
        <link>https://medium.com/@mattchw?source=rss-804a12ce32ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Zcb4vK_KbMh11cSaNgMsGQ@2x.jpeg</url>
            <title>Stories by Matthew Wong on Medium</title>
            <link>https://medium.com/@mattchw?source=rss-804a12ce32ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:24:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattchw/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[Mastering the Craft: 10 Key Highlights from the “Clean Code” Bible for Every Developer]]></title>
            <link>https://levelup.gitconnected.com/mastering-the-craft-10-key-highlights-from-the-clean-code-bible-for-every-developer-5a331acb082e?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a331acb082e</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Thu, 11 May 2023 04:35:21 GMT</pubDate>
            <atom:updated>2023-05-11T04:35:21.326Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn the Art of Clean Coding with Javascript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tq9p_d8ZHfKxKXjy" /><figcaption>Photo by <a href="https://unsplash.com/@nublson?utm_source=medium&amp;utm_medium=referral">Nubelson Fernandes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Every programmer, regardless of their level of experience, can benefit from the wisdom in Robert C. Martin’s book, “Clean Code.” It has been curated as one of the must-read book for every software engineer. As a software developer, crafting clean, efficient, and maintainable code should be your top priority. In this article, we’ll explore the key highlights and principles outlined in “Clean Code,” helping you become a better developer and transforming your programming journey for the better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*lAJlBojzOHf7pPY0wBWixQ.jpeg" /><figcaption>Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin</figcaption></figure><p>There are 10 key areas in total that I think everyone should beware of to elevate the coding skills to the next level. They are <strong>Meaningful Names</strong>, <strong>Functions</strong>, <strong>Function Arguments</strong>, <strong>Comments</strong>, <strong>Formatting</strong>, <strong>Objects and Data Structures</strong>, <strong>Error Handling</strong>, <strong>Unit Tests</strong>, <strong>Classes</strong> and <strong>Code Smells</strong>.</p><h3><strong>1. Meaningful Names</strong></h3><blockquote>TL;DR Choose clear, expressive names for variables, functions, and classes to improve readability and maintainability.</blockquote><p>Using meaningful names for variables, functions, and classes in your code is crucial. This makes the code more readable, maintainable, and understandable for both the original developer and others who may work with the code in the future.</p><p>Here’s an example to illustrate the difference between poor and meaningful naming in JavaScript:</p><h4>Poor Naming:</h4><pre>let d; // time in days<br>const r = 5; // interest rate<br>const p = 1000; // principal amount<br><br>function i(p, r, d) {<br>  return (p * r * d) / 36500;<br>}<br><br>const interest = i(p, r, d);</pre><h4>Meaningful Naming:</h4><pre>const principalAmount = 1000;<br>const annualInterestRate = 5;<br>const investmentPeriodInDays = 30;<br><br>function calculateInterest(principal, rate, days) {<br>  return (principal * rate * days) / 36500;<br>}<br><br>const interest = calculateInterest(principalAmount, annualInterestRate, investmentPeriodInDays);</pre><p>In the meaningful naming example, we can see:</p><ol><li>Variables have descriptive names, such as principalAmount, annualInterestRate, and investmentPeriodInDays. These names make it clear what values they represent.</li><li>The function has a meaningful name, calculateInterest, which clearly indicates what it does.</li><li>The arguments for the function also have clear names, like principal, rate, and days, making it easy to understand what inputs the function requires.</li></ol><p>Using meaningful names greatly improves the readability of the code, making it easier for others (and yourself) to understand and maintain it.</p><h3>2. Functions</h3><blockquote>TL;DR Functions should be small, focused, and have a single responsibility. They should do one thing and do it well.</blockquote><p>Having small, focused functions that adhere to the Single Responsibility Principle (SRP) is another highlight of the book. A function should do one thing and do it well, which makes the code more readable, maintainable, and testable.</p><p>Here’s an example to illustrate the difference between a function that doesn’t follow SRP and one that does in JavaScript:</p><h4>Without Single Responsibility Principle:</h4><pre>function processEmployeeData(employeeData) {<br>  const fullName = `${employeeData.firstName} ${employeeData.lastName}`;<br><br>  // Calculate age based on birthdate<br>  const today = new Date();<br>  const birthDate = new Date(employeeData.birthDate);<br>  let age = today.getFullYear() - birthDate.getFullYear();<br>  const monthDifference = today.getMonth() - birthDate.getMonth();<br>  if (monthDifference &lt; 0 || (monthDifference === 0 &amp;&amp; today.getDate() &lt; birthDate.getDate())) {<br>    age--;<br>  }<br><br>  console.log(`Full name: ${fullName}`);<br>  console.log(`Age: ${age}`);<br>}<br><br>const employeeData = {<br>  firstName: &#39;John&#39;,<br>  lastName: &#39;Doe&#39;,<br>  birthDate: &#39;1990-06-15&#39;,<br>};<br><br>processEmployeeData(employeeData);</pre><h4>With Single Responsibility Principle:</h4><pre>function getFullName(employeeData) {<br>  return `${employeeData.firstName} ${employeeData.lastName}`;<br>}<br><br>function calculateAge(birthDate) {<br>  const today = new Date();<br>  const parsedBirthDate = new Date(birthDate);<br>  let age = today.getFullYear() - parsedBirthDate.getFullYear();<br>  const monthDifference = today.getMonth() - parsedBirthDate.getMonth();<br>  if (monthDifference &lt; 0 || (monthDifference === 0 &amp;&amp; today.getDate() &lt; parsedBirthDate.getDate())) {<br>    age--;<br>  }<br>  return age;<br>}<br><br>function displayEmployeeInformation(employeeData) {<br>  const fullName = getFullName(employeeData);<br>  const age = calculateAge(employeeData.birthDate);<br><br>  console.log(`Full name: ${fullName}`);<br>  console.log(`Age: ${age}`);<br>}<br><br>const employeeData = {<br>  firstName: &#39;John&#39;,<br>  lastName: &#39;Doe&#39;,<br>  birthDate: &#39;1990-06-15&#39;,<br>};<br><br>displayEmployeeInformation(employeeData);</pre><p>In the Single Responsibility Principle example, we can see that:</p><ol><li>The original processEmployeeData function is split into three smaller, focused functions: getFullName, calculateAge, and displayEmployeeInformation.</li><li>Each function performs a single task: getFullName returns the full name, calculateAge returns the age, and displayEmployeeInformation displays the information to the console.</li><li>The functions are more readable, maintainable, and testable since they are small and focused.</li></ol><p>By adhering to the Single Responsibility Principle, we make the code easier to understand, maintain, and test, which leads to higher quality software.</p><h3>3. Function Arguments</h3><blockquote>TL;DR Keep the number of arguments to a minimum and avoid output arguments when possible. This enhances the readability and understandability of the code.</blockquote><p>Minimising the number of function arguments and avoiding output arguments are important. They help improving code readability and understandability.</p><p>Having fewer arguments makes it easier to understand the purpose of a function and how it should be used. Additionally, output arguments, which modify the input variables passed by reference, can lead to confusion and unintended side effects.</p><h4>Multiple Arguments:</h4><pre>function calculateTotal(price, taxRate, discountRate) {<br>  const taxAmount = price * taxRate;<br>  const discountAmount = price * discountRate;<br>  return price + taxAmount - discountAmount;<br>}<br><br>const price = 100;<br>const taxRate = 0.1; // 10%<br>const discountRate = 0.05; // 5%<br>const total = calculateTotal(price, taxRate, discountRate);</pre><h4>Fewer Arguments (Using Object):</h4><pre>function calculateTotal({ price, taxRate, discountRate }) {<br>  const taxAmount = price * taxRate;<br>  const discountAmount = price * discountRate;<br>  return price + taxAmount - discountAmount;<br>}<br><br>const product = {<br>  price: 100,<br>  taxRate: 0.1, // 10%<br>  discountRate: 0.05, // 5%<br>};<br>const total = calculateTotal(product);</pre><p>In the Fewer Arguments example, we can see that:</p><ol><li>The function takes a single argument, an object containing the relevant properties (price, taxRate, and discountRate), instead of three separate arguments.</li><li>By passing an object, we make the function more flexible, allowing for additional properties to be added in the future without changing the function signature.</li><li>The code becomes more readable as the properties are grouped together logically within the object.</li></ol><p>Next, let’s consider an example demonstrating the avoidance of output arguments:</p><h4>With Output Argument:</h4><pre>function calculateAreaAndPerimeter(width, height, result) {<br>  result.area = width * height;<br>  result.perimeter = 2 * (width + height);<br>}<br><br>const dimensions = { width: 10, height: 5 };<br>const result = {};<br>calculateAreaAndPerimeter(dimensions.width, dimensions.height, result);</pre><h4>Without Output Argument:</h4><pre>function calculateAreaAndPerimeter(width, height) {<br>  const area = width * height;<br>  const perimeter = 2 * (width + height);<br>  return { area, perimeter };<br>}<br><br>const dimensions = { width: 10, height: 5 };<br>const result = calculateAreaAndPerimeter(dimensions.width, dimensions.height);</pre><p>In the second example, we can see that:</p><ol><li>The function returns an object containing the area and perimeter properties, instead of modifying an input argument.</li><li>The function is easier to understand and use because it <strong>avoids side effects and follows a more common pattern of returning a result</strong>.</li></ol><p>By minimising the number of function arguments and avoiding output arguments, we make our code more readable, understandable, and maintainable.</p><h3><strong>4. Comments</strong></h3><blockquote>TL;DR Comments should be concise and meaningful. They should be used to explain the purpose of code and to clarify complex logic, but should not be used as a substitute for writing clear code.</blockquote><p>Comments should be used appropriately in your code. Comments should be <strong>concise, meaningful</strong>, and used to explain the purpose or intent of the code, or to clarify complex logic. However, comments should not be used as a substitute for writing clear and readable code.</p><h4>Poor Comments:</h4><pre>// Calculate total<br>function calcTot(a, b, c) {<br>  // Add a and b<br>  const t1 = a + b;<br>  // Subtract c<br>  const t2 = t1 - c;<br>  // Return result<br>  return t2;<br>}</pre><p>In this example, comments are used excessively, and the code has poor naming conventions. The comments describe what the code does rather than why it does it. Now let’s refactor the code with better naming and more effective comments:</p><p>Effective Comments:</p><pre>function calculateTotal(price, tax, discount) {<br>  const totalPriceBeforeDiscount = price + tax;<br><br>  // Apply the discount to the total price before discount<br>  const finalPrice = totalPriceBeforeDiscount - discount;<br><br>  return finalPrice;<br>}</pre><p>In the improved example, we can see that:</p><ol><li>Variables and the function have descriptive names, which makes the code self-explanatory, reducing the need for comments.</li><li>Comments are used sparingly, only to clarify the purpose of applying the discount.</li><li>The code is easier to read and understand because the meaningful names and effective comments provide context.</li></ol><p>Keep in mind that <strong>comments can become outdated or incorrect as code evolves</strong>, so it’s essential to keep them updated and relevant. When writing comments, focus on explaining the “why” behind the code or providing context for complex logic that might not be apparent from the code itself.</p><h3>5. Formatting</h3><blockquote>TL;DR Consistent formatting, including indentation and spacing, improves code readability and makes it easier for others to understand and maintain.</blockquote><p>Proper formatting improves code readability and makes it easier for others (and yourself) to understand and maintain the code.</p><h4>Poorly Formatted Code:</h4><pre>function calculateTotal(price,tax,discount){const totalPriceBeforeDiscount=price+tax;const finalPrice=totalPriceBeforeDiscount-discount;return finalPrice;}<br>const productPrice=100;const taxAmount=15;const discountAmount=10;const total=calculateTotal(productPrice,taxAmount,discountAmount);console.log(&quot;Total:&quot;,total);</pre><h4>Well-Formatted Code:</h4><pre>function calculateTotal(price, tax, discount) {<br>  const totalPriceBeforeDiscount = price + tax;<br>  const finalPrice = totalPriceBeforeDiscount - discount;<br>  return finalPrice;<br>}<br><br>const productPrice = 100;<br>const taxAmount = 15;<br>const discountAmount = 10;<br><br>const total = calculateTotal(productPrice, taxAmount, discountAmount);<br>console.log(&quot;Total:&quot;, total);</pre><p>In the well-formatted example, we can see:</p><ol><li>Consistent indentation: Each level of code is indented with an appropriate number of spaces or tabs, making it easier to see the structure of the code.</li><li>Spacing around operators: There is space around operators such as =, +, -, making the code easier to read.</li><li>Line breaks: Line breaks are used to separate variable declarations, function calls, and other statements, which improves readability.</li><li>Consistent use of quotes: The same type of quotes (double or single) should be used consistently throughout the code.</li><li>Clear separation between code blocks: Blank lines are used to separate function declarations, variable declarations, and other logical sections of the code.</li></ol><p>To maintain consistent formatting throughout your codebase, consider using tools like <a href="https://eslint.org/">ESLint</a> and <a href="https://prettier.io/">Prettier</a> to automatically format your code and enforce a consistent style.</p><h3>6. Objects and Data Structures</h3><blockquote>TL;DR Encapsulation should be employed to hide implementation details and expose only necessary information, making it easier to reason about and change the code.</blockquote><p>Encapsulation makes it easier to reason about and change the code since it isolates the impact of changes to a specific component or module.</p><h4>Without Encapsulation:</h4><pre>const account = {<br>  balance: 1000,<br>  deposit: function (amount) {<br>    this.balance += amount;<br>  },<br>  withdraw: function (amount) {<br>    if (amount &lt;= this.balance) {<br>      this.balance -= amount;<br>    } else {<br>      console.log(&#39;Insufficient balance&#39;);<br>    }<br>  },<br>};<br><br>account.balance += 500; // Directly modifying the balance<br>account.withdraw(200);</pre><h4>With Encapsulation:</h4><pre>const createBankAccount = (initialBalance) =&gt; {<br>  let balance = initialBalance;<br>  const deposit = (amount) =&gt; {<br>    balance += amount;<br>  };<br>  const withdraw = (amount) =&gt; {<br>    if (amount &lt;= balance) {<br>      balance -= amount;<br>    } else {<br>      console.log(&#39;Insufficient balance&#39;);<br>    }<br>  };<br>  const getBalance = () =&gt; balance;<br>  return { deposit, withdraw, getBalance };<br>};<br><br>const account = createBankAccount(1000);<br><br>account.deposit(500); // Using provided methods to interact with the balance<br>account.withdraw(200);<br><br>const currentBalance = account.getBalance();</pre><p>In the encapsulated example, we can see that:</p><ol><li>The balance variable is not directly exposed; it is hidden within the closure created by the createBankAccount function.</li><li>Public methods are provided to interact with the account (deposit, withdraw, getBalance), which control access and manipulation of the balance.</li><li>Users of the account object are limited to the provided methods and cannot directly modify the balance, ensuring the integrity of the object&#39;s state.</li></ol><p>By utilizing encapsulation, we create a clear separation between an object’s internal state and the external interface used to interact with that object. This makes the code easier to understand, maintain, and modify, as changes to the internal implementation will have a limited impact on the code that uses the object.</p><h3>7. Error Handling</h3><blockquote>TL;DR Error handling should be treated as a separate concern and should not be mixed with the main logic of the code. Using exceptions instead of error codes is recommended.</blockquote><p>Proper error handling involves anticipating potential issues and handling them gracefully, making it easier to understand, diagnose, and fix problems when they occur. Using exceptions and appropriate error messages can help with this process.</p><h4>Without Error Handling:</h4><pre>function divide(a, b) {<br>  return a / b;<br>}<br>const result = divide(10, 0);<br>console.log(&#39;Result:&#39;, result); // Output: &#39;Result: Infinity&#39;</pre><p>In the above example, there is no error handling for division by zero, leading to an unexpected output of “Infinity.” Now let’s add error handling to handle this case:</p><h4>With Error Handling:</h4><pre>function divide(a, b) {<br>  if (b === 0) {<br>    throw new Error(&#39;Division by zero is not allowed.&#39;);<br>  }<br>  return a / b;<br>}<br><br>try {<br>  const result = divide(10, 0);<br>  console.log(&#39;Result:&#39;, result);<br>} catch (error) {<br>  console.error(&#39;An error occurred:&#39;, error.message);<br>  // Output: &#39;An error occurred: Division by zero is not allowed.&#39;<br>}</pre><p>In the improved example, we can see that:</p><ol><li>The divide() function checks for division by zero and throws an Error with a meaningful message if it occurs.</li><li>The calling code uses a try/catch block to handle the exception, which allows for graceful handling of the error and prevents the application from crashing.</li><li>The error message is helpful and indicates the specific issue that occurred, making it easier to diagnose and fix.</li></ol><p>By implementing proper error handling in your code, it’s easier to understand, diagnose, and fix problems when they occur, and helps to ensure a better user experience when issues arise.</p><h3>8. Unit Tests</h3><blockquote>TL;DR Writing and maintaining a comprehensive suite of unit tests is essential for ensuring code quality and reducing the risk of bugs being introduced.</blockquote><h4>Three Laws of TTD</h4><ol><li>You may not write production code until you have written a failing unit test.</li><li>You may not write more of a unit test than is sufficient to fail, and not compiling is failing.</li><li>You may not write more production code than is sufficient to pass the currently failing test.</li></ol><p>Let’s write tests for a simple Stack class:</p><pre>const Stack = require(&#39;./stack&#39;);<br><br>test(&#39;push() should add an item to the stack&#39;, () =&gt; {<br>  const stack = new Stack();<br>  stack.push(1);<br>  expect(stack.peek()).toBe(1);<br>});<br><br>test(&#39;pop() should remove the top item from the stack&#39;, () =&gt; {<br>  const stack = new Stack();<br>  stack.push(1);<br>  stack.push(2);<br>  expect(stack.pop()).toBe(2);<br>});<br><br>test(&#39;peek() should return the top item without removing it&#39;, () =&gt; {<br>  const stack = new Stack();<br>  stack.push(1);<br>  stack.push(2);<br>  expect(stack.peek()).toBe(2);<br>  expect(stack.peek()).toBe(2); // Repeating the call to ensure the item was not removed.<br>});<br><br>test(&#39;isEmpty() should return true if the stack is empty&#39;, () =&gt; {<br>  const stack = new Stack();<br>  expect(stack.isEmpty()).toBe(true);<br>  stack.push(1);<br>  expect(stack.isEmpty()).toBe(false);<br>});<br><br>// Law 1: Write a failing test before writing production code.<br>// Law 2: Write just enough of a test to fail.<br>test(&#39;pop() should throw an error if the stack is empty&#39;, () =&gt; {<br>  const stack = new Stack();<br>  expect(() =&gt; stack.pop()).toThrow(Error);<br>});<br><br>test(&#39;peek() should throw an error if the stack is empty&#39;, () =&gt; {<br>  const stack = new Stack();<br>  expect(() =&gt; stack.peek()).toThrow(Error);<br>});<br><br>// Law 3: Write just enough production code to pass the test.</pre><p>By adhering to the Three Laws of TDD, we incrementally build the functionality of the Stack class, making sure that each step is guided by a failing test before implementing the corresponding production code. This process ensures that our code has good test coverage and is designed with testability in mind.</p><h4>Keeping tests clean:</h4><ol><li>Make tests readable by using clear and descriptive test names, as shown in the examples above.</li><li>Keep tests focused on a single aspect of the code being tested.</li><li>Ensure tests are independent and can be run in any order. In the examples above, each test creates its instance of Stack and does not rely on the outcome of other tests.</li></ol><h4>Clean tests provide several benefits:</h4><ol><li>They serve as living documentation for your code, helping developers understand how the code is supposed to behave.</li><li>They help you catch regressions and bugs early in the development process, saving time and effort.</li><li>They make it easier to refactor and improve your code with confidence since the tests ensure that existing functionality still works as expected.</li></ol><p>By treating your tests as an essential part of your codebase, you’ll be able to build higher-quality software with fewer bugs and a more stable foundation for future development.</p><h3>Classes</h3><blockquote>TL;DR Classes should be small and focused, adhering to the Single Responsibility Principle. This makes them easier to understand, maintain, and extend.</blockquote><p>Clean Code principles mention encapsulation, small classes, and the Single Responsibility Principle (SRP) when working with classes.</p><p>Let’s say we have an e-commerce application where users can place orders. We’ll create a simple Product class and an Order class that follows the mentioned principles.</p><p>product.js:</p><pre>class Product {<br>  constructor(name, price) {<br>    this.name = name;<br>    this.price = price;<br>  }<br><br>  getName() {<br>    return this.name;<br>  }<br><br>  getPrice() {<br>    return this.price;<br>  }<br>}<br><br>module.exports = Product;</pre><p>In the Product class, we follow the SRP and Encapsulation principles by providing getter methods for the name and price properties. The class is small, focused, and has a single responsibility: to represent a product.</p><p>order.js:</p><pre>class Order {<br>  constructor() {<br>    this.items = [];<br>  }<br><br>  addItem(product, quantity) {<br>    this.items.push({ product, quantity });<br>  }<br><br>  getTotal() {<br>    return this.items.reduce(<br>      (total, item) =&gt; total + item.product.getPrice() * item.quantity,<br>      0<br>    );<br>  }<br>}<br><br>module.exports = Order;</pre><p>In the Order class, we also adhere to the SRP and Encapsulation principles. The class is responsible for managing the order items and calculating the total price. We avoid exposing the internal structure of the items array by providing specific methods for adding items and getting the total.</p><p>Now let’s use the Product and Order classes in another JavaScript file:</p><p>index.js:</p><pre>const Product = require(&#39;./product&#39;);<br>const Order = require(&#39;./order&#39;);<br><br>const product1 = new Product(&#39;Laptop&#39;, 1000);<br>const product2 = new Product(&#39;Mouse&#39;, 50);<br><br>const order = new Order();<br>order.addItem(product1, 1);<br>order.addItem(product2, 2);<br><br>console.log(&#39;Order Total:&#39;, order.getTotal()); // Output: &#39;Order Total: 1100&#39;</pre><p>In this example, we can see that:</p><ol><li>The Product and Order classes follow the SRP, each having a specific responsibility.</li><li>Both classes are small, with a limited number of methods and properties, which makes them easier to understand and maintain.</li><li>Encapsulation is applied, hiding the implementation details and exposing only the necessary information through public methods.</li></ol><p>By adhering to the Clean Code principles when working with classes, we create code that is more maintainable, easier to understand, and promotes better code organisation.</p><h3>10. Code Smells</h3><blockquote>TL;DR Be aware of and address common “code smells” — indicators that the code may have design or structural issues that need to be addressed.</blockquote><p>Code smells are patterns or symptoms in the code that indicate there may be design or structural issues. They don’t always directly cause bugs but can lead to a codebase that’s hard to maintain, extend, and understand. Here are some common code smells and their examples in JavaScript:</p><h4>1. Long Functions</h4><p>Functions that are too long and try to do too much can be hard to understand and maintain.</p><pre>function processData(data) {<br>  // Step 1: validation<br>  if (data === null || typeof data !== &#39;object&#39;) {<br>    return null;<br>  }<br><br>  // Step 2: normalization<br>  data = data.trim().toLowerCase();<br><br>  // Step 3: processing<br>  const words = data.split(&#39; &#39;);<br>  const wordCounts = {};<br>  for (const word of words) {<br>    if (wordCounts[word]) {<br>      wordCounts[word]++;<br>    } else {<br>      wordCounts[word] = 1;<br>    }<br>  }<br><br>  // Step 4: output<br>  console.log(&#39;Word counts:&#39;, wordCounts);<br>}</pre><p>A better approach would be to split this function into smaller, focused functions:</p><pre>function validateData(data) {<br>  if (data === null || typeof data !== &#39;object&#39;) {<br>    return null;<br>  }<br>  return data;<br>}<br><br>function normalizeData(data) {<br>  return data.trim().toLowerCase();<br>}<br><br>function countWords(data) {<br>  const words = data.split(&#39; &#39;);<br>  const wordCounts = {};<br>  for (const word of words) {<br>    if (wordCounts[word]) {<br>      wordCounts[word]++;<br>    } else {<br>      wordCounts[word] = 1;<br>    }<br>  }<br>  return wordCounts;<br>}<br><br>function outputResult(wordCounts) {<br>  console.log(&#39;Word counts:&#39;, wordCounts);<br>}<br><br>function processData(data) {<br>  data = validateData(data);<br>  if (!data) return;<br>  data = normalizeData(data);<br>  const wordCounts = countWords(data);<br>  outputResult(wordCounts);<br>}</pre><h4>2. Large Classes</h4><p>Classes that are too large and have too many responsibilities can be hard to understand and maintain.</p><pre>class UserManager {<br>  constructor(users) {<br>    this.users = users;<br>  }<br><br>  findUser(id) {<br>    return this.users.find(user =&gt; user.id === id);<br>  }<br><br>  getUserEmail(id) {<br>    const user = this.findUser(id);<br>    return user ? user.email : null;<br>  }<br><br>  // ... many other user-related methods<br><br>  log(message) {<br>    console.log(message);<br>  }<br><br>  // ... many other logging methods<br>}</pre><p>In this case, we should split the UserManager class into two separate classes, each with a single responsibility:</p><pre>class UserManager {<br>  constructor(users) {<br>    this.users = users;<br>  }<br><br>  findUser(id) {<br>    return this.users.find(user =&gt; user.id === id);<br>  }<br><br>  getUserEmail(id) {<br>    const user = this.findUser(id);<br>    return user ? user.email : null;<br>  }<br><br>  // ... other user-related methods<br>}<br><br>class Logger {<br>  log(message) {<br>    console.log(message);<br>  }<br>  // ... other logging methods<br>}</pre><h4>3. Duplicate Code</h4><p>Duplicate code makes it hard to maintain and introduce changes since the same logic may need to be updated in multiple places.</p><pre>function processUser(user) {<br>  // ... some processing<br>  console.log(`Processed user: ${user.name}`);<br>}<br><br>function processProduct(product) {<br>  // ... some processing<br>  console.log(`Processed product: ${product.name}`);<br>}</pre><p>In this case, we should extract the common code into a separate function:</p><pre>function logProcessingResult(type, name) {<br>  console.log(`Processed ${type}: ${name}`);<br>}<br><br>function processUser(user) {<br>  // ... some processing<br>  logProcessingResult(&#39;user&#39;, user.name);<br>}<br>function processProduct(product) {<br>  // ... some processing<br>  logProcessingResult(&#39;product&#39;, product.name);<br>}</pre><h4>4. Magic Numbers or Strings</h4><p>Using unexplained numbers or strings in the code can make it hard to understand the purpose or meaning of those values.</p><pre>function calculateTotal(price, quantity) {<br>  return price * quantity * 1.07; // What does 1.07 mean?<br>}</pre><p>A better approach would be to use a constant to represent the value with a meaningful name:</p><pre>const TAX_RATE = 1.07;<br><br>function calculateTotal(price, quantity) {<br>  return price * quantity * TAX_RATE;<br>}</pre><h4>5. Deep Nesting</h4><p>Deeply nested code blocks can be hard to understand and follow.</p><pre>function processOrder(order) {<br>  if (order) {<br>    if (order.items) {<br>      if (order.items.length &gt; 0) {<br>        // ... process the order<br>      } else {<br>        console.log(&#39;No items in the order.&#39;);<br>      }<br>    } else {<br>      console.log(&#39;Order is missing items.&#39;);<br>    }<br>  } else {<br>    console.log(&#39;No order to process.&#39;);<br>  }<br>}</pre><p>We can refactor the code to reduce nesting by using early returns:</p><pre>function processOrder(order) {<br>  if (!order) {<br>    console.log(&#39;No order to process.&#39;);<br>    return;<br>  }<br><br>  if (!order.items) {<br>    console.log(&#39;Order is missing items.&#39;);<br>    return;<br>  }<br>  if (order.items.length === 0) {<br>    console.log(&#39;No items in the order.&#39;);<br>    return;<br>  }<br><br>  // ... process the order<br>}</pre><p>By identifying and addressing code smells, you can improve the overall quality of your codebase, making it easier to understand, maintain, and extend.</p><p>To know more about code refactoring, check out this refactoring guide:</p><p><a href="https://refactoring.guru/refactoring/smells">Code Smells</a></p><p>By following the key highlights and principles from “Clean Code” by Robert C. Martin, you’ll be well on your way to crafting elegant, efficient, and maintainable code. Remember that clean code is an ongoing journey, and it takes consistent effort to master the craft. Embrace these practices and watch as your code becomes clearer, more manageable, and more enjoyable to work with.</p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a331acb082e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/mastering-the-craft-10-key-highlights-from-the-clean-code-bible-for-every-developer-5a331acb082e">Mastering the Craft: 10 Key Highlights from the “Clean Code” Bible for Every Developer</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XSS — Top cybersecurity threat you must know as a developer]]></title>
            <link>https://levelup.gitconnected.com/xss-top-cybersecurity-threat-you-must-know-as-a-developer-c73a71697bd8?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c73a71697bd8</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[xss-vulnerability]]></category>
            <category><![CDATA[xss-attack]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 03:21:06 GMT</pubDate>
            <atom:updated>2022-11-14T03:21:06.043Z</atom:updated>
            <content:encoded><![CDATA[<h3>XSS — Top cybersecurity threat you must know as a developer</h3><h4>Understand what it is, how it works and how to prevent it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YASGmOkhscK1bkzo" /><figcaption>Photo by <a href="https://unsplash.com/@guerrillabuzz_blockchain_pr_agency?utm_source=medium&amp;utm_medium=referral">GuerrillaBuzz Blockchain PR Agency</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you love going to a Japanese restaurant as the food is delicious and you trust that restaurant. However, the lock of the kitchen is broken today and a suspicious man sneaks into the kitchen and replaces all the fresh ingredients with rotten food. The chefs prepare and cook with stale food without noticing that it is not fresh. Eventually, you end up being sick after eating the food from the restaurant you like. This is <strong>Cross-Site Scripting</strong> attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bIkExHPLsD6tRdoV" /><figcaption>Photo by <a href="https://unsplash.com/@kyleunderscorehead?utm_source=medium&amp;utm_medium=referral">Kyle Head</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Your favourite restaurant: <strong>Website</strong></blockquote><blockquote>Ingredients: <strong>HTML and Javascript</strong></blockquote><blockquote>Suspicious Man: <strong>Hacker</strong></blockquote><blockquote>Rotten Food: <strong>Malicious code</strong></blockquote><h3>What is XSS?</h3><p><strong>XSS(Cross-Site Scripting)</strong> is a cybersecurity vulnerability. It has always been one of the top 10 web security risks stated in OWASP.</p><p><a href="https://owasp.org/www-project-top-ten/">OWASP Top 10 | OWASP Foundation</a></p><blockquote>XSS vulnerability allows attackers to inject malicious client-side scripts into trusted web pages viewed by other users and causes serious and unexpected troubles to the users.</blockquote><p>In short, this issue can arise wherever the developer takes user input and renders it onto the page without sanitizing that input.</p><h3>Types of XSS</h3><h4>Stored XSS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*rxcSTqnHcu8nxBGU9al8EQ.png" /><figcaption>Stored XSS</figcaption></figure><ul><li>Injected script is permanently stored in database/message forum/visitor log/comment field</li><li>Victim then retrieves the malicious script from the server when it requests the stored information</li><li>The malicious script is executed and obtains the sensitive data of users and sends it back to the attacker</li></ul><h4>Reflected XSS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*Lp9OgUsdvjPH3uOyIc0CLw.png" /><figcaption>Reflected XSS</figcaption></figure><ul><li>Reflected off the web server, such as in error message, search result, or any other response that includes some or all of the input sent to the server as part of the request</li><li>Hiding the malicious script in URL</li></ul><h4>DOM based XSS</h4><p>When you mutate DOM directly, it becomes easy for an attacker to inject it with data containing malicious JavaScript.</p><p>For examples:</p><ul><li><strong>innerHTML</strong></li></ul><p>As innerHTML renders complete markup and not just text, malicious code would get injected into your site and then execute.</p><pre>target.<strong>innerHTML</strong> = &quot;&lt;img <strong>onerror=\&quot;alert()\&quot;</strong> &gt;&quot;;</pre><ul><li><strong>Ruby on Rails </strong><strong>html_safe</strong></li></ul><p>html_safe() marks the supplied string as &quot;safe for HTML rendering.&quot; This bypasses HTML escaping and potentially creates XSS vulnerabilities.</p><pre>html = &quot;&lt;div&gt;#{name}&lt;/div&gt;&quot;.<strong>html_safe</strong></pre><ul><li><strong>React </strong><strong>dangerouslySetInnerHTML</strong></li></ul><p>Instead of using a selector to get the HTML element and then setting the innerHTML, you can use this property directly on the element.</p><p>However, it can be dangerous for XSS attacks if data is fetched from a third-party source or submitted by users.</p><pre>return (&lt;p <strong>dangerouslySetInnerHTML</strong>={{__html: review}}&gt;&lt;/p&gt;);</pre><h3>Why XSS is not that easy to avoid?</h3><h4>Hard Problems</h4><p>To avoid XSS, the first idea that popped into your head probably is <strong>forbidding </strong><strong>&lt;script&gt; tag</strong>.</p><p>However, we still have <strong>event handler </strong>in some html tags like &lt;img&gt; or &lt;svg&gt; . For example, &lt;svg onload=&quot;alert()&quot; /&gt;</p><p>Then what if we filter out all the html tags? In real world applications, we may need use html tags in some cases. For examples:</p><ul><li>Gmail uses HTML to send emails</li><li>online rich text/markdown editors</li></ul><h3>How to prevent XSS?</h3><p>Actually, there are a lot of things you can do to prevent XSS.</p><p>One way is to use <strong>textContent</strong> instead of innerHTML . textContent returns the raw content with styling inside of all elements, but excludes the HTML element tags. It will automatically HTML Entity Encode.</p><p>Another way is to use XSS sanitiser. For example, <strong>DOMPurify</strong>.</p><p><a href="https://github.com/cure53/DOMPurify">GitHub - cure53/DOMPurify: DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:</a></p><p>For more about XSS prevention, check out the OWASP XSS prevention cheatsheet:</p><p><a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html">Cross Site Scripting Prevention - OWASP Cheat Sheet Series</a></p><h3>Practise Time</h3><p>The best way to learn something is always to get your hands dirty. Google XSS Game is a training platform provided by google to practice XSS. It consist of 6 levels and in each level, you have to execute a JavaScript alert in order to advance to next level.</p><p><a href="https://xss-game.appspot.com/">XSS game</a></p><p>Below is the solution of each level:</p><h4>Level 1 Hello, world of XSS</h4><p>As the the value of url param query is directly added to the body, we can just simply put the javascript code in the param query .</p><ul><li>URL &lt;https://xss-game.appspot.com/level1/frame?query=<strong>&lt;script&gt;alert(1)&lt;/script&gt;</strong></li></ul><h4>Level 2 Persistence is key</h4><p>This is stored XSS as the post doesn’t passes through any filters and html tags are stored directly into the database.</p><ul><li>&lt;img src=&#39;x&#39; onerror=&#39;alert()&#39;&gt; or</li><li>&lt;img onmouseover=&#39;alert()&#39;&gt;</li><li>img tag with event handlers can execute javascript</li></ul><h4>Level 3 That sinking feeling</h4><p>After checking the code, we can inject our payload at the place of num .</p><ul><li>URL <a href="https://xss-game.appspot.com/level3/frame#1&#39;">https://xss-game.appspot.com/level3/frame#1&#39;</a> onerror=&quot;alert()&quot;&#39;</li></ul><h4>Level 4 Context matters</h4><p>In <em>timer.html</em>, &lt;img src=&quot;/static/loading.gif&quot; onload=&quot;startTimer(&#39;{{ timer }}&#39;);&quot; /&gt; .</p><ul><li>URL <a href="https://xss-game.appspot.com/level3/frame#1&#39;">https://xss-game.appspot.com/level4/frame?time=1000&#39;</a>)%3B alert(&#39;</li><li>)%3B means ;</li></ul><h4>Level 5 Breaking protocol</h4><p>As clicking on “Next &gt;&gt; ” will trigger the payload, we can add the code into the param next .</p><ul><li>URL <a href="https://xss-game.appspot.com/level3/frame#1&#39;">https://xss-game.appspot.com/level5/frame/signup?next</a>=javascript:alert()</li></ul><h4>Level 6 Follow the rabbit</h4><p>After checking the code, we can load external javascript file but not from a http or https url. We can try the data URL.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs">Data URLs - HTTP | MDN</a></p><ul><li>URL <a href="https://xss-game.appspot.com/level3/frame#1&#39;">https://xss-game.appspot.com/level6/frame</a>#data:application/javascript,alert()&#39;</li></ul><p>Now you know one of the top web security threats and how to prevent having XSS vulnerabilities on your website.</p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c73a71697bd8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/xss-top-cybersecurity-threat-you-must-know-as-a-developer-c73a71697bd8">XSS — Top cybersecurity threat you must know as a developer</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying what I’ve learnt in Atomic Habits into coding]]></title>
            <link>https://levelup.gitconnected.com/applying-what-ive-learnt-in-atomic-habits-into-coding-cb268137ea35?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb268137ea35</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[habits]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 14:25:45 GMT</pubDate>
            <atom:updated>2022-07-17T03:44:11.797Z</atom:updated>
            <content:encoded><![CDATA[<h3>Applying what I’ve learned in <strong>Atomic Habits</strong> to coding</h3><h4>Build long-lasting habits to be a better programmer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B2zXP2dqa8hSk7tJ" /><figcaption>Photo by <a href="https://unsplash.com/@josemizrahi?utm_source=medium&amp;utm_medium=referral">Jose Mizrahi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>Atomic Habits</em></strong> by James Clear has always been one of the must-read books for high achievers. Today, I’ve finished the book and come up with the most inspiring highlights and takeaways. As a software engineer, I think what I’ve learnt in this book could inspire me to build long-lasting habits to become a better programmer.</p><h3>What I’ve learnt</h3><h4>Fundamentals</h4><p>The power of atomic habits would surprise everyone as the <strong>tiny changes could make a big difference</strong>.</p><p>To build good habits, we have to change our mindsets and beware 4 points. They are <strong>1% better everyday</strong>, <strong>plateau of latent potential</strong>, <strong>focus on systems instead of goals</strong> and <strong>build identity-based habits</strong>.</p><p><strong>1% better everyday</strong></p><p>This is probably the key highlight in this book:</p><blockquote>0.99³⁶⁵ = 0.03</blockquote><blockquote>1.01³⁶⁵ = 37.78</blockquote><p>So doing 1% better everyday could make a significant change a year later.</p><p><strong>Plateau of latent potential</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXeShJFsBQVsezMnjxb6DA.jpeg" /><figcaption>What you think should happen vs What actually happens</figcaption></figure><p><strong>Focus on systems instead of goals</strong></p><p><strong>Goals</strong>: results you want to achieve</p><p><strong>Systems</strong>: processes/steps that lead you to results</p><p>Most people focus on the goals and neglect the systems. But actually, <strong>Goals</strong> are good for setting a direction only. <strong>Systems</strong> are best for making progress.</p><p><strong>Build identity-based habits</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHo0VjLPwPlzBTkPq16mRQ.jpeg" /><figcaption>Outcome-based habits vs Identity-based habits</figcaption></figure><p>The ultimate form of intrinsic motivation is when a <strong>habit becomes part of your identity</strong>. If you want to build a reading habit, your goal is not to read books but to become a reader. If you want to build a running habit, your goal is not to run a marathon but to become a runner.</p><h4>Science of how habits work</h4><p><strong>The Habit Loop</strong></p><ol><li>Cue</li><li>Craving</li><li>Response</li><li>Reward</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qF0pigVY-XKBJdlp1M_D_Q.jpeg" /><figcaption>Cue -&gt; Craving -&gt; Response -&gt; Reward</figcaption></figure><p>The <strong>cue</strong> triggers a <strong>craving</strong>. Then it motivates a <strong>response</strong>. And it provides a <strong>reward</strong>, which satisfies the craving and finally becomes associated with the cue.</p><h4>Summary of how to create good habits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fk2RsgzOf1lgfz9rEhL9CA.jpeg" /><figcaption>Cue: make it obvious; Craving: make it attractive; Response: make it easy; Reward: make it satisfying</figcaption></figure><p><strong>1st Law: Make it Obvious</strong></p><ul><li><strong>Fill out the habits scorecard</strong></li></ul><p>Make a list of your daily habits to become more aware of your behaviour. Write “+” next to it for a good habit. Write “–” if it’s a bad habit. If it is a neutral habit, write “=”.</p><p><a href="https://jamesclear.com/habits-scorecard">The Habits Scorecard: Use This Simple Exercise to Discover Which Habits You Should Change</a></p><ul><li><strong>Use implementation intention</strong></li></ul><blockquote>I will [BEHAVIOUR] at [TIME] in [LOCATION].</blockquote><ul><li><strong>Use habit stacking</strong></li></ul><blockquote>After I [CURRENT HABIT], I will [NEW HABIT].</blockquote><p><strong>2nd Law: Make it Attractive</strong></p><ul><li><strong>Use temptation bundling</strong></li></ul><p>Linking an action you want to do with an action you need to do.</p><p><a href="https://jamesclear.com/temptation-bundling">How to Stop Procrastinating and Boost Your Willpower by Using &quot;Temptation Bundling&quot;</a></p><ul><li><strong>Join a culture</strong></li></ul><p>We tend to imitate the habits of three social groups: <em>the close</em> (family and friends), <em>the man</em>y (the tribe), and<em> the powerful</em> (those with status and prestige)</p><p><strong>3rd Law: Make it Easy</strong></p><ul><li><strong>Reduce friction</strong></li></ul><p>Decrease the number of steps between you and the good habits.</p><ul><li><strong>Prime the environment</strong></li></ul><p>Prepare the environment to make future actions easier.</p><ul><li><strong>Use the Two-Minute Rule</strong></li></ul><blockquote>When you start a new habit, it should take less than two minutes to do.</blockquote><p>Downscale the action so that you can start and finish in 2 minutes or less. Then, you can think about upgrading the action gradually.</p><p><a href="https://jamesclear.com/how-to-stop-procrastinating">How to Stop Procrastinating by Using the &quot;2-Minute Rule&quot;</a></p><ul><li><strong>Automate your habits</strong></li></ul><p>Invest in technology and onetime purchases that lock in future behaviour.</p><p><strong>4th Law: Make it Satisfying</strong></p><ul><li><strong>Use reinforcement</strong></li></ul><p>Give yourself an immediate reward when you complete your habit.</p><ul><li><strong>Use a habit tracker</strong></li></ul><p>Keep track of your habit streak.</p><ul><li><strong>Never miss twice</strong></li></ul><p>When you forget to do a habit, make sure you get back on track immediately.</p><h3>How to apply it to coding</h3><p>As a software engineer, I really want to apply what I’ve learnt in this book to building good habits that help me to write better code right away. There are two habits I want to build and really hope that they can last so as to improve my problem solving skills and be better in coding.</p><h4>Desired Habit 1: Reading books</h4><p>A good book will always give you insights into a certain area. This definitely helps me to grow my mindset when coding. For examples, <em>Clean Code</em>, <em>Clean Architecture</em>, <em>Design Pattern</em>, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gh9gj9nDe-sHf1Lb" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Make it Obvious</strong></p><ul><li>Implementation intention</li></ul><blockquote>I will read 10 pages at 8am in my living room everyday</blockquote><ul><li>Habit stacking</li></ul><blockquote>After I get on the train, I put on my headphone and start reading</blockquote><ul><li>Design my environment</li></ul><p>I will place my iPad in my living room before the night before so I can start reading.</p><p><strong>Make it Attractive</strong></p><ul><li>Temptation bundling</li></ul><p>Listening to my favourite music while reading books. I will choose the instrumental version as it helps me to focus instead of just listening to the music.</p><p><strong>Make it Easy</strong></p><ul><li>Two-Minute Rule</li></ul><p>Start with reading 2 pages first to make it easy to get started.</p><ul><li>Reduce friction</li></ul><p>Leave my phone in the drawer until I finish reading.</p><p><strong>Make it satisfying</strong></p><ul><li>Reinforcement</li></ul><p>Have my favourite snacks. Of course, don’t eat too much.</p><ul><li>Habit tracker</li></ul><p>I can track the progress of reading an eBook on “Books” or “Kindle” apps. Also, I can use Notion to write chapter summaries after reading each chapter.</p><h4>Desired Habit 2: Practise Leetcode</h4><p>Leetcode is a great tool to enhance my problem solving skills and prepare for technical interviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d0a7_KHLt1TlNJoB" /><figcaption>Photo by <a href="https://unsplash.com/@ngeshlew?utm_source=medium&amp;utm_medium=referral">Lewis Kang&#39;ethe Ngugi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Make it obvious</strong></p><ul><li>Implementation intentions</li></ul><blockquote>I will solve one medium Leetcode problem at 9pm on my desk</blockquote><ul><li>Habit stacking</li></ul><blockquote>After I finish my lunch in the office, I get back to my seat and spend 20 minutes on solving one Leetcode problem</blockquote><p><strong>Make it attractive</strong></p><ul><li>Join a culture</li></ul><p>We tend to adopt habits that are praised and approved of by our culture because we have a strong desire to fit in and belong to the tribe. I can join a community on discord or form a coding challenge community with my colleagues.</p><ul><li>Reframe mind-set</li></ul><blockquote>👎 I have to practise Leetcode</blockquote><blockquote>👍 I get to improve my problem solving ability and perform better in coding</blockquote><p><strong>Make it easy</strong></p><ul><li>Two-Minute Rule</li></ul><p>Spend 5 minutes on reading one Leetcode problem to make it easy to get started.</p><p><strong>Make it satisfying</strong></p><ul><li>Reinforcement</li></ul><p>Watch Netflix for 30 mins after solving one problem.</p><ul><li>Habit tracker</li></ul><p>Track the number of questions solved on Leetcode.</p><blockquote>Tiny changes. Remarkable results.</blockquote><p>After reading Atomic Habits, I did apply what I’ve learnt to build my desired habits everyday. Doing a bit of work everyday may not show significant changes immediately. But I believe obvious improvement will be seen one year later. If you also struggle to improve your programming skills, let’s try the methods and start changing today.</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! More content in the <a href="https://levelup.gitconnected.com/">Level Up Coding publication</a>.<br>Follow: <a href="https://twitter.com/gitconnected">Twitter</a>, <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a>, <a href="https://newsletter.levelup.dev/">Newsletter</a><br><strong>Level Up is transforming tech recruiting ➡️ </strong><a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join our talent collective</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb268137ea35" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/applying-what-ive-learnt-in-atomic-habits-into-coding-cb268137ea35">Applying what I’ve learnt in Atomic Habits into coding</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Daily Git Workflow]]></title>
            <link>https://levelup.gitconnected.com/my-daily-git-workflow-a176387d6cd?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a176387d6cd</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[git-workflow]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 12:25:06 GMT</pubDate>
            <atom:updated>2021-09-30T14:59:35.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>All git commands you need to know to handle any project from the start to end</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jusXeDjCMpKHkv0E" /><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>Git is our good friend when developing ourselves or collaborating with our colleagues. It’s hard to imagine without versioning. But, learning git commands can be a nightmare to beginners as there are so many git commands to handle different situations. I’ve been through this process.</p><p>Let me share my daily git workflow when working with real-world projects.</p><p><strong>TL;DR</strong> Below is my daily git workflow to handle most of the projects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*q2QvjS1ASDroVSkuYw-f5Q.png" /><figcaption>My Daily Git Workflow</figcaption></figure><h3>Setup</h3><p>If you just install git on your own machine, you could setup a global git config file with your name and email so all the git projects on your machine could use the default git config.</p><pre>git config --global user.name &lt;YOUR_NAME&gt;<br>git config --global user.email &lt;YOUR_EMAIL&gt;</pre><p>With the above commands, .gitconfig file will be created in your home directory. To check you global git config, you could use:</p><pre>git config --global -l</pre><h4>Start a working area</h4><p>After setting up the global git config, you can really start a new working area.</p><p>If creates an empty repository or turn a directory into a git repository, you could use:</p><pre>git init</pre><p>Executing git init creates a .git subdirectory in the current working directory, which contains all of the necessary Git metadata for the new repository. For example, some subdirectories for objects and refs. A HEAD file is also created which points to the currently checked out commit.</p><p>If you want to work on an existing remote repository, you could use:</p><pre>git clone</pre><p>Internally, git clone first calls git init to create a new repository. It then copies the data from the existing repository, and checks out a new set of working files.</p><h3>Before start making changes on a repository</h3><h3>Branching</h3><p>A branch plays an important role in version control. It helps us to create an independent line of development and serves as an abstraction for the edit/stage/commit process. New commits are recorded in the history for the current branch, which results in a fork in the history of the project.</p><p><a href="https://www.atlassian.com/git/tutorials/using-branches">How to Create a Branch in Git? | Atlassian Git Tutorial</a></p><p>To list all branches including local and remote branches, you could use:</p><pre>git branch -a</pre><p>To list all local branches only, you could use:</p><pre>git branch</pre><p>To list all remote branches only, you could use:</p><pre>git branch -r</pre><p>After checking all the available branches, you could create a new branch or switch to another branch.</p><p>To create new branch, you could use:</p><pre>git branch &lt;BRANCH_NAME&gt;</pre><p>or</p><pre>git checkout -b &lt;BRANCH_NAME&gt;</pre><p>To switch to another branch, you have to create a local branch first to avoid a detached HEAD. You could:</p><pre>git checkout -b &lt;LOCAL_BRANCH_NAME&gt; &lt;REMOTE_BRANCH_NAME&gt;</pre><p>Now you can start developing and changing a bunch of files.</p><h3>After creating and editing files</h3><p>git creates a commit (very much like a patch file) based on the files you want added to commit.</p><p>First, you have to tell git which files are going to be committed. Any changes you have made to those files will be included in the commit. This is called staging.</p><p>To add all files including new untracked files, modified files, or deleted files to the Stage, you could use:</p><pre>git add .</pre><p>To all some files to the Stage only, you could use:</p><pre>git add &lt;FILE_NAME_1&gt; &lt;FILE_NAME_2&gt; &lt;FILE_NAME_3&gt;</pre><p>After adding files to the Stage, you can create a new commit with a commit message. You could use:</p><pre>git commit -m &quot;COMMIT_MESSAGE&quot;</pre><p>Before pushing the committed changes to the remote repository, you may want to inspect your current working repository.</p><p>To list which files are staged, unstaged, and untracked, you could use:</p><pre>git status</pre><p>It shows you what’s been going on with git add and git commit. Status messages also include relevant instructions for staging/unstaging files.</p><h3>Collaboration</h3><p>git is a version control system designed for coordinating work among programmers collaboratively. Your colleagues could be working on the same git repository at the same time. Most of the time you have to get back in sync with changes committed by others before pushing your changes to the remote repository.</p><p>To download contents from the remote repository, you could use:</p><pre>git fetch</pre><p>You can get all the updates from the remote repository, including new branches</p><p>If you found that there are some updates of the branch you are working on and you want to make sure your branch is in sync, you could use:</p><pre>git pull</pre><p>This will fetch all the changes from the remote repository and merge any remote changes in the current local branch.</p><p>To upload local repository content to a remote repository, you could use:</p><pre>git push origin &lt;BRANCH_NAME&gt;</pre><p>If you want to put a forked branch back to the master branch, you could use:</p><pre>git checkout master<br>git pull<br>git checkout &lt;BRANCH_NAME&gt;<br>git merge master</pre><h4>Merge Conflicts</h4><p>Sometimes, the working branch may conflict with the master branch while merging as your colleagues are also developing.</p><p>Here are the normal steps of resolving merge conflicts:</p><ol><li>Open the conflict files and modify them manually</li><li>After modifying the file, you can use <strong>git add </strong>to stage the newly merged files</li><li>Use <strong>git commit</strong> command to create new commit with message</li><li>Use <strong>git push</strong> to upload local repository content to a remote repository</li></ol><p>Basically you know all git commands which are sufficient to handle daily tasks.</p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a176387d6cd" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/my-daily-git-workflow-a176387d6cd">My Daily Git Workflow</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When should you use Node.js?]]></title>
            <link>https://levelup.gitconnected.com/when-should-you-use-node-js-727c7d97fd09?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/727c7d97fd09</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 16:04:14 GMT</pubDate>
            <atom:updated>2021-08-26T16:04:14.422Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sometimes it’s a bad idea to use it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*iohtMNSNC0XQCjlQ.png" /></figure><p>There is a lot of programming languages, development platforms, frameworks and tools for building application servers. As a software engineer, we always have to understand both the advantages and disadvantages and decide when to use which programming language or tool based on our needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkc6fi9SEnu6d_SP_Pz1-g.png" /><figcaption>Traditional web server model</figcaption></figure><p>Before the rise of Node.js, most servers are following the <strong>traditional web server model</strong>. In the traditional web server model, there is a thread pool that maintains multiple threads to deal with incoming requests. Each request will be processed by a specific thread from the thread pool. Once a thread is assigned to handle an incoming request, it will return to the thread pool only until it completes the execution and returns a response. If no thread is present to fulfill the request then the request needs to wait for the next available thread.</p><p>In recent decades, Node.js is growing rapidly not only in start-ups but also in enterprise companies. Tech giants like Amazon, Netflix, eBay, LinkedIn, Paypal and more, are relying on Node.js as their application development environments.</p><p>Although it seems to be a trend for choosing Node.js for server-side development, we need to understand what it really is and its pros and cons before using it in your next project.</p><h3>What is Node.js?</h3><p>Node.js is first released in 2009 and I believe most of developers have heard of it and probably are using it as the web-serving solution. But not everyone truly understand its features.</p><h4>Runtime environment</h4><p>First of all, Node.js is not a programming language or a framework but a <strong>JavaScript runtime environment</strong>. With Node.js, JavaScript code can be executed without a browser and this encourages developers to build full-stack applications solely using Javascript.</p><h4><strong>Non-blocking I/O event loop</strong></h4><p>Another major thing which spots the difference between Node.js and the traditional web server is <strong>Node.js runs on a single thread with an event loop</strong> to perform non-blocking I/O operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gXf2PhsqqoPvMlnkx2Ybw.png" /></figure><p>The Node.js event loop executes the Javascript code on its single thread and processes the requests asynchronously. If the requests consist of blocking I/O tasks, the event loop will pass the tasks to the internal thread pool to handle any intensive operation. Once the operation is finished, the responsible threads will notify the event loop.</p><p>This is the feature of Node.js and it allows you to allocate more of your system’s time and memory handling requests instead of wasting your space and time overheads for threads (i.e. context-switching).</p><p>To sum up:</p><ul><li>Node.js is a <strong>Javascript runtime environment</strong></li><li>Node.js has an <strong>Event Loop</strong> to handle non-blocking and event-driven I/O operations</li></ul><h3>When to use Node.js?</h3><p>Now we have a brief picture of what Node.js really is. Let’s take a look at how we can make use of its advantages to maximise our application performance.</p><h4>API Application</h4><p>Node.js is also a great choice for constructing an API application with both relational and non-relational databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*xC6p1j1qntmoOfwT_QDB5g.png" /></figure><p>Why Node.js is suitable? It’s all because of the <strong>Single thread with event loop</strong>. This makes:</p><ul><li>Node.js runs on a single thread which makes it easier to handle up to 10,000 concurrent requests</li><li>All blocking I/O tasks (i.e. database access) are always being processed asynchronously by internal threads without interrupting the main thread</li></ul><p>This makes Node.js good to handle the requests, make database operations, and expose JSON objects for clients. In the past, some say Node.js is only suitable for non-relational database because of a lack of ORMs for relational database. But now there are a lot of mature ORM solutions like <a href="https://sequelize.org/master/">Sequelize</a> to query and manipulate data from a relational database.</p><h4>Real-time applications</h4><p>Due to the event-driven and asynchronous nature, Node.js is good at building real-time applications like messaging, notifications delivery, live streaming and collaboration tools.</p><p>Let’s take messaging application as an example. Messaging application is:</p><ul><li>lightweight</li><li>high traffic</li><li>data-intensive but requires light computation power</li></ul><p>Node.js is well-suited for implementing messaging application.</p><p><a href="https://socket.io/">Socket.io</a>, a JavaScript library for realtime and bidirectional communication, is available to build a messaging application easier and faster. It uses the <a href="https://en.wikipedia.org/wiki/WebSocket">WebSocket</a> protocol with HTTP long polling as a fallback option and offers the capacity of not only messaging but also binary streaming, document collaboration and real-time analytics.</p><h4>Microservices</h4><p>Apart from that, Node can also be used to build microservices — an architectural approach based on building an application as a collection of small services. Each microservice has its own data model and manages its own data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*CPtvhQIc7OdW7WaBGnC6xA.png" /></figure><p>There are a lot of programming languages for building microservices. One of them is NodeJS. So, How does Node.js’s features make it one of the best choices for microservices?</p><ul><li>Node.js assigns I/O tasks to the internal IO threads without blocking the main thread</li><li>Node.js uses event-driven architectures which can be highly decoupled</li></ul><p>With microservices, a large scale system can be broken down into small pieces of microservices and be deployed independently. Each microservice can have a higher autonomy and scales up or scales down freely.</p><h3>When not to use Node.js?</h3><p>Every programming language, however, has its disadvantages.</p><h4>CPU intensive tasks</h4><p>When it comes to heavy computation, Node.js is not the best solution for that. Event loop, which runs on a single thread, is weak at handling CPU intensive tasks.</p><p>The event loop is responsible for every incoming requests from the clients and passed the I/O tasks to the internal threads. However, this event loop runs on a single thread. When the thread is blocked by all other tasks, incoming requests would have to wait for the thread to be unblocked before they can be processed.</p><h3>Conclusion</h3><p>Node.js is, without a doubt, very different from the traditional web server model. Its event loop offloads I/O operations to the system kernel whenever possible. However, we have to be aware of the weakness of its event loop. <strong>Never use Nodejs to solve compute scaling problems</strong>.</p><p>I hope you have a better understanding of the characteristics of Node.js and when you should use it.</p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=727c7d97fd09" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/when-should-you-use-node-js-727c7d97fd09">When should you use Node.js?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operating System — Scheduling]]></title>
            <link>https://levelup.gitconnected.com/operating-system-scheduling-fb7dc14b8c0a?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb7dc14b8c0a</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 20:42:05 GMT</pubDate>
            <atom:updated>2021-08-03T20:42:05.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>Operating System — Scheduling</h3><h4>Understand Scheduling in just 5 minutes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DfGRNybrhM4A4KAv" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your computer is performing hundreds and thousands of tasks at the same time every day. Have you ever thought about how it handles so many things in a stable and organised way?</p><h3>What is Scheduling?</h3><p><strong>Scheduling</strong> is the procedure of deciding which process to run next and allocate resources to it to perform tasks. We often mention “<strong>Context Switching</strong>” when discussing scheduling. It is the actual switching procedure, from one process to another.</p><h4>When does context switching happen?</h4><p>The image below shows the lifecycle of a process. If you want to know more about process management, feel free check out my previous article.</p><p><a href="https://levelup.gitconnected.com/operating-system-process-management-26c73901166">Operating System — Process Management</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*gqAX5VTFvuQUl2GC7D1qOA.png" /><figcaption>Process lifecycle</figcaption></figure><p>There are many ways to make context switching happen:</p><ol><li>Whenever a process goes to blocking / waiting state (wait()/sleep())</li><li>When a POSIX signal arrives (SIGCHLD)</li><li>When an interrupt arrives (keystroke)</li><li>When the OS scheduler interrupts and stops the process (round-robin, round-robin with priority)</li></ol><h4>Take a deep look on context switching</h4><p>You may be wondering what <strong>context switching</strong> is actually doing in.</p><p>Suppose a process gives up running on the CPU. For examples, calling sleep().</p><p>Then, the scheduler is going to choose the next process to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*QPqcXMauJiMtY1ejVdVatA.png" /><figcaption>Backup all current context</figcaption></figure><p>But, before the scheduler can seize the control of the CPU, CPU has to backup all current context of that process to the kernel-space memory:</p><ul><li>current register values</li><li>program counter (which line of code the current program is at)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*kHPuqLyPpGrCu_g_-u2lyg.png" /><figcaption>Load context of process from the main memory</figcaption></figure><p>If the scheduler decides to schedule another process in the ready queue, the schedule has to load the context of that process from the main memory to the CPU.</p><p>This entire operation is called “<strong>Context Switching</strong>”.</p><h4>Context Switching is expensive</h4><p>Direct costs in kernel:</p><ul><li>Save and restore registers, etc.</li><li>Switch address space (expensive instructions)</li></ul><p>Indirect costs:</p><ul><li>cache</li><li>buffer cache</li><li>TLB misses</li></ul><h3>What is process scheduling?</h3><p>Scheduling is required because the number of computing resource — the CPU — is limited.</p><p>When a process is chosen by the scheduler, the process would have the CPU until:</p><ul><li>the process voluntarily waits for I/O</li><li>the process voluntarily releases the CPU (e.g. exit())</li><li>the process detects particular kinds of interrupts (e.g. periodic clock interrupt)</li></ul><p>In old days, it was called “<strong>time-sharing</strong>”. Nowadays, all systems are time-sharing.</p><p>For process scheduling, there are different scheduling algorithms.</p><h3>Scheduling algorithms</h3><h4>Shortest-job-first (SJF)</h4><p>Whenever a new process arrives at the system, the scheduler steps in and selects the next task based on their remaining CPU requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrsrXNPlkk9noo1XVwMfDw.png" /><figcaption>Scheduler will CPUs to handle process A first as there is only one process</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spLvr5sBKXUenkpYqFX4tw.png" /><figcaption>Scheduler will assign CPUs to handle the new process (process B) first as it requires the least resources</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qc_dFOhmD2nO_am0CDwM1w.png" /><figcaption>After running process B, the CPUs will continue to handle process A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzL5P3FYtTaxADXMBXzGYg.png" /><figcaption>If new process (process C) with lower resources requirement arraives, the CPUs will switch to handle it first</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmwZN_gNdcn8SRpEM3uzhg.png" /><figcaption>After running process C, the CPUs will continue to handle process A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0tzCa0sreVzfv1lnvRzUw.png" /><figcaption>Process D will be ignored for now as process A requires less resources</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHKMyy5Oj9VMDLWnBbC6Xg.png" /><figcaption>Process D will be handled after finishing process A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boUFzAnPnjRa9UerWvAqtg.png" /><figcaption>Done</figcaption></figure><p>The drawback of this algorithm is the number of context switching can be high as <strong>context switching is expensive</strong>.</p><h4>Round-robin</h4><p>Round-Robin (RR) scheduling is preemptive.</p><p>Processes are running one-by-one as a circular queue and with no priority.</p><ul><li>New processes are added to the tail of the ready queue</li><li>New process arrives will not trigger a new selection decision</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJPA3QjaqMjJusnuLBuGQg.png" /><figcaption>Every process is given a quantum of 2, or the amount of time allowed to execute</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G54reQ_pekEH3APinCoaEA.png" /><figcaption>CPUs will handle process A first and only process the given quantun</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVa7DcpfIl5ydGdSDHc8ow.png" /><figcaption>After process A has used up the quantum, scheduler will then assign CPUs to handle the next process, which is process B</figcaption></figure><p>Whenever the quantum of a process is used up, the process releases the CPU and this is the preemption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dAyFzZSWXcgdsxJGNClLQ.png" /><figcaption>Process B will consume the quantum</figcaption></figure><p>Then, the scheduler steps in and it chooses the next process which has a non-zero quantum to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6x0mdjxluj9DgLsFC3fY4Q.png" /><figcaption>After process Bhas used up the quantum, scheduler will then assign CPUs to handle the next process, which is process C</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wy-fds8022LhJTCsDrZcw.png" /><figcaption>After finishing process C, CPUs will then handle process D</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOS1omMkeUIXXSCWFEmR6A.png" /><figcaption>After a round, the quantums of the processes have been reset</figcaption></figure><p>If all processes in the system have used up the quantum, they will be re-charged to their initial values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJ5SBjm8isD1Mpn3NwDHDQ.png" /><figcaption>CPUS will handle process A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVEyRkAsxOQjWeqPiptrJA.png" /><figcaption>CPUs have finished processing process B</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-_cHcCsOmLKdHiPuomrQQ.png" /><figcaption>At the meanwhile, quantum of process A are reset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nObvL9rq-zFA6U2CmKeNg.png" /><figcaption>Done</figcaption></figure><h4>Priority Scheduling</h4><p>A task is given a priority and is usually an integer.</p><ul><li>A scheduler selects the next process based on the priority</li><li>Higher priority process + Round-Robin = priority queue + new process arrival triggers a new selection</li></ul><p><strong>Static priority scheduling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZ3bWfSK7_1RkwBgUphb0g.png" /><figcaption>Static priority scheduling</figcaption></figure><p>Process is assigned a fix priority when they are submitted to the system. The highest priority class will be selected. The tasks are usually short-lived, but important</p><p>To prevent high-priority tasks from running indefinitely, lower priority classes will be scheduled only when the upper priority classes has no tasks.</p><p><strong>Multiple queue priority scheduling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twECmPIZiMhT9U4BOe9wKw.png" /><figcaption>Multiple queue priority scheduling</figcaption></figure><p>It is still a priority scheduler. But, at each priority class, different schedulers may be deployed. The priority can be a mix of static and dynamic.</p><h4>Next Steps</h4><p>If you’re reading this line, congratulations!!! You made it. You have learnt the basics of scheduling and the most common scheduling algorithms.</p><p>Feel free to check other articles about operating system below:</p><p><a href="https://mattchw.medium.com/overview-of-operating-system-cc3f6f6bb062">Overview of Operating System</a></p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb7dc14b8c0a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/operating-system-scheduling-fb7dc14b8c0a">Operating System — Scheduling</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operating System — Threading]]></title>
            <link>https://levelup.gitconnected.com/operating-system-threading-ae9697322efb?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9697322efb</guid>
            <category><![CDATA[network]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 15:43:54 GMT</pubDate>
            <atom:updated>2021-07-13T15:46:27.661Z</atom:updated>
            <content:encoded><![CDATA[<h3>Operating System — Threading</h3><h4>Understand threading in just 4 minutes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vh0PcqmIZOhKuZ3F" /><figcaption>Photo by <a href="https://unsplash.com/@redviking509?utm_source=medium&amp;utm_medium=referral">John Anvik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Threading</strong> is one of the most important concepts for a software engineer. It allows a program to operate tasks simultaneously. You must have heard of threading very often. But do you really know what it is? How about processes? Do you know the difference between a <strong>thread</strong> and a <strong>process</strong>? Do you know how to <strong>create a thread</strong>?</p><p>If you’re an advanced developer or computer science graduate, treat this article as a refresher. If you’re new to the operating system world, it is a tailor-made for you.</p><h3>What is a Thread?</h3><p>A thread is a basic unit of CPU utilization and it is comprised of:</p><ul><li>threadID</li><li>program counter</li><li>register set</li><li>stack</li></ul><p>For the threads belonging to the same process, they share:</p><ul><li>code section</li><li>data section</li><li>other operating system resources (e.g. open files &amp; signals)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7-o4NZtjNMyfNEb_NgvZw.png" /><figcaption>Single-threaded process vs Multi-threaded process</figcaption></figure><h3>Process vs Thread</h3><h4>Process:</h4><ol><li>Heavy weight</li><li>Costly creation (require more memory)</li><li>Cannot access memory area of other processes</li><li>Costly process switching</li><li>Different processes mean different programs</li></ol><h4>Thread:</h4><ol><li>Light weight</li><li>Cheap creation (require less memory)</li><li>Share the same memory area with other threads</li><li>Cheap thread switching</li><li>Multiple threads mean the same code segment</li></ol><h3>Multi-threads in usersapce memory</h3><p>One of the benefits of Multi-threading is ease of data sharing.</p><p>Data sharing can be done via:</p><ul><li>global variables</li><li>dynamically allocated memory.</li></ul><p>All threads share the global variable zone and the heap and they can read from and write to both areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*0mk4lmSFr3k0DcuU8FCN0Q.png" /><figcaption>Multi-threads share data together</figcaption></figure><p>However, this leads to <strong>mutual exclusion</strong> and <strong>synchronization</strong> problems. Check my previous article if you want to know more about mutual exclusion.</p><p><a href="https://levelup.gitconnected.com/operating-system-inter-process-communication-ipc-60a288b11d18">Operating System — Inter-process Communication (IPC)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*KQjqr_q9LonmYs65K6PPKQ.png" /><figcaption>Userspace memory of a process</figcaption></figure><h4>Code and thread function</h4><p>All threads share the same code and athread can start with one specific function, which is the thread function.<br><br>A thread function can invoke other functions or system calls. But a thread never returns to the caller of the thread function.</p><h4>Local variables</h4><p>Each thread has its own stack for the local variables.</p><h3>How to create threads?</h3><h4>Pthread library</h4><p>Let’s have a look of the difference between system calls for process and thread.</p><p>System calls for Process</p><ul><li>Creation: <strong>fork()</strong></li><li>I.D. Type: <strong>PID </strong>and it is an integer</li><li>Get identity: <strong>getpid()</strong></li><li>Termination: <strong>exit()</strong></li><li>Wait for child termination: <strong>wait()</strong> <strong>/ waitpid()</strong></li><li>Kill: <strong>kill()</strong></li></ul><p>System calls for Thread</p><ul><li>Creation: <strong>pthread_create()</strong></li><li>I.D. Type: <strong>pthread_t </strong>and it is a structure</li><li>Get identity: <strong>pthread_self()</strong></li><li>Termination: <strong>pthread_exit()</strong></li><li>Wait for child termination: <strong>pthread_join()</strong></li><li>Kill: <strong>pthread_kill()</strong></li></ul><h4>Example of thread creation using pthread_create()</h4><p>Thread Function:</p><pre>void * hello( void *input ) {<br>  printf(“%s\n”, (char *) input);<br>  pthread_exit(NULL);<br>}</pre><p>Main Function:</p><pre>int main(void) {<br>  pthread_t tid;<br>  <strong>pthread_create(&amp;tid, NULL, hello, “hello world”);</strong><br>  pthread_join(tid, NULL);<br>  return 0;<br>}</pre><h3>Mutual exclusion in Pthread</h3><p>Semaphore can be used as a lock but it can be very hard to code and read.</p><p>POSIX Thread offers <strong>Mutex</strong> and <strong>Condition variable</strong> which can used with POSIX semaphore together.</p><h4><strong>Mutex</strong></h4><p><strong>Initialization</strong></p><pre>pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;</pre><p><strong>Locking</strong></p><pre>pthread_mutex_lock(&amp;mutex);</pre><ul><li>If the mutex is not locked, lock the mutex.</li><li>If the mutex is locked, block the calling thread.</li></ul><p><strong>Unlocking</strong></p><pre>pthread_mutex_unlock(&amp;mutex);</pre><p>Example of a thread function using mutual exclusion:</p><pre>while(TRUE) {</pre><pre>  <strong>pthread_mutex_lock(&amp;mutex);</strong></pre><pre>  if(shared &lt; 100)<br>    <strong>shared++; // shared object</strong><br>  else {<br>    <strong>pthread_mutex_unlock(&amp;mutex);</strong><br>    break;<br>  }</pre><pre>  <strong>pthread_mutex_unlock(&amp;mutex);</strong></pre><pre>  sleep(rand() % 10);</pre><pre>}</pre><h4>pthread_mutex vs POSIX Semaphore</h4><p>POSIX semaphore</p><ul><li>Owned by kernel</li><li>Can synchronize across process/thread</li><li>any thread/process can execute <strong>sem_wait()</strong> &amp; <strong>sem_post()</strong> on<br>any semaphores</li></ul><p>pthread_mutex</p><ul><li><strong>Synchronize across the threads of the same process only</strong></li></ul><p>pthread_mutex is definitely a lot easier to use and debug.</p><h4>Condition Variable</h4><p><strong>Initialization</strong></p><pre>pthread_cond_t cond = PTHREAD_COND_INITIALIZER;</pre><p><strong>Waiting</strong></p><pre>pthread_cond_wait(&amp;cond, &amp;mutex);</pre><p><strong>Wakeup no. 1</strong></p><pre>pthread_cond_signal(&amp;cond);</pre><p>This function <strong>wakes up a thread which is waiting on the </strong>condition variable <strong>“cond”</strong>. If there are more than one thread waiting, at least one of those threads will wake up.</p><p><strong>Wakeup no. 2</strong></p><pre>pthread_cond_broadcast(&amp;cond);</pre><p>This function <strong>wakes up all threads</strong> which is waiting on the condition variable “cond”.</p><h4>Next Steps</h4><p>If you’re reading this line, congratulations!!! You made it. You have learnt the basics of threading and how to create it.</p><p>Feel free to check other articles about operating system below:</p><p><a href="https://mattchw.medium.com/overview-of-operating-system-cc3f6f6bb062">Overview of Operating System</a></p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9697322efb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/operating-system-threading-ae9697322efb">Operating System — Threading</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operating System — Memory Management]]></title>
            <link>https://levelup.gitconnected.com/operating-system-memory-management-7f130d242e68?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f130d242e68</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 15:37:42 GMT</pubDate>
            <atom:updated>2021-06-29T00:24:34.025Z</atom:updated>
            <content:encoded><![CDATA[<h3>Operating System — Memory Management</h3><h4>Understand Memory Management in just 5 minutes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b8XBVHV6M7K4QnOk" /><figcaption>Photo by <a href="https://unsplash.com/@jeremy0?utm_source=medium&amp;utm_medium=referral">Jeremy Zero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Memory Management</strong> is the process of managing computer memory, moving processes between main memory and disk to boost the overall performance of the system. It is vitally important as it helps OS to keep track of every memory location, including allocating memory and freeing it.</p><p>In this article, I am going to focus on userspace memory only as it directly affects the execution of application software and every softare engineer should know about it.</p><h3>User-space memory management</h3><h4>Address Space</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Srd3CFvM3GkWvuG5hk7Y2A.png" /><figcaption>Address space</figcaption></figure><p>One address is mapped to one byte. On a 32-bit system, the maximum amount of memory in a process is 2^32 bytes, which means <strong>4GB</strong>. That means the memory of a process on a 64-bit system can be <strong>16EB</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*JjiUBGG3JPe1vl5MJhIlJA.png" /><figcaption>More detail about address space</figcaption></figure><p>Each process has its own address space and it should have 2^32 bytes (4GB) of memory. (I am talking about a 32-bit system)</p><p>Address space consists of 4 main kinds of memory. They are:</p><ol><li>Program code &amp; segments</li><li>Data segment</li><li>Stack</li><li>Heap</li></ol><h4>Program code &amp; constants</h4><p>Let’s have a look at an example of code segment:</p><pre>int main(void) {<br>  <strong>char *string = &quot;hello&quot;;</strong> //string constant<br>  printf(&quot;\&quot;hello\&quot; = %p\n&quot;, <strong>&quot;hello&quot;</strong>); // &quot;hello&quot; is used<br>  printf(&quot;String pointer = %p\n&quot;, <strong>string</strong>); // same constant is used<br>  return 0;<br>}</pre><p>A computer is very clever. In this example, the program is always using the same string constant as long as it is unique.</p><p>Most of the developers or software engineers with basic programming knowledge definitly know it. Codes and constants are both <strong>read-only</strong>.</p><ul><li>We cannot change the values of the codes nor the constants during runtime.</li><li>Constants are stored in code segment and Only unique constants are stored.</li></ul><h4>Data Segment &amp; BSS</h4><p>Global and static variables are stored in data segment and BSS(Block Started by Symbol). Data Segment is for storing initialized variables while BSS is for storing uninitialized variables.</p><p>Let’s take a look at the example below:</p><pre>int global_int = 1; // global</pre><pre>int main(void) {<br>  int local_int = 1;<br>  static int static_int = 1; // static</pre><pre>  printf(&quot;local_int addr = %p\n&quot;, &amp;local_int ); // e.g. 0xbf8bb8ac<br>  printf(&quot;static_int addr = %p\n&quot;, &amp;static_int ); // e.g. <strong>0xxxxxx18</strong><br>  printf(&quot;global_int addr = %p\n&quot;, &amp;global_int ); // e.g. <strong>0xxxxxx14</strong><br>  return 0;<br>}</pre><p>If you try to run the c program on your own machine. We will find that the global and static variable are just stored next to each other. That means they are in the same segment.</p><p>Let’s take a look at another example:</p><pre>int global_bss; // uninitialized<br>int global_data = 1; // initialized</pre><pre>int main(void) {<br>  static int static_bss; // uninitialized<br>  static int static_data = 1; // uninitialized</pre><pre>  printf(&quot;global bss = %p\n&quot;, &amp;global_bss ); // e.g. <strong>0xxxxxx88</strong><br>  printf(&quot;static bss = %p\n&quot;, &amp;static_bss ); // e.g. <strong>0xxxxxx84</strong><br>  printf(&quot;global data = %p\n&quot;, &amp;global_data ); // e.g. <strong>0xxxxxx14</strong><br>  printf(&quot;static data = %p\n&quot;, &amp;static_data ); // e.g. <strong>0xxxxxx18</strong><br>}</pre><p>This shows that data and BSS are stored separately.</p><h4>Stack</h4><p>The stack is an area which stores:</p><ul><li><strong>local variables</strong>,</li><li><strong>function parameters</strong>, and</li><li><strong>environment variable</strong></li></ul><p>created by a function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*wdYnOQTYEnHfxTnhRY3u2g.png" /><figcaption>Example of stack</figcaption></figure><p>When a function is called, a stack frame will be pushed. When a function returns, the stack frame will be poped. This job is not done by the kernel but instead it is done by the compiler. It hardcodes this mechanism into our programs.</p><p>A function can read and write anywhere in the stack, not restricted to its own stack frame.</p><p>However, the compiler cannot estimate the stack’s size in compile time.<br>The number of function calls depends on a lof of things like the program state, the user inputs, etc. The kernel can only reserve certain space for the stack.</p><p>Let’s thing a bit more. <strong>What if there is no more space left in the stack?</strong> What will the OS do? Enlarge the stack? What if it is a chain of endless<br>recursive function calls?</p><p>What will happen?</p><ul><li>Exception caught by the CPU</li><li><strong>Stack overflow</strong> exception</li><li>Program terminated</li></ul><p><strong>Solutions</strong></p><ul><li>Minimizing the number of arguments</li><li>Minimizing the number of local variables</li><li>Minimizing the number of calls</li><li>Use global variables</li><li>Use malloc</li></ul><h4>Heap</h4><p>When a program is just running, the entire heap space is unallocated or empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*wKzBNtyOtP-DcBDWjgEbpg.png" /><figcaption>Heap is growing when malloc is called</figcaption></figure><p>The allocated space growing or shrinking depends on <strong>malloc() </strong>and <strong>free() </strong>system calls. <strong>malloc()</strong> grows the heap space while <strong>free()</strong> shrinks the heap space.</p><p>When “<strong>malloc()</strong>” or “<strong>free()</strong>” is called, it may call the “brk()” system call. The “<strong>brk()</strong>” system call mark where the address of the heap ends.</p><ul><li><a href="https://man7.org/linux/man-pages/man3/malloc.3.html">malloc(3) - Linux manual page</a></li><li><a href="https://linux.die.net/man/3/free">free(3) - Linux man page</a></li><li><a href="https://man7.org/linux/man-pages/man2/brk.2.html">brk(2) - Linux manual page</a></li></ul><p>“<strong>free()</strong>” de-allocates any allocated memory. When a program calls “<strong>free(ptr)</strong>”, then the address “ptr” must be the start of memory obtained by previous “<strong>malloc()</strong>” call.</p><h4>Next Steps</h4><p>If you’re reading this line, congratulations!!! You made it. You have learnt the basics of user space memory management. Of course there are more complex problems about the memory management like segmantation fault. Hopefully I can discuss some of them in the future.</p><p>Feel free to check other articles about operating system below:</p><p><a href="https://mattchw.medium.com/overview-of-operating-system-cc3f6f6bb062">Overview of Operating System</a></p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f130d242e68" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/operating-system-memory-management-7f130d242e68">Operating System — Memory Management</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operating System — Inter-process Communication (IPC)]]></title>
            <link>https://levelup.gitconnected.com/operating-system-inter-process-communication-ipc-60a288b11d18?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/60a288b11d18</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Mon, 21 Jun 2021 16:13:55 GMT</pubDate>
            <atom:updated>2021-06-23T14:36:24.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>Operating System — Inter-process Communication (IPC)</h3><h4>Understand IPC in just 3 minutes</h4><p><strong>Inter-process communication</strong> (<strong>IPC</strong>) is simply a mechanism for the processes to manage shared data. The most commonly used object to share data between two processes is pipe.</p><h4><strong>What’s a pipe?</strong></h4><p>Pipe is a shared object between two processes which data from one to another. It is unidirectional, which means data can only flow from left to right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFOdnuaQbrVgqJRGNkGkcA.png" /><figcaption>Example of Inter-process Communication</figcaption></figure><p>Deep down in the kernal, the pipe() system call creates a piece of shared FIFO queue in the kernel space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rztxCQJ2d8b5zXlEMILJPw.png" /></figure><p>In this example, the “ls” process is a producer and it writes data into the pipe. The “less” process is a consumer and it reads the data from the pipe.</p><p>However, you may realise that there could be a problem. The buffer’s size is limited. What if “ls” produces too fast while “less” consumes too slow?</p><p>It’s called <strong>producer-consumer problem</strong> and it’s a synchronization problem. Producer-consumer problem is one of the classic IPC problems and I will talk about it later.</p><p>As user space memory is not sharable between processes even they are parent and child, shared objects are therefore provided at the kernel level. There are other IPC problems beyond pipe. You may have to use shared memory and shared files directly. The concurrent access may cause unpredictable outcomes and Kernel won’t help you to take care of it.</p><h4>Race condition</h4><p>When processes share a same memory together, we could not skip talking about race condition. It could become a bug if we don’t take a good care of it.</p><p>A race condition means the outcome of an execution depends on a particular order in which the shared resource is accessed. It may happen when:</p><ol><li>there are shared objects</li><li>there are multiple processes</li><li>the processes are concurrently accessing shared objects</li></ol><p>Race condition is always a nightmare as it’s hard to debug.</p><h4>How to resolve race condition on a shared object?</h4><p><strong>Mutual Exclusion</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*_M0jjP4ZxG39zClYBxMypw.png" /><figcaption>Mutual Exclusion</figcaption></figure><p>When I’m playing with the shared memory, no one could touch it. A set of processes would not have the problem of race condition if <em>mutual exclusion is guaranteed</em>.</p><p>Bear in mind. Shared object is still sharable, but:<br>- the shared object could not be shared <strong>at the same time</strong><br>- it has to be shared one by one</p><p>To Achieve mutual exclusion, the program code could be divided into 3 sections:</p><ol><li><strong>Section Entry</strong>: start of critical section. Telling other process that the shared memory is in used.</li><li><strong>Critical Section</strong>: code segment that is accessing the shared object. It should as tight as possible.</li><li><strong>Section Exit</strong>: end of critical section. Telling other process that the shared memory is now free.</li></ol><p>In short, mutual exclusion is achieved by blocking other processes from entering a critical section if a process is already accessing the critical section.</p><h4><strong>How to achieve mutual exclusion by programming?</strong></h4><p><strong>Spin lock</strong></p><p>It is to loop on another shared object, “<strong>turn”</strong>, to detect the status of other processes.</p><p>For example, Process A:</p><pre>while (TRUE) {<br>  while( turn != <strong>0</strong> ) /* busy waiting */</pre><pre><strong>  ----------------------<br>  critical_section();</strong></pre><pre><strong>  ----------------------  </strong><br>  <br>  <strong>turn = 1;</strong><br>  <br>  remainder_section();<br>}</pre><p>Process B:</p><pre>while (TRUE) {<br>  while( turn != <strong>1</strong>) /* busy waiting */</pre><pre><strong>----------------------<br>  critical_section();</strong></pre><pre><strong>----------------------  </strong><br>  <br>  <strong>turn = 0;</strong><br>  <br>  remainder_section();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*o7TaP5BxfPj5NnLVKcAEkw.png" /><figcaption>Example of spin lock</figcaption></figure><p><strong>Peterson’s solution</strong></p><p><strong>Peterson’s solution </strong>is similar to spin lock. Apart from “<strong>turn</strong>”, one more extra shared object, “<strong>interested”</strong>, is used. If I don’t show interest, I’ll let other processes to use the shared memory. If all processes both show interest, all the processes have to take turns.</p><p>For example, Process A:</p><pre><strong>interested[process] = TRUE</strong>;</pre><pre>while( <strong>turn == process</strong> &amp;&amp; <strong>interested[other process] == TRUE</strong> )</pre><pre>/* busy waiting */</pre><pre><strong>----------------------<br>  critical_section();</strong></pre><pre><strong>----------------------  </strong><br>  <br>  <strong>interested[process] = FALSE</strong>;<br>  <br>  remainder_section();<br>}</pre><p>Process B (same as Process A):</p><pre><strong>interested[process] = TRUE</strong>;</pre><pre>while( <strong>turn == process</strong> &amp;&amp; <strong>interested[other process] == TRUE</strong> )</pre><pre>/* busy waiting */</pre><pre><strong>----------------------<br>  critical_section();</strong></pre><pre><strong>----------------------  </strong><br>  <br>  <strong>interested[process] = FALSE</strong>;<br>  <br>  remainder_section();<br>}</pre><p>However, mutual exclusion has one obvious disadvantage. It hinders the performance of parallel computations.</p><h4>Next Steps</h4><p>If you’re reading this line, congratulations!!! You made it. You have learnt the basics of IPC and how to resolve the race condition of processes. There are some interesting IPC problems like producer-consumer problem and dining philosopher problem which definitely worth a mention. Hopefully I can discuss some of them in the future.</p><p>Feel free to check other articles about operating system below:</p><p><a href="https://mattchw.medium.com/overview-of-operating-system-cc3f6f6bb062">Overview of Operating System</a></p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60a288b11d18" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/operating-system-inter-process-communication-ipc-60a288b11d18">Operating System — Inter-process Communication (IPC)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operating System — Process Management]]></title>
            <link>https://levelup.gitconnected.com/operating-system-process-management-26c73901166?source=rss-804a12ce32ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/26c73901166</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[process-management]]></category>
            <dc:creator><![CDATA[Matthew Wong]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 15:35:37 GMT</pubDate>
            <atom:updated>2020-08-13T02:07:01.063Z</atom:updated>
            <content:encoded><![CDATA[<h3>Operating System — Process Management</h3><h4>The basic, intermediate and advanced knowledge about process</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TC1DmcB4LrYVVG8F" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Process management in operating system is an important concept as we generate hundreds and thousands of processes when we execute different programs in a day. In order to make it easier for you to understand process management, I’m gonna break it down to three levels, from easiest to hardest:</p><ol><li><strong>Basic (Process, PCB, Process Lifecycle)</strong></li><li><strong>Intermediate (Process in user space)</strong></li><li><strong>Advanced (Process in kernel space)</strong></li></ol><h3>Level 1 — Essential Concepts You Must Know</h3><h4>What’s a process?</h4><p>A <strong>process</strong> is a program in execution. It contains every information of that running program:</p><ul><li>Current program counter</li><li>Accumulated running time</li><li>List of files that are currently opened by that program</li><li>Page table</li></ul><h4>What’s Process Control Block(PCB)?</h4><p>Every process is represented by a data structure called <strong>Process Control Block(PCB)</strong>. A PCB keeps all the important information of a process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*2KQbb1VgapNap_YCaY8zUA.png" /><figcaption>Process Control Block</figcaption></figure><ul><li><strong>Pointer</strong>: A pointer to the parent process.</li><li><strong>Process ID</strong>: Unique ID number representing a process.</li><li><strong>Process State</strong>: The state any process currently is in (Ready, Wait, Exit, etc).</li><li><strong>Process Priority</strong>: Numeric value which states how urgent a process is. Process with the highest priority will be allocated to the CPU first.</li><li><strong>Program Counter</strong>: Address of the next instruction in line of the processes.</li><li><strong>Accounting Information</strong>: The amount of CPU used, time limits, job or process numbers, etc.</li><li><strong>CPU Registers</strong>: Accumulators, index registers, general-purpose registers, etc.</li><li><strong>I/O Information</strong>: An array of open files and I/O devices allocated to the process.</li></ul><h4>What’s Process Lifecycle?</h4><p>There is a lifecycle of every process. The states of a process are Start, Ready, Running, Waiting and Terminated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*LNPKoppfT6-1Kx-rbd6B7g.png" /><figcaption>Process Lifecycle</figcaption></figure><p><strong>Start</strong>: The birth of a process.<br>Except the first process “init”, every process is created using<strong> fork()</strong>.</p><p><strong>Ready</strong>: The process is ready.<br>It means it’s ready to run but is not running. A process may become “ready”<br>(runnable) after:</p><ul><li>It is just created by <strong>fork()</strong></li><li>It has been running on the CPU for some time and the OS chooses another process to run (scheduled context switch)</li><li>Returning from blocked states</li></ul><p><strong>Running</strong>: The process is running.<br>The OS chooses this process to be running on the CPU and changes its state to “Running”.</p><p><strong>Waiting/Blocking</strong>: The process is blocked.<br>While the process is running, it may wait for something (e.g. getc(), wait()). There are 2 types of wait, interruptible and un-interruptible.</p><ul><li><strong>Interruptible wait</strong>: Sometimes, a process has to wait for the response from a device and, therefore, it is blocked. This blocking state is interruptible. It means pressing “Ctrl + C” can get the process out of the waiting state.</li><li><strong>Un-Interruptible wait</strong>: Sometimes, a process needs to wait for a resource until it really gets the response. It’s in an Un-interruptible status. It means it won’t be “Ctrl + C” interruptible.</li></ul><p><strong>Terminated: </strong>The process is going to die.<br>The process may choose to terminate itself or force to be terminated.</p><h3>Level 2 — Intermediate Knowledge (User Space)</h3><p>After having the basic concepts, we’re gonna go deeper to know more about the system calls of process but focusing on user space (from programmer view).</p><ol><li>How to identify processes?</li><li>How to create a new process?</li></ol><h4>How can we identify processes from one to another?</h4><p>Each process is given a unique ID number, and is called the process ID(PID). The system call, <strong>getpid()</strong>, prints the PID of the calling process.</p><p>Example of getpid():</p><pre>#include &lt;stdio.h&gt; // printf()<br>#include &lt;unistd.h&gt; // getpid()</pre><pre>int main(void) {</pre><pre>  printf(“My PID is %d\n”, <strong>getpid()</strong> );</pre><pre>  return 0;</pre><pre>}</pre><h4>How can we create a new process?</h4><p>To create a process, we use the system call <strong>fork()</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*nJ8DAPkwzMHBVnZMHDq79A.png" /></figure><p>Example of fork():</p><pre>int main(void) {<br>  printf(“Parent (PID = %d)\n”, getpid());<br>  <strong>fork()</strong>;<br>  printf(“My PID is %d\n”, getpid() );<br>  <strong>return</strong> 0;<br>}</pre><p>Output:</p><pre>Parent (PID = 1234) &lt;- parent process<br>My PID is 1234 &lt;- parent process<br>My PID is 1235 &lt;- child process</pre><p>In the above example, we can observe that:</p><ul><li>Both the parent process and the child process execute the same program</li><li><strong>Child process starts its execution at the location that fork() is returned, not from the beginning of the program</strong></li></ul><p>The system call <strong>fork()</strong> is like “cell division”. It creates the child process by cloning from the parent process, including all user-space data.</p><p>If a process can only duplicate itself and always runs the same program, it’s not quite meaningful. So, here comes another question — how can we execute other programs?</p><p>Let’s meet the <strong>exec*()</strong> system call family!</p><h4><strong>How can we execute a program?</strong></h4><p><strong>exec*()</strong> is a system call family and the family has 6 members (execl, execv, execlp, execvp, execle, execve).</p><p>Let’s take execl() as an example:</p><pre><strong>execl(“/bin/ls”, “/bin/ls”, NULL);</strong></pre><p>We would like to run the command “/bin/ls” in this case.</p><ul><li>1st argument “/bin/ls”: The file that we want to execute</li><li>2nd argument “/bin/ls”: When the process switches to “/bin/ls”,<br>this string is the program argument[0]</li><li>3rd argument “NULL”: This states the end of the program argument list</li></ul><p>Here is another example of execl():</p><pre><strong>execl(&quot;/bin/ls&quot;, &quot;/bin/ls&quot;, &quot;-l&quot;, NULL);</strong></pre><p>In this case, we have 4 arguments:</p><ul><li>1st argument “/bin/ls”: The file that we want to execute</li><li>2nd argument “/bin/ls”: When the process switches to “/bin/ls”,<br>this string is the program argument[0]</li><li>3rd argument “- l”: When the process switches to “/bin/ls”,<br>this string is the program argument[1]</li><li>4th argument “NULL”: This states the end of the program argument list</li></ul><p>So, this is an example of how to use execl() in a C-program:</p><pre>int main(void) {<br>  printf(“before execl\n”);<br>  <strong>execl(“/bin/ls”, “/bin/ls”, NULL);</strong><br>  printf(“after execl\n”);<br>  return 0;<br>}</pre><p>However, “after execl” is not printed if you run this program. It means the lines of code “after execl()” is not reached. The parent process is terminated.</p><p><strong>Bear this in mind</strong>: The exec system call family is not simply a function that calls a command. The “return” or the “exit()” statement in “/bin/ls” will terminate the process. Therefore, it is certain that the process cannot go back to the original program!</p><p><strong>Question: How can we make a meaningful process creation? </strong><br><strong>Answer: fork() + exec*() + wait() = system()</strong><br>Example of creating a meaningful process:</p><pre>int exec(const char *cmd) {<br>  if(cmd == -1)<br>    return -1;</pre><pre>  // if fork() returns 0, this is a child process  <br>  if(<strong>fork()</strong> == 0) { <br>    <strong>execl(&quot;/bin/sh&quot;, &quot;/bin/sh&quot;, &quot;-c&quot;, cmd_str, NULL);</strong></pre><pre>    fprintf(stderr, &quot;%s: command not found\n&quot;, cmd_str);<br>    exit(-1);<br>  }</pre><pre>  <strong>wait(NULL)</strong>;<br>  return 0;<br>}</pre><pre>// main<br>int main(void) {<br>  printf(&quot;before exec\n\n&quot;);<br>  <strong>exec(&quot;/bin/ls&quot;);</strong><br>  printf(&quot;after exec\n&quot;);<br>  return 0;<br>}</pre><p>The key to suspend the execution of the parent process and to wake the parent up after the child is terminated is using <strong>wait()</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*2xH3zug4Dc0vgKSctZhnZA.png" /><figcaption>How wait() can suspend the parent process</figcaption></figure><p><strong>wait()</strong> is used to suspend the calling process to waiting state and return (wakes up) when one of its child processes is terminated or receive a signal.</p><p>Now, you know that:</p><ul><li>A new process is created by system()</li><li>A process is a program being brought by <strong>exec*() </strong>to the memory</li><li>C library call, <strong>system()</strong>, is implemented by <strong>fork()</strong>, <strong>exec*()</strong>, and<br><strong>wait()</strong></li></ul><h3>Level 3 — Advanced Knowledge (Kernel Space)</h3><p>So far, we’ve only covered the process in user space. This is how the full picture looks like before moving on to the kernel space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*39jvK6M51hnb1xOB7hENEA.png" /></figure><h4>What happened when we invoke system calls?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*zi7DhP77-Dpz0awoeyC_OA.png" /></figure><p>As the code is in user-space memory, the program counter is pointing to the user-space memory.</p><p>When the process called the system call(e.g. getpid()), the CPU switches from the user-space to the kernel-space, and reads the PID of the process from the kernel.</p><p>When the CPU has finished executing the system call, it switches back to the user-space memory, and continues running that program code.</p><p>Therefore, a CPU is always switching between user-space and kernel-space. We can check the time spent on user-space and kernel-space when executing a program.</p><ul><li><strong>User time</strong>: CPU time spent on codes in user-space memory</li><li><strong>Sys time</strong>: CPU time spent on codes in kernel-space memory</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*deKFPZJ4QBYQk5Xq6GB0Wg.png" /></figure><p>In Linux, there’s a command called <strong>time</strong> to check the user time and sys time. To know more, check this out:</p><p><a href="https://man7.org/linux/man-pages/man1/time.1.html">time(1) - Linux manual page</a></p><h4>How fork() works?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Pkqc_eSLKSdezNzkPlWocg.png" /></figure><p>When a process calls fork(), there’s a processing time as the kernel needs to do something. Let’s find out what the kernel is doing exactly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*u31tcQQcHoj8lHXVHUkaWQ.png" /></figure><p>Inside kernel space, processes are arranged as a doubly linked list, called the <strong>Task List</strong>.</p><p>This is how <strong>fork()</strong> updates the memory in both user-space and kernel-space:</p><ol><li>Parent process 1234 calls <strong>fork()</strong></li><li>PCB is being copied in the kernel space and code in user-space memory is also being copied</li><li>In kernel space, some details of copied PCB is updated</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*LMGQcwZbNdq9-GV2CY2_rQ.png" /></figure><p>After calling <strong>fork()</strong>, both the parent process and the child process will be returned from fork(). At last, a return value will be added in the PCB. The return value of parent process will be the PID of its child process and the return value of child process will be 0.</p><h4>How exec*() works?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Ja093ol2wAF6ZmdC3xmvLw.png" /></figure><p>When a process calls <strong>exec()</strong>, the memory in user-space will be changed:</p><ul><li><strong>Local variables</strong> &amp; <strong>dynamically allocated memory</strong> are cleared</li><li><strong>Global variables</strong> are reset based on new code</li><li><strong>Code &amp; constants</strong> are changed to the new code</li></ul><p>Of course, the kernel will also reset the register values (e.g., program counter) in PCB.</p><h4>How wait() and exit() work?</h4><h4>exit()</h4><p>I want to talk about <strong>exit()</strong> first as calling exit() without calling wait() will cause a serious problem, <strong>zombie process</strong>. You will understand it very soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*mN3ag3ggTqZw3Y1Qf1mbsQ.png" /></figure><p>This is how <strong>exit()</strong> frees the memory in both user-space and kernel-space:</p><ol><li>Child process 1235 calls <strong>exit()</strong></li><li>All allocated memory in kernel space is freed. The list of opened files are all closed. (so it’s okay to skip fclose() but it’s not recommended)</li><li>All allocated memory in user space is freed. (including program code<br>and allocated memory)</li><li>The kernel notifies the parent of the child process about the termination<br>of its child. The kernel sends a <strong>SIGCHLD</strong> signal to the parent.</li></ol><p>As the parent process 1234 didn’t call wait(), it will ignore the <strong>SIGCHLD</strong> signal. Therefore, process ID 1235 is still in the kernel’s task list. The status of the child process is now called <strong>zombie process</strong>.</p><h4>wait()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*sFhsJYXjUJ4GgyWWliAv0Q.png" /></figure><p>By default, every process does not respond to the <strong>SIGCHLD</strong> signal. The parent ignores his child unless it’s really waiting for the child process.</p><p>If a process has called <strong>wait()</strong>, the kernel will register a signal handling<br>routine for that process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*Tq72zQ9Hg6B_ZjS2lkBTWw.png" /></figure><p>When the kernel sends <strong>SIGCHLD</strong> to the parent process, the corresponding signal handling routine will be invoked.</p><p>This is what the default handler is gonna do:</p><ol><li>Accept and remove the <strong>SIGCHLD</strong> signal;</li><li>Destroy the child process(remove it from process table, task-list, etc.)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*yy0TtUiGTXV8ATO7SaYiag.png" /></figure><p>After removing the child process, the kernel deregisters the signal handling routine for the parent process and returns the PID of the terminated child.</p><p>Therefore, calling <strong>wait()</strong> is very important!!! The main reason is <strong>system resource management</strong>. A zombie process takes up a PID but the total number of PIDs are limited (32,768). So, always remember to invoke <strong>wait()</strong> in the parent process first.</p><p>If you’re reading this line, congratulations!!! You made it. It’s not easy to read from level 1 to level 3. I believe you have a very concrete understanding on process management now.</p><p>To know more about my backend learning path, check out my journey here:</p><p><a href="https://mattchw.medium.com/my-backend-developer-learning-journey-%E6%88%91%E7%9A%84%E5%BE%8C%E7%AB%AF%E5%AD%B8%E7%BF%92%E4%B9%8B%E6%97%85-5315fe2fefc2">My Backend Developer Learning Journey 我的後端學習之旅</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c73901166" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/operating-system-process-management-26c73901166">Operating System — Process Management</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>