It’s commonly known that JavaScript is technically an object-oriented language, even though it doesn’t seem to follow some of the same language constructs as C# or Java and friends.
But all too often, while I do see JavaScript written well organizationally, it is still technically written prodecurally. Take this for instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
What’s the problem?
Now you may be thinking, what is the problem with having code like this? The answer is maintainability. If in another part of your application you decide you need to create a car and take a similar action, you must repeat this conditional logic.
The problem stems partially from having easy access to the properties of this object. By having instant access to the properties of this object, your program can look at an object and decide on an action to take. From an object-oriented standpoint, this is bad, because now the object does not manage its own state and actions, but rather the application does.
Is there a better solution?
Of course. When crafting objects its important to provide methods so they have ability to manage their own state (properties) and actions (methods). Let’s rework our example just a tad to see how this could be simply done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
What’s the difference?
The way this example differs from our previous one has to do with who manages when things happen. In each of the snippets, the cars are checked for newness before they get washed. The improvement again lies in its maintainability. If you have other code in the future that instantiates a car, you can call getWash() without fear having to determine whether the car gets washed or not. The car takes care of that for you. That is the power of object-oriented programming as opposed to procedural. Let your objects determine if they need to take action, and leave the application to do other things.
Maintenance will be easier in the future, I promise.