In a recent message I referenced some changes I made to this function and included a copy of it. I mentioned that I wanted to refactor it after getting the behavior I wanted because it’s rather unreadable. So let’s see how I would refactor this:
So the first thing I don’t like is that I threw 3 constants in at the beginning to make it easier to create a Powershell command later. So I’m going to move those constants to a new function along with the code and simply refer to the function when I need it. I started by simply creating the function I’m going to use, but it’s not doing anything yet:
Now I’ll copy and paste the constants in, and then copy and paste the code using the constants in:
Ok, now I have some undefined variables in there. sPSCmd can be changed to retVal. And then I need the sPathsPart and sHashAlgorithm variables to be added as parameters to the function.
Perfect, now I can do a Debug->Compile. This reveals that I am using the constants in other places in the function as well. One way to resolve this would be to simply move the constants to a global scope so that both functions will be able to use them. The only bad thing about that in my case would be that it moves the constants far away from the code using them as my functions are in a larger library. However, in this case, I’ll just move them. The other options would be to define the constants multiple times (NO!!! That’s not good people), create a class which would contain the constants privately with the public methods needed that will do the things I need to do. Ok, I’ve talked myself into it. Here’s the new class file using Insert->Class Module and I’m saving it as PS_FileHashesCommand:
And now I will copy and paste the other line that uses the constants into the new Public Function I’ve created:
Ok, now I can update the original function to use the new object and new functions and it will look like so:
This is slightly improved, but there’s a long way to go to make it readable. I’ll continue tomorrow.