9. Using a CarPark class instead

The problem with the above solution is that the code handling the carpark is mixed up with the code handling the GUI. If there is a bug with the code for the carpark, then it is difficult to find the code because of all the code to do with the GUI.

It would be better to design a class for handling a carpark. If we are going to do this, then as before there are two questions to answer:

We have already decided an answer to the first question: a collection of number plates represented using an ArrayList. There are all sorts of operations that we could provide:

Here is the code of one possible CarPark class:

0355: Imports System.Text
0356: Public Class CarPark
0357:     Private iArrayList As ArrayList
0358:     Public Sub New()
0359:         iArrayList = New ArrayList
0360:     End Sub
0361:     Public Sub Arrive(ByVal pString As String)
0362:         iArrayList.Add(pString)
0363:     End Sub
0364:     Public Sub Depart(ByVal pString As String)
0365:         iArrayList.Remove(pString)
0366:     End Sub
0367:     Public Overrides Function ToString() As String
0368:         Dim tStringBuilder As StringBuilder = New StringBuilder
0369:         For Each tString As String In iArrayList
0370:             tStringBuilder.Append(tString & vbCrLf)
0371:         Next
0372:         Return tStringBuilder.ToString()
0373:     End Function
0374:     Public Function Size() As Integer
0375:         Return iArrayList.Count
0376:     End Function
0377: End Class

And here are the relevant parts of the Form1 class altered to use the CarPark class:

0378: Public Class Form1
0379:     Inherits System.Windows.Forms.Form
0381:     Private iCarPark As CarPark
0382: #Region " Windows Form Designer generated code "
0384:     Public Sub New()
0385:         MyBase.New()
0387:         'This call is required by the Windows Form Designer.
0388:         InitializeComponent()
0390:         'Add any initialization after the InitializeComponent() call
0391:         iCarPark = New CarPark
0392:     End Sub


0488:     Private Sub Button1_Click(ByVal sender As System.Object, _
0489:             ByVal e As System.EventArgs) Handles Button1.Click
0490:         iCarPark.Arrive(TextBox1.Text)
0491:         Label1.Text = TextBox1.Text + " has arrived"
0492:     End Sub
0494:     Private Sub Button2_Click(ByVal sender As System.Object, _
0495:             ByVal e As System.EventArgs) Handles Button2.Click
0496:         iCarPark.Depart(TextBox1.Text)
0497:         Label1.Text = TextBox1.Text + " has departed"
0498:     End Sub
0500:     Private Sub Button3_Click(ByVal sender As System.Object, _
0501:             ByVal e As System.EventArgs) Handles Button3.Click
0502:         TextBox2.Text = iCarPark.ToString()
0503:     End Sub
0504: End Class