Skip to content

Properties with accessor and mutator methods #2219

Closed

Description

@vors

Copied from TFS 3231229

We should be able to do something along these lines

class foo
{
  [string]$bar {
    get { 
      #getter code
    }
    set {
      # setter code
    }  
  }
}

Activity

  1. added
    Issue-Enhancement
    WG-Language
    on Sep 9, 2016
  2. added
    Up-for-Grabs
    on Nov 2, 2016
  3. iSazonov commented on Nov 21, 2016

    @iSazonov
    Collaborator

    sergei (@vors) This is interesting. Could you clarify: this requires not only changes in the parser?

  4. vors commented on Nov 21, 2016

    @vors
    CollaboratorAuthor

    It will be at least these places:

    • Parser
    • ASTs
    • PSType.cs
  5. iSazonov commented on Nov 21, 2016

    @iSazonov
    Collaborator

    sergei (@vors) Thanks! I went thinking :-)

  6. iSazonov commented on Nov 23, 2016

    @iSazonov
    Collaborator

    PowerShellTeam Please assign me.

  7. powercode commented on Nov 25, 2016

    @powercode
    Collaborator

    Are we sure this is the syntax we want?
    How does it interact with existing syntax?
    What about the following:

    # readonly property
    class A {
       [int]$i {get;} # ??? explicit backing property
       A($i){
          $this.i = $i
       }
    }
    # getter setter: do we have a private backing field?
    class A {
       [int]$i {
            get {
               # what here?
            } 
            set {
                if ($value -lt 0) {throw 'x'}
                $i_ = $value #field derived from propname ?  or 'private [int] $i_'?
             }
       } = 4 # default value 
    }
    

    There's been a lot of work done i C# to handle a lot of these cases, and I think it is worth to take some time to think through what we want to achieve here. And I think there is a lot to learn from other languages here.

    Let us list and discuss the scenarios before jumping to implementation.

  8. iSazonov commented on Nov 26, 2016

    @iSazonov
    Collaborator

    Staffan Gustafsson (@powercode) I am full agree.
    Now I am preparing the base for these enhancements. I am on parser step and completed a parser for get/set {...} (Parser error recovery takes a long time).
    I can inform you that the original code already does implicit get/set and backing field, and attribute processing.
    Now I plan to do as soon as possible a PR with the parser and get feedback. Then do next step and make AST and compile for get/set {...}. If this discussion will adopt new features, then I can always add them immediately or in subsequent PRs because the base will be ready.

  9. iSazonov commented on Jan 11, 2017

    @iSazonov
    Collaborator

    It seems the code is ready for testing.
    I remember that Jason Shirk (@lzybkr) spoke about the specifics of these tests.
    Where will we locate these tests? In Scripting.Classes.BasicParsing.Tests.ps1?
    Any advise before I begin?
    Do it makes sense to make PR now and add tests later?

  10. lzybkr commented on Jan 20, 2017

    @lzybkr
    Contributor

    Sorry, I missed commenting on this. I don't have a strong preference on tests. BasicParsing.Tests.ps1 is probably not the place for anything that tests semantics.

    You can submit a PR whenever you like - but if there aren't any tests, of course you'll be asked to add them.

  11. SeeminglyScience commented on May 15, 2019

    @SeeminglyScience
    Contributor

    I have this mostly done. Implementation needs some cleaning up, may need some design changes, and still needs tests and semantic checks, but it all works. Aiming to get a PR up this weekend or next.

    Progress in this branch.

  12. iSazonov commented on May 16, 2019

    @iSazonov
    Collaborator

    Patrick Meinecke (@SeeminglyScience) I have very old (2 year) implementation (90%) in the branch https://github.com/iSazonov/PowerShell/tree/classgetset-4
    You can (must 😄) grab tests from the branch.
    Also I quickly look your implementation and think you could find useful ideas in my branch too.

  13. SeeminglyScience commented on May 17, 2019

    @SeeminglyScience
    Contributor

    Ilya (@iSazonov) Hmm looking at your branch now, I don't think these tests have a ton of overlap. Your design is very clever, though I was looking for a more traditional implementation.

  14. 4 remaining items

  15. iSazonov commented on May 17, 2019

    @iSazonov
    Collaborator

    Thanks for clarify. I see you point. Your option is easier to implement. I tried it and refused for the same reasons (harder to understand :-) ). In my opinion, this requires more user training and makes more mistakes. Also your option gives users too much freedom and provokes side effects.
    In general, I believe that this backfield should appear in an explicit form only when it is really impossible to do without it - but we can.

    Patrick Meinecke (@SeeminglyScience) Have you other thoughts to share? I think we need to get a community feedback.

    /cc sergei (@vors) Jason Shirk (@lzybkr) Michael Klement (@mklement0) Rob Holt (@rjmholt) Dongbo Wang (@daxian-dbw) Steve Lee (@SteveL-MSFT)

  16. SeeminglyScience commented on May 17, 2019

    @SeeminglyScience
    Contributor

    Seeing a setter that returns feels off. It took me a little bit to get what was happening, and I imagine it would be harder for other folks who aren't as familiar with the behind the scenes. Speculation of course, could just be me.

    Also your option gives users too much freedom and provokes side effects.

    I think that type of freedom fits well in PowerShell. Even so, I don't think we need to be more strict than C#.

    In general, I believe that this backfield should appear in an explicit form only when it is really impossible to do without it - but we can.

    I can't think of many instances where I would implement an accessor that fits neatly into that mold. If it's not generated per call (where I wouldn't need backing field) or lazy init then I'm not likely to need accessors. I think your design is a really cool idea, and would be nice to have as an option, though it wouldn't be what I'd default to.

  17. rjmholt commented on May 17, 2019

    @rjmholt
    Collaborator

    Wow! Really amazing you guys have tackled this. Feel like I'm quite late to this discussion.

    I personally found the usage of $PSItem took me a while to understand in the setter example above. The get/set syntax being basically C# I think creates the expectation of C#-like semantics where you have to explicitly create your own backing property if you want something more than just assignment and dereference of a backing field.

    The thing is that PowerShell classes don't really have fields — PS class properties with no get or set are equivalent to C# class properties with { get; set; } — so explicit get and set in PowerShell classes only really make sense with non-trivial bodies. But not all getters and setters need backing fields (they might be what EF calls a "computed property"), so $PSItem doesn't apply in all cases (not really a big problem -- this is true in other usages of $PSItem in PowerShell).

    I think part of the issue is that having syntax so close to C#'s creates an expectation of everything being like C#, but because .NET has getters and setters baked into it I think the syntax proposed is the most sensible (get { ... } is not unlike begin { ... }). Which basically means I think we should go with Patrick Meinecke (@SeeminglyScience)'s version where $PSItem only applies as the value in a setter.

  18. ThomasNieto commented on Jan 12, 2020

    @ThomasNieto
    Contributor

    Patrick Meinecke (@SeeminglyScience) / Ilya (@iSazonov) good work on this. I've been wanting this feature for a while. Do either of you have any updates on the progress of this feature?

  19. iSazonov commented on Jan 12, 2020

    @iSazonov
    Collaborator

    I feel we don't get a progress until we design in-depth. Minor enhancements do not look so useful.

  20. SeeminglyScience commented on Jan 12, 2020

    @SeeminglyScience
    Contributor

    Thomas Nieto (@ThomasNieto) I stopped working on this awhile ago. The actual code is mostly done if anyone else wants to build off of it. I'm not going to have the spare time for the design debates/probably RFC, so anyone else who wants to take this on is welcome to.

  21. JohnFAsh commented on Sep 13, 2021

    @JohnFAsh

    Forgive my ignorance of Powershell internals, but on the face of it could we not make use of the facts that (a) (hidden) get_ and set_ methods are automatically created for each property; (b) it is syntactically allowed to user-define the same methods, but (c) this seems to have no effect - the user definition does not override the system-generated one. If it did, that would allow as much flexibility as we could want; but I don't know what other consequences might flow from this.

  22. SeeminglyScience commented on Sep 14, 2021

    @SeeminglyScience
    Contributor

    but I don't know what other consequences might flow from this.

    Some change would still need to be made to enable that. The biggest consequence is just having to support that forever. Plus you would need some way to annotate that it's for a property, otherwise it would be a breaking change (imagine someone using a snake_case naming convention, while not particularly popular in pwsh it's not unheard of). At that point you might as well add proper language support.

  23. JohnFAsh commented on Sep 14, 2021

    @JohnFAsh

    @ SeeminglyScience Thanks for the feedback.
    "... otherwise it would be a breaking change...": I agree it's theoretically a breaking change, but in order for it to have any actual impact, someone would need to have written a get_/set_ method and left it there even though it hasn't ever worked (it's been masked by the system version) - not a likely occurrence, I would suggest.
    "...having to support that forever...": surely there are lots of instances where a system default can be over-ridden by writing something with the same name; in fact that's more common than the reverse situation. What is different here?
    Thanks for your patience.

  24. SeeminglyScience commented on Sep 15, 2021

    @SeeminglyScience
    Contributor

    @ SeeminglyScience Thanks for the feedback.
    "... otherwise it would be a breaking change...": I agree it's theoretically a breaking change, but in order for it to have any actual impact, someone would need to have written a get_/set_ method and left it there even though it hasn't ever worked (it's been masked by the system version) - not a likely occurrence, I would suggest.

    I'm thinking it's not too unlikely that some folks happened to name a method get_something in the same way one might name a method invoke_the_thing.

    "...having to support that forever...": surely there are lots of instances where a system default can be over-ridden by writing something with the same name; in fact that's more common than the reverse situation. What is different here?

    So ideally it would be implemented inline, so you don't have to define a property and then separately define it's getters and setters as individual methods. If the proposed workaround were implemented then it would need to continue to be supported even after the ideal solution is also implemented.

  25. JohnFAsh commented on Sep 15, 2021

    @JohnFAsh

    Patrick Meinecke (@SeeminglyScience) Thanks again.

    ...not too unlikely that some folks happened to name a method get_something...

    So you're suggesting (are you?) that this might happen when there isn't a property called 'something'; and later the 'something' property gets added, and attempting to access it behaves oddly. That might be puzzling, but it doesn't actually break anything that worked before. Incidentally, I suppose I'm assuming that accessing a property via dot notation gets translated to a get_/set_ method call (because that's probably how I would do it, and the two behave the same at the moment); but I don't know whether that is true.

    ...ideally it would be implemented inline...

    Agreed; and I take the point that there might be strange consequences if a user used both techniques on the same property. If necessary this could either be prevented as invalid syntax, dealt with on a 'defined priority' basis (like function definitions in different scopes), or just treated like other duplicate function definitions, i.e. "last one wins".
    Incidentally, I made the suggestion simply because the good work you did seems to be in limbo for want of someone to take it forward, and I thought this might be related to the perceived complexity of your solution; so it seemed sensible to ask "what is the simplest thing that might work?" - and that is what came to mind.

  26. added
    Resolution-No Activity
    on Nov 16, 2023
  27. RalfReddings commented on Dec 19, 2023

    @RalfReddings

    what became of the plan to implement this feature for classes? I have been asking how to do this in PowerShell on Reddit and StackOverflow and I was reccomended to do it in C#, as PowerShell does not support.

    Please consider adding this to PowerShell 7. I dont know any C# and I want to take advantage of this feature in Powershell.

  28. iRon7 commented on Jan 16, 2024

    @iRon7

    Despite the arguments from Patrick Meinecke (@SeeminglyScience) on the get_/set_ syntax suggestion from JohnFAsh, I (a PowerShell scripter who is not hindered by any C# knowledge 😊) would prefer his syntax suggestion as it has the benefit that it is downwards compatible from Windows PowerShell 5.1 (since PowerShell supports classes) where a C# like mutator will throw an error:

    class foo
    {
        hidden [string] $_bar
    
        [string] $bar {
            get { return '+++' + $this._bar + '+++' }
            set { $this._bar = "---$PSItem---" }
        }
    }

    Currently throws:

    ParserError:
    Line |
       5 |      [string] $bar {
         |                   ~
         | Missing ';' or end-of-line in property definition.
    

    This probably means that whenever you try to load a future class that contains accessors-as-proposed in e.g. Windows PowerShell, it will cause an error even it could still be a useful class by means of its (hidden) getter/setter methods or even by creating a "Use-ClassAccessors" cmdlet patch that implements the Script Properties in the concerned class, see StackOverflow: Is it possible to override the Getter/Setter functions in a powershell 5 class?

    I'm thinking it's not too unlikely that some folks happened to name a method get_something in the same way one might name a method invoke_the_thing.

    I don't think that it is very likely that this will happen (also knowing that you might further narrow the selected method with constrains as parameterless). and even than; so what?: you might get an unexpected something property...
    Also; from what I understand other programming languages (JavaScript?, Python?) have a similar implementation.
    (It appears to me that PowerShell is already pretty good in avoiding conflicts: it will simply use multiple underscores if the member already exist, e.g.: get__something)

    Anyways, I have opened a new issue (#21079) for this as the Enhancement request is still valid and was actually already in a Up-for-Graps state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Issue-EnhancementResolution-No ActivityUp-for-GrabsWG-Language

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions