Home > Articles > Software Development & Management > Object Technology

This chapter is from the book

Example: Creating a Properties Class

In the following pages, I will create a new class called Properties, which will be a subclass of the Dictionary class.


There are three potential scenarios to consider for the Constructor. You may get the data to be parsed for the Properties class from a file or a string, and you also may want to be able to instantiate the class without any data so that you can add it later, either by individually setting the key/value pairs or by some other method.

To accomplish this, I'll overload the Constructor method with three versions. If I did nothing, the default Constructor would be used, which takes no parameters. However—and this is a big "however"—if I overload the Constructor class with any other Constructor, the default Constructor goes away and is not accessible. The reason is that it allows you to require that the class accept a parameter in the Constructor because you do not always want the default Constructor available.

This means that you have to reimplement the default Constructor to retain the capability to instantiate the class with no parameters, so that is what I do first:

Sub Constructor()
  // Do nothing
End Sub

The second implementation will accept a string in the parameter. Whenever this Constructor is called, the class automatically parses the file as part of the Constructor. This means that after the class is instantiated, the key/value pairs are accessible, with no further steps required.

Sub Constructor(myPropertyString as String)

  If myPropertyString <> " " Then
    // An error as occurred
  End If

End Sub

The following implementation accepts a FolderItem. It tests to make sure the FolderItem is readable and writeable, both of which are functions of the FolderItem class. If the FolderItem instance is readable and writeable, it sends the file to the overloaded parsePropertyFile function.

Sub Constructor(myPropertyFile as FolderItem)
  If myPropertyFile.exists Then

    If myPropertyFile.IsReadable and myPropertyFile.IsWriteable Then
      // An error has occurred
    End If

    // An error has occurred
  End If

End Sub


Functionget(aKey as string, aDefault as string) As string
  Dim s as String
  s = Me.Lookup(aKey, aDefault)
End Function

The get() function is also overloaded to take only one string as a parameter. When this occurs, I need to test first to see whether the Dictionary has the key passed in the parameter, and if it doesn't, respond appropriately.

Function get(aKey as string) As string
  Dim s as String

  If Me.HasKey(aKey) = True Then
    s = Me.Value(aKey)
    // Handle the Error

    Return  ""
  End If
 End Function

You can accomplish the equivalent by using the Dictionary's Lookup() function. Remember that nothing is stopping you from calling the Lookup() function directly from other parts of your program because it is a public method of Dictionary.

Function get(aKey as string) As string
  Dim s as String

  s = Me.Lookup(aKey, "")
End Function

I can also replicate the same functionality by calling the first get() function from the second:

Function get(aKey as string) As string
  Dim s as String

  s = Me.get(aKey, "")
End Function

Of the three options I have given for implementing function get(aKey) as String, the last option is preferable, in my opinion. You may be wondering why you should bother implementing the get() method at all, because you can use the native Dictionary methods anyway. One reason is because get() provides a simpler syntax. Dictionaries can use Variants for keys and values, but I really care only about strings, so get() makes the assumption that it's a string. More importantly, because of the two versions of get() that I am using, I can change the implementation in the future of how the default value is generated when no default value is given, or add tests to the code to make sure that the default value that is passed is a valid default value.

There is yet another approach to implementing get() that accomplishes the same goals, more or less: instead of overloading get(), you can override and overload Lookup() to achieve the same effect.

I'll override Lookup() first. Remember that to override a method, the signature has to be the same, which means the parameters must accept Variants. Also, the reason I said I liked using get() was that it gave me an opportunity to test for legal values first. You can do the same here, by calling the parent class's version of Lookup after you've tested the values:

Function Lookup(aKey as Variant, aDefaultValue as Variant) as String
  Dim key,default as String
  key = aKey.StringValue
  default = aDefaultValue.StringValue
  If default <> "" Then
    Return Dictionary.Lookup(key, default).StringValue()
  End If
End Function

I can also keep things simple by using an overloaded version of Lookup() that accepts only a key in the parameter and handles the default value automatically:

Function Lookup(aKey as Variant) as String
  Dim key,default as String
  key = aKey.StringValue
  default = aDefaultValue.StringValue
  If default <> "" Then
    Return Dictionary.Lookup(key, default).StringValue()
  End If
End Function

Note that in both cases, I returned a string rather than a Variant. REALbasic doesn't pay attention to the return value when determining whether a method is overloaded. This allows me to force the return of a string, even though the original Lookup() implementation returns a Variant.


In addition to get(), I also implemented a set() subroutine. Again, this is for simplicity's sake because I could also just call the Dictionary.Value() function directly. It also means I can test the values before assigning them, which always helps. I also use the Assigns keyword, which alters the way that the method can be called in your program. An example of how it is used follows this example:

Sub set(aKey as string, assigns aProperty as string)

If aKey <> "" and aProperty <> "" Then
  Me.Value(aKey) = aProperty
// An error occurred
End if
End Sub

By using the Assigns keyword in the parameter, you can set a key/value pair using the following syntax, which mirrors the syntax used for the Value() function of Dictionary:

Dim prop as Properties
prop = New Properties()
prop.set("FirstKey") = "FirstValue"


The first step to parsing the file is to split the string into individual lines. I have two functions for this—one that accepts a string and another that accepts a FolderItem. The string version splits the string on a newline character (ASCII value of 13) and then cycles through each line, parsing the lines individually.

Protected Sub parsePropertyFile(myFile as string)
  Dim my_array(-1) as String
  Dim line as String

  my_array = myFile.split(Chr(13))

  For Each line In my_array
End Sub

A second version of parsePropertyFile accepts a FolderItem as a parameter. FolderItems are discussed at length later in the book, but the code in this example is sufficiently self-explanatory that you get the general idea of what is happening. When you open a FolderItem as a text file, it returns a TextInputStream. A TextInputStream allows you to read it line by line by calling the ReadLine() function.

Protected Sub parsePropertyFile(myPropertyFile as folderItem)
  Dim textInput as TextInputStream
  Dim astr as string

  If myPropertyFile Is Nil Then
       // An error has occurred
  End If

  If myPropertyFile.exists Then
    Me.file = myPropertyFile
    textInput = me.file.OpenAsTextFile
    Loop Until textInput.EOF

    // An error has occurred
  End If

End Sub


Each line is parsed individually.

Protected Sub parseLine(my_line as string)
  Dim aKey, aValue as string

  // Split line at "=", and ignore comments
  If Left(my_line, 1) <> "#" Then
    If CountFields(my_line, "=")= 2 Then

      aValue = Trim(NthField(my_line, "=", 2))
      aKey = Trim(NthField(my_line, "=", 1))

      Me.set(aKey) = aValue

    End If

  End If // starts with "#"

End Sub

The first thing I test for is to see whether the line starts with a # character. In property files, a # at the beginning of a line indicates a comment, and because comments are only for human consumption, I can safely ignore them in my program.

The next step is to split the line into two values, one for the property and the other for the value. Although I could use the Split() function, I have chosen to use the CountFields/NthField combination primarily because it makes it a little easier to count how many fields there are. Because each property is separated from its value by an equal sign, I will parse the line only if there are two fields in the line (which is the same thing as saying that there is only one "=" sign on the line).

The property name, or key, is in the first field, and the value is in the second field. When extracting the values using NthField, I trim the results, which removes whitespace on either side of the string. This accounts for situations where there are extra spaces between the "=" sign and the values themselves. As a result, both of these formats will be parsed correctly:

aProperty = aValue

Finally, I use the set() method to add the key/value pair to the Dictionary.

Now that all the members of the class are implemented, here is an example of how you can use the class:

Dim prop as Properties
Dim s as String
Dim propStr as String
propStr = "First=FirstValue"  + Chr(13) + "Second=SecondValue"
prop = New Properties(propStr)
s = prop.get("First") // s equals "FirstValue"
prop.set("Third") = "ThirdValue"
s = prop.get("Third") // s equals "ThirdValue"

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020