Vb Classic Refactor Type To Class

Refactoring a VbClassic user-defined Type into a Class is a language-specific case of ReplaceRecordWithDataClass.

Problem:

This VisualBasic program has structures / records / VisualBasic user-defined "Types," and some behavior of the program should be more closely associated with this data. Encapsulation, polymorphism, and other OO concepts may also be appropriate.

Solution:
Convert VisualBasic user-defined types to VisualBasic classes.

How To:
  1. Create a class of the same name as the Type.
  2. Copy Type members to the class and make them Private member variables.
  3. Provide Property Get/Set/Let methods to enable access to the member variables.
  4. Eliminate the original Type declaration.
  5. Ensure that objects are allocated when needed:
  6. Simple variables: Where "Dim var As TypeName?" exists, add "Set var = new TypeName?".
  7. Arrays: Ensure that array elements are given new objects at initialization, or when first used.


Fair Warning: I haven't done this yet. I'll try it out as soon as I get a chance. Comments are welcome. -- JeffGrigg

I would suggest changing 2 to use public members and postpone 3 until you need it. Property gets and lets are more work and CodeClutter?. VisualBasic types are read/write without any checks, so the possibility of YouArentGonnaNeedIt is definitely there. -- ThomasEyde

In practice we did make all member variables public. In fact, we started with property get/let functions, but later killed practically all of them, making the member variables public. (Not that the project was an example of good, or even acceptable OO practice. ;-) I would think that "good" objects would have well designed methods and no public properties. (That is, instead of refactoring between public member variables and public properties, it would be better to ExtractMethod into the class, to create proper initialization functions and methods, and eliminate public properties.) -- JeffGrigg


Some other things to look out for if you're working with legacy code:

 Type
GrilRec(2) as Long
becomes

 Private clGrilRec(2) as Long

Public Property Get GrilRec(ByVal Index As Long) As Long GrilRec = clGrilRec(Index) End Property

Public Property Let GrilRec(ByVal Index As Long, ByVal NewGrilRec As Long) clGrilRec(Index) = NewGrilRec End Property

-- IainBuckingham


Two insights into the relationship between Types and Classes in VisualBasic:


I have changed step 6 where it suggested to convert to "Dim var As New TypeName?", which should only be useful vary rarely. -- MarkHurd


CategoryRefactoring CategoryVbClassic


EditText of this page (last edited February 12, 2009) or FindPage with title or text search