One place for hosting & domains

      5 Tips to Write Better Conditionals in JavaScript


      When working with JavaScript, we deal a lot with conditionals, here are the 5 tips for you to write better / cleaner conditionals.

      1. Use Array.includes for Multiple Criteria

      Let’s take a look at the example below:

      // condition
      function test(fruit) {
        if (fruit == 'apple' || fruit == 'strawberry') {
          console.log('red');
        }
      }
      

      At first glance, the above example looks good. However, what if we get more red fruits, say cherry and cranberries? Are we going to extend the statement with more || ?

      We can rewrite the conditional above by using Array.includes (Array.includes)

      function test(fruit) {
        // extract conditions to array
        const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
      
        if (redFruits.includes(fruit)) {
          console.log('red');
        }
      }
      

      We extract the red fruits (conditions) to an array. By doing this, the code looks tidier.

      2. Less Nesting, Return Early

      Let’s expand the previous example to include two more conditions:

      • if no fruit provided, throw error
      • accept and print the fruit quantity if exceed 10.
      function test(fruit, quantity) {
        const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
      
        // condition 1: fruit must has value
        if (fruit) {
          // condition 2: must be red
          if (redFruits.includes(fruit)) {
            console.log('red');
      
            // condition 3: must be big quantity
            if (quantity > 10) {
              console.log('big quantity');
            }
          }
        } else {
          throw new Error('No fruit!');
        }
      }
      
      // test results
      test(null); // error: No fruits
      test('apple'); // print: red
      test('apple', 20); // print: red, big quantity
      

      Look at the code above, we have:

      • 1 if/else statement that filter out invalid condition
      • 3 levels of nested if statement (condition 1, 2 & 3)

      A general rule I personally follow is return early when invalid conditions found.

      /_ return early when invalid conditions found _/
      
      function test(fruit, quantity) {
        const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
      
        // condition 1: throw error early
        if (!fruit) throw new Error('No fruit!');
      
        // condition 2: must be red
        if (redFruits.includes(fruit)) {
          console.log('red');
      
          // condition 3: must be big quantity
          if (quantity > 10) {
            console.log('big quantity');
          }
        }
      }
      

      By doing this, we have one less level of nested statement. This coding style is good especially when you have long if statement (imagine you need to scroll to the very bottom to know there is an else statement, not cool).

      We can further reduce the nesting if, by inverting the conditions & return early. Look at condition 2 below to see how we do it:

      /_ return early when invalid conditions found _/
      
      function test(fruit, quantity) {
        const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
      
        if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early
        if (!redFruits.includes(fruit)) return; // condition 2: stop when fruit is not red
      
        console.log('red');
      
        // condition 3: must be big quantity
        if (quantity > 10) {
          console.log('big quantity');
        }
      }
      

      By inverting the conditions of condition 2, our code is now free of a nested statement. This technique is useful when we have long logic to go and we want to stop further process when a condition is not fulfilled.

      However, that’s no hard rule for doing this. Ask yourself, is this version (without nesting) better / more readable than the previous one (condition 2 with nested)?

      For me, I would just leave it as the previous version (condition 2 with nested). It is because:

      • the code is short and straight forward, it is clearer with nested if
      • inverting condition may incur more thinking process (increase cognitive load)

      Therefore, always aims for Less Nesting and Return Early but don’t overdo it. There is an article & StackOverflow discussion that talks further on this topic if you interested:

      3. Use Default Function Parameters and Destructuring

      I guess the code below might look familiar to you, we always need to check for null / undefined value and assign default value when working with JavaScript:

      function test(fruit, quantity) {
        if (!fruit) return;
        const q = quantity || 1; // if quantity not provided, default to one
      
        console.log(`We have ${q} ${fruit}!`);
      }
      
      //test results
      test('banana'); // We have 1 banana!
      test('apple', 2); // We have 2 apple!
      

      In fact, we can eliminate the variable q by assigning default function parameters.

      function test(fruit, quantity = 1) { // if quantity not provided, default to one
        if (!fruit) return;
        console.log(`We have ${quantity} ${fruit}!`);
      }
      
      //test results
      test('banana'); // We have 1 banana!
      test('apple', 2); // We have 2 apple!
      

      Much easier & intuitive isn’t it? Please note that each parameter can has it own default function parameter. For example, we can assign default value to fruit too: function test(fruit="unknown", quantity = 1).

      What if our fruit is an object? Can we assign default parameter?

      function test(fruit) { 
        // printing fruit name if value provided
        if (fruit && fruit.name)  {
          console.log (fruit.name);
        } else {
          console.log('unknown');
        }
      }
      
      //test results
      test(undefined); // unknown
      test({ }); // unknown
      test({ name: 'apple', color: 'red' }); // apple
      

      Look at the example above, we want to print the fruit name if it’s available or we will print unknown. We can avoid the conditional fruit && fruit.name checking with default function parameter & destructing.

      // destructing - get name property only
      // assign default empty object {}
      function test({name} = {}) {
        console.log (name || 'unknown');
      }
      
      //test results
      test(undefined); // unknown
      test({ }); // unknown
      test({ name: 'apple', color: 'red' }); // apple
      

      Since we only need property name from fruit, we can destructure the parameter using {name}, then we can use name as variable in our code instead of fruit.name.

      We also assign empty object {} as default value. If we do not do so, you will get error when executing the line test(undefined)Cannot destructure property name of 'undefined' or 'null'. because there is no name property in undefined.

      If you don’t mind using 3rd party libraries, there are a few ways to cut down null checking:

      • use Lodash get function
      • use Facebook open source’s idx library (with Babeljs)

      Here is an example of using Lodash:

      // Include lodash library, you will get _
      function test(fruit) {
        console.log(__.get(fruit, 'name', 'unknown'); // get property name, if not available, assign default value 'unknown'
      }
      
      //test results
      test(undefined); // unknown
      test({ }); // unknown
      test({ name: 'apple', color: 'red' }); // apple
      

      You may run the demo code here. Besides, if you are a fan of Functional Programming (FP), you may opt to use Lodash fp, the functional version of Lodash (method changed to get or getOr).

      4. Favor Map / Object Literal than Switch Statement

      Let’s look at the example below, we want to print fruits based on color:

      function test(color) {
        // use switch case to find fruits in color
        switch (color) {
          case 'red':
            return ['apple', 'strawberry'];
          case 'yellow':
            return ['banana', 'pineapple'];
          case 'purple':
            return ['grape', 'plum'];
          default:
            return [];
        }
      }
      
      //test results
      test(null); // []
      test('yellow'); // ['banana', 'pineapple']
      

      The above code seems nothing wrong, but I find it quite verbose. The same result can be achieve with object literal with cleaner syntax:

      // use object literal to find fruits in color
        const fruitColor = {
          red: ['apple', 'strawberry'],
          yellow: ['banana', 'pineapple'],
          purple: ['grape', 'plum']
        };
      
      function test(color) {
        return fruitColor[color] || [];
      }
      

      Alternatively, you may use Map to achieve the same result:

      // use Map to find fruits in color
        const fruitColor = new Map()
          .set('red', ['apple', 'strawberry'])
          .set('yellow', ['banana', 'pineapple'])
          .set('purple', ['grape', 'plum']);
      
      function test(color) {
        return fruitColor.get(color) || [];
      }
      

      Map is the object type available since ES2015, allow you to store key value pair.

      Should we ban the usage of switch statement? Do not limit yourself to that. Personally, I use object literal whenever possible, but I wouldn’t set hard rule to block that, use whichever make sense for your scenario.

      Todd Motto has an article that dig deeper on switch statement vs object literal, you may read here.

      TL;DR; Refactor the syntax

      For the example above, we can actually refactor our code to achieve the same result with Array.filter .

      
       const fruits = [
          { name: 'apple', color: 'red' }, 
          { name: 'strawberry', color: 'red' }, 
          { name: 'banana', color: 'yellow' }, 
          { name: 'pineapple', color: 'yellow' }, 
          { name: 'grape', color: 'purple' }, 
          { name: 'plum', color: 'purple' }
      ];
      
      function test(color) {
        // use Array filter to find fruits in color
      
        return fruits.filter(f => f.color == color);
      }
      

      There’s always more than 1 way to achieve the same result. We have shown 4 with the same example. Coding is fun!

      5. Use Array.every & Array.some for All / Partial Criteria

      This last tip is more about utilizing new (but not so new) Javascript Array function to reduce the lines of code. Look at the code below, we want to check if all fruits are in red color:

      const fruits = [
          { name: 'apple', color: 'red' },
          { name: 'banana', color: 'yellow' },
          { name: 'grape', color: 'purple' }
        ];
      
      function test() {
        let isAllRed = true;
      
        // condition: all fruits must be red
        for (let f of fruits) {
          if (!isAllRed) break;
          isAllRed = (f.color == 'red');
        }
      
        console.log(isAllRed); // false
      }
      

      The code is so long! We can reduce the number of lines with Array.every:

      const fruits = [
          { name: 'apple', color: 'red' },
          { name: 'banana', color: 'yellow' },
          { name: 'grape', color: 'purple' }
        ];
      
      function test() {
        // condition: short way, all fruits must be red
        const isAllRed = fruits.every(f => f.color == 'red');
      
        console.log(isAllRed); // false
      }
      

      Much cleaner now right? In a similar way, if we want to test if any of the fruit is red, we can use Array.some to achieve it in one line.

      const fruits = [
          { name: 'apple', color: 'red' },
          { name: 'banana', color: 'yellow' },
          { name: 'grape', color: 'purple' }
      ];
      
      function test() {
        // condition: if any fruit is red
        const isAnyRed = fruits.some(f => f.color == 'red');
      
        console.log(isAnyRed); // true
      }
      

      Summary

      Let’s produce more readable code together. I hope you learn something new in this article.

      That’s all. Happy coding!



      Source link

      Tips for Contributing to Open Source With GitHub


      How to Join

      This Tech Talk is free and open to everyone. Register below to get a link to join the live event.

      Format Date RSVP
      Presentation and Q&A October 13, 2020, 12:00–1:00 p.m. ET

      If you can’t join us live, the video recording will be published here as soon as it’s available.

      About the Talk

      A rundown of some of GitHub Developer Advocate Brian Douglas’ favorite tips to make your life easier as an open source project maintainer and future contributor. After watching this talk, you’ll be able to automate common tasks so that you can focus on the parts of any project that you want to prioritize.

      What You’ll Learn

      • Best things to look for when contributing to open source projects.
      • Ways to make your project approachable for contributors.
      • How to automate your contributor experience.

      This Talk is Designed For

      • Prospective open source contributors
      • Current open source maintainers

      Prerequisites

      About the Presenter

      Brian Douglas is a Developer Advocate at GitHub where he works on increasing the use of GitHub’s platform-specific features through technical content. (Ask him about GitHub Actions!) Brian has a passion for open source and loves mentoring new contributors.

      To join the live Tech Talk, register here.



      Source link

      6 Tips for Managing Cloud Security in the Modern Threat Landscape


      In a world where advanced cyberattacks are increasing in frequency and causing progressively higher costs for affected organizations, security is of the utmost importance no matter what infrastructure strategy your organization chooses. Despite longstanding myths, cloud environments are not inherently less secure than on-premise. With so many people migrating workloads to the cloud, however, it’s important to be aware of the threat landscape.

      Ten million cybersecurity attacks are reported to the Pentagon every day. In 2018, the number of records stolen or leaked from public cloud storage due to poor configuration totaled 70 million. And it’s estimated that the global cost of cybercrime by the end of 2019 will total $2 trillion.

      In response to the new cybersecurity reality, it is estimated that the annual spending on cloud security tools by 2023 will total $12.6 billion.

      Below, we’ll cover six ways to secure your cloud. This list is by no means exhaustive, but it will give you an idea of the security considerations that should be considered.

      Mitigating Cybersecurity Threats with Cloud Security Systems and Tools

      1. Intrusion Detection and 2. Intrusion Prevention Systems

      Intrusion detection systems (IDS) and intrusion prevention systems (IPS) are other important tools for ensuring your cloud environment is secure. These systems actively monitor the cloud network and systems for malevolent action and rule abuses. The action or rule may be reported directly to your administration team or collected and sent via a secure channel to an information management solution.

      IDSs have a known threat database that monitors all activity by users and the devices in your cloud environment to immediately spot threats such as SQL injection techniques, known malware worms with defined signatures and invalid secure certificates.

      IPS devices work at different layers and are often features of next-generation firewalls. These solutions are known for real-time deep packet inspection that alerts to potential threat behaviors. Sometimes these behaviors may be false alarms but are still important for learning what is and what is not a threat for your cloud environment.

      3. Isolating Your Cloud Environment for Various Users

      As you consider migrating to the cloud, understand how your provider will isolate your environment. In a multi-tenant cloud, with many organizations using the same technology resources (i.e. multi-tenant storage), you have segmented environments using vLAN’s and firewalls configured for least access. Any-any rules are the curse of all networks and are the first thing to look for when investigating the firewall rules. Much like leaving your front door wide-open all day and night, this firewall rule is an open policy of allowing traffic from any source to any destination over any port. A good rule of thumb is to block all ports and networks and then work up from there, testing each application and environment in a thorough manner. This may seem time consuming but going through a checklist of ports and connection scenarios from the setup is more efficient then doing the work of opening ports and allowing networks later.

      It’s also important to remember that while the provider owns the security of the cloud, customers own the security of their environments in the cloud. Assess tools and partners that allow you take better control. For instance, powerful tools such as VMware’s NSX support unified security policies and provide one place to manage firewall rules with its automation capabilities.

      4. User Entity Behavior Analytics

      Modern threat analysis employs User Entity Behavior Analytics (UEBA) and is invaluable to your organization in mitigating compromises of your cloud software. Through a machine learning model, UEBA analyzes data from reports and logs, different types of threat data and more to discern whether certain activities are a cyberattack.

      UEBA detects anomalies in the behavior patterns of your organization’s members, consultants and vendors. For example, the user account for a manager in the finance department would be flagged if it is downloading files from different parts of the world at different times of the day or is editing files from multiple time zones at the same time. In some instances, this might be legitimate behavior for this user, but the IT director should still give due diligence when the UEBA outs out this type of alert.  A quick call to confirm the behavior can prevent data loss or the loss of millions of dollars in revenue if the cloud environment has indeed been compromised.

      5. Role-Based Access Control

      All access should be given with caution and on an as-needed basis. Role-based access control (RBAC) allows employees to access only the information that allows them to do their jobs, restricting network access accordingly. RBAC tools allow you to designate what role the user plays—administrator, specialist, accountant, etc.—and add them to various groups. Permissions will change depending on user role and group membership. This is particularly useful for DevOps organizations where certain developers may need more access than others, as well as to specific cloud environments, but not others.

      When shifting to a RBAC, document the changes and specific user roles so that it can be put into a written policy. As you define the user roles, have conversations with employees to understand what they do. And be sure to communicate why implementing RBAC is good for the company. It not only helps you secure your company’s data and applications by managing employees, but third-party vendors, as well.

       6. Assess Third Party Risks

      As you transition to a cloud environment, vendor access should also be considered. Each vendor should have unique access rights and access control lists (ACL) in place that are native to the environments they connect from. Always remember that third party risk equates to enterprise risk. Infamous data breach incidents (remember Target in late 2013?) resulting from hackers’ infiltration of an enterprise via a third-party vendor should be enough of a warning to call into question how much you know about your vendors and the security controls they have in place. Third party risk management is considered a top priority for cybersecurity programs at a number of enterprises. Customers will not view your vendor as a separate company from your own in the event that something goes sideways and the information goes public. Protect your company’s reputation by protecting it from third party risks.

      Parting Thoughts

      The above tools are just several resources for ensuring your cloud environment is secure in multi-tenant or private cloud situations. As you consider the options for your cloud implementation, working with a trusted partner is a great way to meet your unique needs for your specific cloud environment.

      Explore INAP Managed Security.

      LEARN MORE

      Allan Williamson
      • Technical Account Manager


      READ MORE



      Source link