Reviewing Initial Code
00:00 In the previous lesson, you studied the first version of your serializer solution. In this lesson, you’ll assess some of the code’s limitations. So the things to notice is firstly, of course, this is not a Factory Method design pattern.
00:14 We don’t have creators or factories or products. We just have client codes and the client needs to code all this, so the client needs to be aware of how JSON is implemented, and how XML is implemented.
00:30
There are a few other issues with this code. Let’s have a look at that. A potential drawback of the code is the conditional if-elif-else
structure.
00:40
Now, the example you studied is quite a basic one. It only has one elif
, but more advanced solutions quite quickly result in complex structures, potentially nested conditional structures.
00:54
So what are the challenges with complex conditional code? Well, firstly, it can be hard to read and therefore, it can be hard to understand. Also, it can be hard to maintain. In the code you looked at, the serialize()
function needs updating in too many situations, even in the basic example that you studied.
01:16
So the serialize()
function needs updating when a new format is introduced or when the Song
object changes. Also, when an object other than a song needs serializing, for example, you’ll see a book later on in the course and when the string representation for a format changes.
01:36 So it looks like there is plenty of opportunity for improvement, and you might consider a Factory Method design pattern for that. Now, to do that, the first thing you need is a common interface.
01:50 Because remember, to apply the Factory Method pattern, you’ll need a common interface. Now, do we have one? Well, we have a common goal. So that’s a good start, as we want to convert a song instance into a string representation,
02:05
and the common interface would be to pass the Song
object and the data format, so either JSON or XML or YAML in the near future to the serialize()
function.
02:17 That would be our common interface.
02:20 Now, in the next lesson, you’ll refactor this code into a basic implementation of the Factory Method pattern.
Become a Member to join the conversation.