Combining multiple functions

We already mentioned that modules are packages for your functions. When creating a new module, try to follow the same principles as other module designers. Your module should not be a collection of all of your functions, but should fit a certain topic, such a technology, or maybe your department. Modules can help to structure your code.

When getting started with module development, most people tend to write thousands of lines of code in a single psm1 file. In development, this is what we call an anti-pattern. This particular anti-pattern is called the god class.

Read more on this particularly annoying anti-pattern at https://sourcemaking.com/antipatterns/the-blob. Luckily, it can be remedied through refactoring. Refactoring means extracting code that is used multiple times and combining it into functions, reducing the nesting level (cyclomatic complexity), and more.

Before falling into that trap, the following module structure has proven to be quite versatile:

We structure the code into Public (externally visible functions), Private (internally used functions), and Types, or other additional data structures. This becomes our module scaffolding, which we can take and apply indefinitely. Only the contents of our folders will ever change. In each folder, there should be one script for each function. When we talk about source control, the reason for this will become very apparent.

While this structure might look daunting at the beginning, it is very easy to apply, and, more importantly, easy to understand, even for people unfamiliar with your module. Since each function is in a separate script file, finding functions is very easy. Working with VSCode makes your life even easier, by showing you the references to your functions:

If your functions need to access variables (for example, to keep a dictionary of items in-memory while the module is imported), you can apply the same principles as those for scripting. Variables declared in your module are in the script scope, and are accessible by all of your functions. If you declare variables in the global scope, they will be visible outside of your module, as well.

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

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