You may come to a point where you have to load data from a file. No big deal so far. But what if the data can come to you in multiple file formats. Many developers still to this day would then setup a switch statement and depending on the file extension would then define how the file gets loaded.
Code Snippet
- Dim extension As String = IO.Path.GetExtension(filename)
- Select Case extension
- Case ".csv"
- ' Load csv file.
- Case ".txt"
- ' Load a text file.
- Case ".xls"
- ' Load a spreadsheet file.
- End Select
This works, but now you have three different subroutines that load a file in a class that is meant to have the data and not load the data. This violates the single responsibility principle. So instead we can create a dictionary that will be able to determine what file will get loaded.
Code Snippet
- Private fileExtensions As Dictionary(Of IFileLoad.FileExtensions, Lazy(Of IFileLoad))
The interface IFileLoad code is below.
Code Snippet
- Public Interface IFileLoad
- Enum FileExtensions As Integer
- CSV = 0
- TXT = 1
- XLS = 2
- End Enum
- Function ImportFile(filename As String) As List(Of IOrder)
- End Interface
Add the dictionary items so that they will load up the correct classes that can implement the IFileLoad interface. A side note is now if you have to export data then you have a class ready to implement a new export interface. The single responsibility then becomes input/output of files.
Code Snippet
- fileExtensions.Add(IFileLoad.FileExtensions.CSV, New Lazy(Of IFileLoad)(Function() New CSVImport))
- fileExtensions.Add(IFileLoad.FileExtensions.CSV, New Lazy(Of IFileLoad)(Function() New TXTImport))
- fileExtensions.Add(IFileLoad.FileExtensions.CSV, New Lazy(Of IFileLoad)(Function() New XLSImport))
The IOrder interface is then used because it won't matter if the order has additional detail, we just need the basics of an order. This allows the application to become extensible.
Code Snippet
- Public Interface IOrder
- Property OrderID As Integer
- Property OrderNumber As String
- Property OrderType As String
- Property Price As Double
- End Interface
Finally, we then get the file extension that will return the list of our orders.
Code Snippet
- Dim extension As String = IO.Path.GetExtension(filename)
- Dim importfile As IFileLoad = fileExtensions(extension.TrimStart(".")).Value
- Dim orders As List(Of IOrder) = importfile.ImportFile(filename)
This is so extremely powerful and maintains the single responsibility principle while using dependency inversion. Two key components of SOLID.
No comments:
Post a Comment