Creating the Creator Function
00:00
In the previous lesson, you took an important step towards creating your Factory Method pattern by moving out the product functionality out of the serialize()
function.
00:13
Now, why is that important? That’s because the serialize()
function is client code and we want that client code to be as simple as possible, so the creation of the products should not be done by the clients.
00:25 You’ve outsourced that so to speak to the product functions. In this lesson, you’re going to take it a step further by outsourcing the decision-making process to a creator.
00:38
So what am I talking about here? On lines 13 to 18, in your serialize()
function, you see the if-elif-else
construction. So it looks like the client has to make a decision what happens when the format is JSON, and what happens when the data format is XML.
00:56 Now that decision, we want to outsource to the creator. Now, to do that, you are going to create a creator function. If you move to line 19 and create a little space, I again start with a comment.
01:11
So with hash and call it Creator
, just to point out where we are, give it a bit of structure. I’m going to create that function def_
,
01:22
and I’m going to call it get_serializer()
.
01:26
And that function takes song
and data_format
even as input parameters,
01:35
and for the moment just type pass
.
01:39
Then if you select lines 13 to 18, copy them, so Ctrl + C in my case, and then override the pass
on line 22, press Ctrl + V or paste. And now you have the if-elif-else
construction in your _get_serializer()
creator function.
02:02
The next step to do is then to reference or call this creator function in the serialize()
client code. So in the serialize()
function on line 12, you can select lines 13 to 18, and just delete those, indentation, and then just call _get_serializer()
.
02:22
So _get_serializer()
, and then pass in song
and data_format
.
02:31 And so that is the second step you have now created a creator function. The third step is to simplify the code a little bit, but that you will cover in the next lesson.
Become a Member to join the conversation.