PropertyとSetter/Getter

PropertyとSetter/Getter

「Propertyプロシージャって、よく考えたら何なんやろ???」と思った。

現に、JavaなんかにはPropertyという仕組みはない。

比較

次のように、ParentHogeクラス、ChildHogeというクラスを作った。

ParentHogeクラスには、ChildHogeオブジェクトを返すChildプロパティがあり、ChildHogeクラスにはNameプロパティがある、という設計。

クラスモジュール ParentHoge
Option Explicit

Private child_ As ChildHoge

'Properties'
Public Property Set Child(ByVal argObj As ChildHoge)
  Set child_ = argObj
End Property
Public Property Get Child() As ChildHoge
  Set Child = child_
End Property

'Setter/Getter'
Public Sub setChild(ByVal argObj As ChildHoge)
  Set child_ = argObj
End Sub
Public Function getChild() As ChildHoge
  Set getChild = child_
End Function

見ての通り、ChildプロパティのProperty SetProperty Getを持たせる一方、同じ機能を提供するSetter/Getterメソッドも実装している。

クラスモジュール ChildHoge
Option Explicit

Private name_ As String

'Properties'
Public Property Let Name(ByVal argValue As String)
  name_ = argValue
End Property
Public Property Get Name() As String
  Name = name_
End Property

'Setter/Getter'
Public Sub setName(ByVal argValue As String)
  name_ = argValue
End Sub
Public Function getName() As String
  getName = name_
End Function

こちらもNameプロパティのProperty LetProperty Getを持たせる一方、同じ機能を提供するSetter/Getterメソッドを実装している。

使ってみる

ParentHogeインスタンスから、配下のChildオブジェクトのNameにアクセスする。

標準モジュール
Private Sub test02()
'(1) Propertyを使用'
  Dim p1 As ParentHoge
  Set p1 = New ParentHoge
  Set p1.Child = New ChildHoge
  p1.Child.Name = "ち~んw"
  Debug.Print p1.Child.Name
'(2) Setter/Getterを使用'
  Dim p2 As ParentHoge
  Set p2 = New ParentHoge
  Call p2.setChild(New ChildHoge)
  Call p2.getChild.setName("( ´_ゝ`)フーン")
  Debug.Print p2.getChild.getName
End Sub

(1)、(2)ともに、やっている内容は同じ。よって、実行すると、イミディエイト ウインドウには

f:id:akashi_keirin:20191025080143j:plain

このように表示される。

おわりに

少なくとも、利用側のコードの可読性という点では、圧倒的にPropertyを使うやり方が上回っていると思う。

何となくSetter/Getterの方がカッコよく思えてしまうのですがw