loading...

re: OOP Overkill VIEW POST

FULL DISCUSSION
 

You mention using arrays (or stdClass objects I suppose), well the problem with passing arrays to a method or function is you then have to perform a bunch of checks to make sure you have all the elements you need.

If(isset($arr['foo']) && $arr['foo'] == 'A'){
  // DO THIS
}...

and repeat for however many elements you need to validate. And what if you have to pass that array to more than one function? Do you repeat all the validation, or do you abstract it, or do you rely on only being passed valid arrays from trusted callers?

What I do instead is write a dumb little class. It might only be 30 lines long but it'll be instantiated through a static method (or multiple static methods)

public static function createWithArray($input){
     $obj = new static();

     // do validation of array here.
     if(!$validated){
           $obj = false;
     } else {
          $obj->foo = $input['foo'];
          // I could also create and set other properties that I will KNOW exist based on observations of the input, which will make the code in my other function MUCH easier to read and understand.
          $obj->hasLongFoo = strlen($obj->foo) > 5;
     }
     return $obj;
}

Then back in my original function I change the definition to:

public function myFunc(\nameOfMyClass $myObj=null){
    // and I only need to check...
    if(!$myObj instanceof \nameOfMyClass)){
        return false;
    }

    // do stuff with valid object
    if($myObj->hasLongFoo){
         // do something with that information
    }
}

My function will only accept valid input.

This is how Swift works basically. You can trust your input and get on with writing clean code.

Massive additional benefit: My IDE (PHP Storm) understands what my object is and will tell me if I type any of the properties wrong. With an array you're on your own.

 

Thanks alot for the input ;)

Code of Conduct Report abuse