PowerShell-Specific Code Smells

A code smell is something you find in source code that may indicate that there’s something wrong with the code. For instance, seeing a function that is over a thousand lines gives you a clue that something is probably wrong even without looking at the specific code in question. You could think of code smells as anti-“Best Practices”. I’ve been thinking about these frequently as I’ve been looking through some old PowerShell code.

I’m going to be writing posts about each of these, explaining why they probably happen and how the code can be rewritten to avoid these “smells”.

A few code smells that are specific to PowerShell that I’ve thought of so far are:

  1. Missing Param() statements
  2. Artificial “Common” Parameters
  3. Unapproved Verbs
  4. Building output using +=
  5. Lots of assignment statements
  6. Using [object] parameters to allow different types

Let me know if you think of others. I’ll probably expand the list as time goes on.

-Mike

2 Comments

  1. Not a strong disagreement with #4, but I’d like to see more explanation/ evidence of why this should be in the code smell list. Might be helpful if you were to expand on _why_ you included these, and how the conclusion was reached.

    • Thanks for commenting. The quick answer is that if possible you should be writing your output to the pipeline immediately rather than aggregating it in a collection. This is something that is very PowerShell specific and I’ve had to break myself of the += habit. I’ll try to cover #4 in my next post.

Comments are closed.