I'm making a course on Laravel Sanctum: MasteringAuth.com

Create more objects for more powerful and expressive code

Constantin Druc ยท 16 Oct, 2021

[00:01] Sometimes it makes sense to extract new objects even for the most basic things. One example is the concept of money. Money isn't just a number, it also has a currency. The currency itself isn't just a string. The currency has a code, a symbol, and a name.

[00:22] When dealing with primitive values like integers, strings, arrays, try to think of objects that could replace them. For example, instead of a string phone number, you could have a phone number object. Instead of an integer seconds, you could have a duration object. Instead of a string name, you could have a person name object.

[00:52] Not only will your code become more expressive, but those objects also tend to attract new behavior. The phone number object may offer a prefix method, duration might become smart enough to give you the duration in minutes, or hours, or whatever unit of measure you desire. The name will no longer be a dumb string, it will give you its initials, the first, or last name, or even the full name.

[01:34] Using objects instead of primitives makes your code more powerful and more expressive. Now, in my case, I have this video id string. As far as I know, youtube doesn't follow a specific format for the video ids; they seem random. So at first glance there isn't much I could do with the id itself. However, a youtube video id class might serve as a great place to retrieve the id from a video url. So we could have youtube video id from url, and then pass the link to the video.

[02:08] Now let's create this class. I'll duplicate the youtube talk one, and then remove everything inside it, and here, we'll have a primary constructor that will receive the id as a string, and then we'll have a secondary constructor, public static function from url that will receive the url, and we return a new instance of self. Now to get the query string from the url we could do parse url passive url and then php url query. This will give us the query string, but we need the actual parameters. To put the parameters into an array we could do parse string and then pass it the array. Now if we don't have a v parameter, which is the id of the video, so if we don't have params of v then we need to throw an exception, otherwise we'll return new self and then pass params of v.

[03:33] Finally we need to add a tostring method, and here we'll do return this id. Now our youtube talk class will no longer accept just a string, it will need a youtube video id instead. And then down here, where we use the id, we'll cast it to string. Finally, in our test, let's import the video id class, remove this one, rerun the test, and it still passes.

[04:11] Let's arrange these a bit, and that was it. Remember, instead of using primitives, see if you can come up with an object that better represents what you are trying to express.