4 Class can include “methods”

It is true that one can use classes without using other aspects of OOP. However, the ability to also package methods in a class (along with properties) can also come in very handy.

To follow our example, let us imagine that we have the following classes defined:

A web script should have some minimal logic to validate objects of each of these classes, just in case a database is corrupted, or a user specifies incorrect parameters. Using the procedural method, each class has its own validation function that returns true if and only if an object of that class is considered valid.

Obviously, each validation function must have a different name, such as validateQuestion, validateUser and validateCourse. While this method works fine, it does get quite tedious when there are 20 more classes that have their own validation functions!

OOP specifies that even subroutines (functions and procedures) can be packaged into classes. This means that the Question class gets to specify its validate function, the User class gets to specify its own validate function and etc. Two different classes can specify a function of the same name.

As a result, an object called newUser of the class User can invoke the “validate” function of the User class by the following syntax:

    newUser.validate();  
  

Similarly, an object called revisedQuestion of the class Question can invoke the “validate” function of the Question class using the following code:

    revisedQuestion.validate();  
  

There is no confusion as to which validate function to use because the class of the objects (newUser and revisedQuestion) already resolves whose validate function to use!

Sharp eyes also realize that the functions do not take any parameters, not even to specify which User or Question object to validate. This is because newUser.validate() is interpreted as “hey, newUser object, invoke your validate function”. In other words, the “validate” function knows which object it should apply to because the function belongs to the object to be processed.

In conclusion, defining subroutines as a part of a class helps to prevent subroutine name clutter. It also eliminates any possibility of using the wrong type of objects as a parameter to subroutines.