Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are validation parameters really useful?

Tags:

powershell

I'm studying powershell functions and its validate parameters. However I can't understand if they are really useful.

I make a simple example.

function get-choice(
[parameter(Mandatory=$true)][String][ValidateSet('Y','N')]$choice
)
{return $choice}

get-choice k

This function returns me this error:

get-choice : Impossibile convalidare l'argomento sul parametro 'choice'. L'argomento "k" non appartiene al set "Y,N" specificato dall'attributo ValidateSet. Fornire un argomento inclu
so nel set ed eseguire di nuovo il comando.
In riga:6 car:11
+ get-choice <<<<  k
    + CategoryInfo          : InvalidData: (:) [get-choice], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,get-choice

If I don't specify a valid set of values I can check them within my code:

function get-choice2(
[parameter(Mandatory=$true)][String]$choice
) {
    if($choice -ne 'y' -and $choice -ne 'n') {
        write-host "you must choose between yes and no"
        return
    }
return $choice
}

get-choice2 k

and I get a more friendly message:

you must choose between yes and no

First of all I'd like to know if it's possible to customize error message using validateset. Then I hope that someone could explain why I'd have to prefer first approach. Thanks in advance.

like image 363
Nicola Cossu Avatar asked Mar 28 '11 20:03

Nicola Cossu


2 Answers

Some reasons why to use standard validation:

  • declarative code; much easier to read then the if statement
  • much shorter (4 lines of code compared to 1 line with only return statement)
  • the custom code can have some bugs
  • later in Vx of PowerShell there could be some custom validation messages (?) (just dreaming)
  • ...

Check Better error messages for PowerShell ValidatePattern - post by @jaykul. You will see how you could customize the error message. It's a little bit developer oriented, but worth reading it.

like image 83
stej Avatar answered Oct 20 '22 14:10

stej


The advantage to using parameter validation is that you don't have to do it yourself. That's a lot of boring, boilerplate code that no longer needs to be written and tested. A big win in my book, even though it results in less-friendly error messages.

You can write some help documentation for your function, so that user's can type help get-choice2, and see an explanation for what that parameter means:

function get-choice(
[parameter(Mandatory=$true)][String][ValidateSet('Y','N')]$choice
)
{
    <#
    .SYNOPSIS
    Gets the user's choice.

    .PARAMETER choice
    The choice.  Must be Y or N.
    #>

    return $choice
}

Run help about_comment_based_help for more details, or see the MSDN documentation.

like image 30
Aaron Jensen Avatar answered Oct 20 '22 14:10

Aaron Jensen