VBA: Why Use Properties Instead of Subroutines or Functions?

前端 未结 4 536
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-19 11:04

Why do we need to use property Let, Get and Set in a VBA class when we can simply pass and return our arguments using subroutines or f

4条回答
  •  我在风中等你
    2021-01-19 11:28

    I think that the short answer is that properties are characteristics of the class while methods (subroutines) are actions.

    My interpretation of this is that properties are the "adjectives" and methods are the "verbs". We could make an analogy to help illustrate this: We have two NHL goalies (let's create them as members of clsGoalie), Carey Price and Dustin Tokarski. Each has a property specific to their unique "goalie" object which we call save percentage (pSavePercentage). Both goalies require the exact same method for stopping a shot on net (Let's say Private Sub BlockShot) but their unique properties will influence the performance of that action.

    The answer to why we would define the characteristics of a class with properties instead of return values is that properties extend the object, or in essence, define the object. Return values can not be used to reference back to the object they originated from. Back to our goalie analogy... Let's suppose we defined the save percentage of each of our goalies with a subroutine. We could make it work but it would require more code in our main method. First we would have to 'Dim SavePercentage As Double' (already you can see that we've stepped outside of our object). Next, 'SavePercentage = Price.calcSavePercentage'. Finally, we would have to write a whole new method (in our Main or some other module) that we would then pass our new variable of type double to... A this point we don't even know who's in net. Did Price save that shot or was it Tokarski? Confusing. In this instance, had we made save percentage a property of the class "clsGoalie" we would better leverage the power of OOP: clean code and encapsulation.

    Hope this helps a bit.

提交回复
热议问题