Newer
Older
labs / tiddlers / content / labs / lab03 / _Labs_03_The Product Data Access Class.md
@Mark George Mark George on 20 Jul 2021 2 KB WIP lab 3

We need somewhere to store the product objects that the product editor dialog creates.

The best way to do this is to encapsulate the storage into a separate class. If we do this properly then we will be able to easily change the storage mechanism at a later date (such as switching from collections to a database) without affecting the GUIs.

We will create a data access class for managing the storage of the product objects.

The industry refers to instances of these classes as Data Access Objects (DAO). You can read more about the DAO concept at:

http://en.wikipedia.org/wiki/Data_access_object

One of the problems that object-oriented languages have is that you often find that the place that a piece of data is stored is five times removed from the location that needs it. DAO classes help us with this problem because they give us a centralised location that all objects can use to access the data.

  1. Add an issue to GitBucket that describes that you need to create a data access class for handling the storage of the products.

  2. Create a class in the dao package. Name the class ProductCollectionsDAO since it is a DAO class that will store products using collections.

  3. We need a place to store the product objects. The quickest way to do this is to use a private, static, ArrayList field. The field will hold the products, so name it appropriately (use a plural to indicate that the field holds many products).

    Don't forget to initialise the field (unless you enjoy debugging null-pointer exceptions).

    Take a second to think about why the field needs to be static.

  4. The class will need the following methods:

    • A method for saving a product. It will take a single product as a parameter and add it to the ArrayList. This method does not need to return anything. Name this method saveProduct.

    • A method for getting all of the products. It will take no parameters and will return the entire ArrayList. Name this method getProducts.

    • A method for removing a product. It will take a single product as a parameter and remove it from the ArrayList. This method does not need to return anything. Name this method removeProduct.

  5. Did you remember to 'program to an interface'?

    You should be using Collection on the left hand side of the field/method declarations instead of ArrayList.

    If not, fix it now.

  6. Did you remember to specify the 'type' of the collections?

    You should be using the angle bracket notation to specify what type of objects your collections are expecting to hold.

    If not, fix it now.

  7. Commit. This class is now complete, so you can use the Closes #4 command in your commit message to close the issue (assuming the issue #4 --- adapt to suit).