Classes in [removed] Why do these two examples do

2019-03-16 21:29发布

问题:

I found this piece of code on this StackOverFlow question, Dictionary of Objects/Classes in VBScript.

My question is why does this "short" class do the same thing as this "long" class? Why even bother coding the long class? Could the short class version be used with additional methods within the same class? Thanks!

Short class

Class employeeclass
    Public first, last, salary
End Class

Long Class

Class employeeclass
    Private m_first
    Private m_last
    Private m_salary

    Public Property Get first
        first = m_first
    End Property
    Public Property Let first(value)
        m_first = value
    End Property

    Public Property Get last
        last = m_last
    End Property
    Public Property Let last(value)
        m_last = value
    End Property

    Public Property Get salary
        salary = m_salary
    End Property
    Public Property Let salary(value)
        m_salary = value
    End Property
End Class

Full script with the short class however, just replace the short class with the long class an get the same result.

Class employeeclass
    Public first, last, salary
End Class

Dim employeedict: Set employeedict = CreateObject("Scripting.Dictionary")

Dim employee: Set employee = new employeeclass
With employee
    .first = "John"
    .last = "Doe"
    .salary = 50000
End With
employeedict.Add "1", employee

Set employee = new employeeclass
With employee
    .first = "Mary"
    .last = "Jane"
    .salary = 50000
End With
employeedict.Add "3", employee

Dim employeedetails: Set employeedetails = employeedict.Item("1")
WScript.Echo "Name: " & employeedetails.first & " " & employeedetails.last & " $" & employeedetails.salary 
WScript.Echo employeedict.Item("3").first & " " & employeedict.Item("3").last & " makes $" & employeedict.Item("3").salary

回答1:

All programming paradigms (different ways of developing software) strive to build better programs with less effort. The concepts "better" and "effort", however, are less strictly defined as mathematical terms and their core meanings change over time.

The basic idea of OOP is to bundle complex data (like the info needed to deal with employees) with complex functionality (like the actions needed to manipulate such info). Before OOP you could have employee structs/records/types and nifty functions/subs/procedures to raise an employee's salary, but the programmer was responsible for applying the correct function to the correct data in the correct way.

Building on this base, OOP can provide further benefits that increase software quality and reduce efforts and risk of errors especially in the context of big teams creating and re-using large systems of software components:

  1. memory management by calling destructors automatically (e.g. C++; other languages - VBScript included - use garbage collection instead)
  2. code re-use by inheritance (e.g. Java; VBScript objects can't inherit, you'll have to embed objects into objects to get a similar effect)
  3. information hiding/controlling access to reduce risk of errors and make improvements of implementations possible

Your first (short) class has data, but no methods. Let's add an init function:

Public Function init(p_first, p_last, p_salary)
  Set init = Me
  first = p_first : last = p_last : salary = p_salary
End Function

So to get 10 employees you can write 10 times

Set employeedict(nId) = new employeeclass.init("John", "Doe", 12345.67)

instead of 10 times

Dim employee: Set employee = new employeeclass
With employee
    .first = "John"
    .last = "Doe"
    .salary = 50000
End With
employeedict.Add "1", employee

Now let's imagine a raiseSalary method that does some computations (based on cents not dollars for the sake of a later argument)

Sub raiseSalary()
  (m_)salary = x * (m_)salary / y ...
End Sub

Calling this method - and changing the formular once when some law changes - certainly beats having 40 lines like

employeeX.salary = x * (m_)salary / y ...

scattered all over your script. (This is just functional abstraction, not OOP; in C++ or Java it would be easy/automagically to have the boss' salary calculated by a different formula (polymorphic function) when you process a long list of employees - in VBScript you'll have to resort to dirty/risky tricks involving duck typing.)

Your second (long) class has - boiler plate - methods (properties) for controlling data access, but no payload functionality (like raiseSalary). As long as you don't add interesting things to the setters (input validation, conversions (e.g. dollars to cents) and real world usable methods, the long class is just a waste of coding time. (Of course, if you are payed by code line/hour and your manager does not realize the class as it is does not guard against incomplete or wrong initializations, it's easy if ill gotten money.)

But if your init function garanties complete initialization of member data and validates input (e.g. double number in plausible range) and your raise-the-salary formula is centralized in one method, you could change the computation to use long numbers for better accuracy and convert dollars to cents once in the init method - with no change in the code that uses the class.

Whether you should guard against users setting the salary directly to stupid values by the book (private members and accessors) or by book (documented admonishments) depends on your audience.

To sum up:

  1. Classes should have payload methods
  2. Getters/Setters without at least some additional features above just storing parameters/returning member data are useless
  3. Even in a VBScript scripting context (one programmer, many ad hoc scripts for specific tasks, few re-usable components/modules, incomplete support of OOP features) organizing your code in 'better' classes (with init functions, input validation, centralized implementation of core functionality) is a good thing.


回答2:

The difference between "short" and "long" class is, as @Garath already mentioned, that the former exposes the member variables that store the actual value, whereas the latter encapsulates those variables in properties.

Properties in VBScript have basically 2 advantages, despite the fact that they require more code:

  • You can make a property read-only (or write-only), which is not possible with member variables.
  • You can validate a value before storing it in the respective member variable. For instance if you have a property ip_addr that takes an IP address in quad-dot notation, you can check if it consists of 4 numbers separated by dots, with each number between 0 and 255, and raise an error if the check fails.


回答3:

They look and do almost same. But frist one use field, second use properties. Look here for good explanation http://blogs.msdn.com/b/vbteam/archive/2009/09/04/properties-vs-fields-why-does-it-matter-jonathan-aneja.aspx