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.
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.
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)
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.
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
}