0

Hey guys,

I'm not having a problem, I was just wondering what's the best way of implementing isSomthing in OOP paradigm?


Take this example: we want to know if the user was temporarily (like 10 minutes) banned. Here are the two options:


  1. Implementing isTempBanned() method in the User class. Then whenever we want to check if user is banned, we just call this method. no change to the other parts of the code is required.


  1. Adding a isTempBanned property to the User class. Then whenever the state of user's ban changes, we update this property accordingly. Then when we need to know, we just use this property.


Can you explain Pros and Cons of each way? from these standpoints:

  • performance
  • code maintainability
  • clean code
  • readability
  • etc...

Keep in mind that there is no better way. I'm just asking to know when should I use the first method and when to use the second one.


Rahimi0151
  • 395
  • 3
  • 11

2 Answers2

2

Ultimately you have to use both of them!

based on Encapsulation principle , think of your example as a getter/setter scenario, to keep bugs as low as possible, getter is User.isBanned method, setter is User.banUser method.

class User{
    banned_until : Date = null

    isBanned(){
        if(this.banned_until){
            return this.banned_until.valueOf() > new Date().valueOf();
        }
        return false;
    }

    banUser(){
       this.banned_until = new Date() ///any date in future ....
    }
}
SemyColon.Me
  • 378
  • 3
  • 18
0

isSomthing is usually used for boolean. no matter what data type you use. all differences are method and property differences. I suggest you read this:

Properties vs Methods

Fateme
  • 26