Using closure to hide private variables and functions away

Our goal is to hide the global constant, sites, and the helper function, index_site!, such that they are not visible in the public API. To achieve that, we can utilize let blocks.

In the body of the module, we can wrap all of the functions inside a let block, as follows:

Now, let's see what has been changed:

  • The sites constant has been replaced by a bound variable at the beginning of the let block. The variables in a let block are bound only in the scope of the block and are not visible to the outside world.
  • The functions that need to be exposed to the API are prefixed with the global keyword. This includes add_site!, crawl_sites!, current_sites, and reset_crawler!. The index_site! function is left as-is so that it is not exposed.

The global keyword allows us to expose the function names to the global scope of the module, which can be exported and made accessible from the public API.

After reloading the module, we can confirm that neither sites nor index_site! are available from the API, as shown in the following output:

As you can see, a let block is an effective way to control access to global variables or functions in a module. We have the ability to encapsulate functions or variables that we want to prevent access from outside of the module.

There may be a performance overhead when wrapping functions within a let block. You may want to run a performance test before using this pattern in any performance-critical section of your code.

As let blocks are quite useful in limiting the scope, we can often use it in longer scripts and functions. Next, we will look at how it is used in practice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.10.137