Wednesday, March 16, 2016

Showing the intent of your code in Powershell

I hang out on /r/Powershell quite often and I find myself talking about writing code that shows your intent quite often. When I initially started working with Powershell I was kind of put off by the verbosity of it. Over time I came to accept it and things like tab complete make it easy to work with.

I turned that corner a long time ago and really like the verbosity of it now. When you combine that with clean code best practices that create self documenting code, Powershell becomes so easy to read and work with. I like it when my code makes it very easy to see what the intent of it is. I share a lot of code so this is something I find to be important in my work.

My simple example is trying to split a string and skipping the first item in the list. This is the code sample that was getting passed around:

$obj = (Get-ADGroup 'GroupName').DistinguishedName.split(',')
$obj[1..$($obj.count - 1)]


It worked and accomplished the goal. But compare it to this and think about what one shows the intent of the code better.

(Get-ADGroup 'GroupName').DistinguishedName -split ',' |  Select-Object -Skip 1


In my code, I would take it one more step.

$ADGroup = Get-ADGroup 'GroupName'
$ADGroup.DistinguishedName -split ',' |  Select-Object -Skip 1


 All three of them are valid Powershell and this just a style preference, but having a solid and consistent can make your code a lot easier to read. 




No comments: