Last active
May 3, 2019 14:54
-
-
Save vexx32/6b3e7350f24106c7c1599cca857bb2e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Simple approach - let PS's type conversion logic handle it. | |
# Pitfall: someone can just supply arbitrary text to the function, which is a bit unfortunate. | |
function Get-Factorial { | |
param($Number) | |
if ($Number -eq 0) { | |
1 | |
} | |
else { | |
$Number * (Get-Factorial -Number ($Number - 1)) | |
} | |
} | |
# More robust approach: type cast the parameter itself | |
# Pitfall: No handling of negative numbers, will cause infinite loops | |
function Get-Factorial { | |
param( | |
[int] | |
$Number | |
) | |
if ($Number -eq 0) { | |
1 | |
} | |
else { | |
$Number * (Get-Factorial -Number ($Number - 1)) | |
} | |
} | |
# Strict approach: prevent negatives with parameter attributes, | |
# and prevent extra values being passed in arbitrarily with [CmdletBinding()] | |
function Get-Factorial { | |
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory, Position = 0)] | |
[ValidateRange(0, [int]::MaxValue)] | |
[int] | |
$Number | |
) | |
if ($Number -eq 0) { | |
1 | |
} | |
else { | |
$Number * (Get-Factorial -Number ($Number - 1)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment