Ali The Expert

Logo

Refactoring If...Else Statement In JS

Most of the time the first solution that pops up in our mind is not the best solution. It is only through experience and improving one’s logical thinking and problem-solving skills that one can come up with an optimized approach for a given problem. It is a common observation that most of the code in JS gets nested because of the various conditions one has to handle for the solution.

Hopefully, you get to learn something new today and become a better developer by writing clean, readable, and optimized code.

Refactoring If...Else Statement In JS

Ternary Operator

This is the best and most common way to replace your “if…else” statements. In the field of conversational AI, one will encounter a situation where you have to check the platform from where the bot is triggered and give a response accordingly. This is the best example to use a ternary operator rather than using an if statement to check the condition.

Switch Case

The switch case statement is not the best possible way to replace nested “if-else” statements but these can be used to reduce duplicate code which is another common mistake ignored by developers in the field of conversational AI. Many times we expect the virtual agent to give a static or simple response for different User Intents. When we implement the fulfillment logic for this we tend to unknowingly produce duplicate code. These situations can be eliminated by using switch case statements as a common logic can be executed for multiple cases and other simple responses can be covered under separate cases.

Short-Circuiting

In this approach, we will use logical operators like “ && ” (AND) and “||” (OR). The Working of these operators is complementary to each other.
For example, The right side of the “ AND ” operator is executed only if the left side is true while the right side of the “ OR ” operator is executed only if the left side is false. We can use this logic to easily remove the nesting in our code.
This can be useful for setting a custom exit message at the end of a conversation.
Also, remember that there are few expressions that are always falsy(converted to false)
eg: null, undefined, NaN, an empty string(“”)Many times we expect the virtual agent to give a static or simple response for different User Intents. When we implement the fulfillment logic for this we tend to unknowingly produce duplicate code.
These situations can be eliminated by using switch case statements as a common logic can be executed for multiple cases and other simple responses can be covered under separate cases.

Short-Circuiting

These are used as an early exit strategy. We define our conditions in such a way that the loop is exited for every check. This strategy makes the code more readable and optimized.
This can be used in situations where we check if the user is authenticated and perform some actions accordingly(eg: Triggering an event for user intent)

5. Function Delegation

You can clearly see the concept of closures implemented as the parameters of the outer function are accessible to the inner functions Hope this was helpful for everyone and especially to the folks from the conversational AI domain. For folks not from conversational AI backgrounds, I would recommend you to go through the hyperlinked texts for each of the approaches above as they will help you understand the concepts better.

You can clearly see the concept of closures implemented as the parameters of the outer function are accessible to the inner functions

Hope this was helpful for everyone and especially to the folks from the conversational AI domain.

For folks not from conversational AI backgrounds, I would recommend you to go through the hyperlinked texts for each of the approaches above as they will help you understand the concepts better.

 
Refactoring If...Else Statement In JS

Mocking multiple HTTP requests in a function (Go)

Mocking HTTP requests for unit tests is common practice, but recently I found myself faced with a mocking problem I hadn’t seen before: mocking multiple different requests within a single function. Based on the functionality required, it wouldn’t make sense to split the function up further, and each of the requests were performed synchronously, with further requests dependent on the current response. Since I couldn’t find anything directly applicable in my googling, I wanted to share how I approached this unit test. First of all, I always find myself reviewing this article about mocking an http client, and the overall structure I use is very similar. The second post I found that helped me fill in the blanks was this StackOverflow post. Let’s start with the client interface, below. The httpRequest function isn’t necessary, but since the Client interface requires aDo function, it keeps a lot of the error checking in this function.

package model

import (
                          “io”
                          “net/HTTP”
)

// HTTPClient is an interface that allows mocking client for testing
type HTTPClient interface {
                  Do(req *http.Request) (*http.Response, error)

}

 

var Client HTTPClient

 // httpRequest creates a new request and calls Client.Do
func httpRequest(method string, url string, body io.Reader) (*http.Response, error) {
                 request, err := http.NewRequest(method, url, body)
                 if err != nil {
                                return nil, err
}

resp, err := Client.Do(request)
if err != nil {
return nil, err
}

                                     return resp, nil
}

Now let’s look at the test function. Nothing particularly pretty or interesting, but you can see that a slice of URL strings are passed through, and until 200 returns the function will loop through and create and send new HTTP requests.

What we want to do in the unit test is provide a custom response for each URL instead of having a singular response that the client always returns.