How workaround function() lack of return value specification?

This topic contains 6 replies, has 3 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 7 months ago.

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #35649
    Profile photo of GS
    GS
    Participant

    Hello,

    Trying to find out what is the best way to design script with reusable functions without running into possibility accidentally writing into output by forgetting | Out-Null statements etc?

    #35650
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Pretty much, "don't do that." The language doesn't offer any inbuilt protections, except in v5 classes.

    #35651
    Profile photo of GS
    GS
    Participant

    "Dont' do that"? What do you mean? Don't use functions? How do you reuse code properly? Global variables instead? Or what is a guidance?

    #35652
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Sorry – just "don't" accidentally output stuff you don't want output. "Don't" forget to use Out-Null. That's the guidance. There is no way, aside from v5 classes, to design [a] script with reusable functions without running into the possibility [of] accidentally writing into output. PowerShell just doesn't offer any physical means of doing so. It's irritating sometimes, and it's something that v5 classes, with their stricter "return" keyword, address, but in terms of functions or the rest of the language, there's nothing you can do to address the situation. I'm not actually trying to be snarky – it's just that there's nothing to do, apart from "be really, really careful when you code."

    #35655
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    I suppose if you really wanted to, you could write a function like this:

    
    function Do-Something
    {
        $return = $null
        
        $null = & {
            # stuff
            $return = 'Value to return'
            # more stuff
        }
    
        return $return
    }
    

    It's funny looking, but that would guarantee that anything you didn't explicitly assign to the $return variable wouldn't go down the pipeline.

    #35656
    Profile photo of GS
    GS
    Participant

    I'm wondering why this feature was omitted from original Powershell specification. Even novice programmers would expect to be available to return specific type from Function()

    #35657
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Mostly because it's trying to be both a shell and a scripting language. Some of the shell semantics are really awkward for people who are thinking like a developer (and that's why classes, more of a developer thing anyway, behave differently.)

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.