SOLID Principles question

I studying about SOLID principles in OOP I have many questions about this principles …
One of this questions is
I have a User Class(Parent Class is Database Object) , Student Class(Parent class user) , Admin Class (Parent Class User) do I need to create an interface for Student Class and Admin Class ? to not break the Open/Closed Principle?

Nope. All you need to do is to not ever test if some object is instanceof Student or instanceof Admin. Instead, operate on derived types polymorphically by only invoking the base User class’s public methods.

Thank you so much for answering my question so the solution for this is to create some methods in User class and use this method in Admin Or User?

Yup, that’s right. For example:

// Bad

class User {}
class Student extends User {}
class Admin extends User {}

function printName($user) {
    if ($user instanceof Student) {
        echo 'The user is: student';
    }
    if ($user instanceof Admin) {
        echo 'The user is: admin';
    }
}

// Good

abstract class User {
    abstract public function getName();
}
class Student extends User {
    public function getName() {
        return 'user';
    }
}
class Admin extends User {
    public function getName() {
        return 'admin';
    }
}

function printName($user) {
    echo "The user is: {$user->getName()}";
}

The reason one is considered good and the other bad is because in the future, you might make more derived classes, maybe class Teacher extends User for example. In the bad example, if printName was passed a Teacher instance, it wouldn’t actually print anything, and a new bug would be in your program. Whereas the good example can handle any arbitrary derived type, both current and future, without ever needing to change.

1 Like

Thank you very much sir :slight_smile:

Sir Jeff_Mhot can I replace the abstract class User to a Interface ?

1 Like

Going back to the original question on SOLID principles. Over the years I have read the principles many times. Most make sense and I tend to follow them most of the time.

But some are just bizarre like this Open/Closed nonsense. Seems like it was written by a bunch of theologians. I’m personally convinced they are just making stuff up.

And with respect to the Student/Admin question. Will your admin class have admin only methods or are all the classes basically the same? If the classes will end up being the same then using a role based approach might be a possibility. A User with a role of student. etc. Just something to consider.

If there’s no implementation in there, then yes.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.