Dennis
Dennis

Reputation: 8101

How to properly call a class while providing error reporting at the class-caller level

I am writing fresh code, as part of refactoring an older legacy codebase.

Specifically, I am writing a Device class that will be used to compute various specifications of a device.

Device class depends on device's model number and particle count and I can call it as $device = new Device($modelNumber, $particleCount);

Problem: since this class will go into existing legacy code, I have no direct influence on if this class will be called properly. For Device to work, it needs to have correct model number and correct particle count. If it does not receive the proper configuration data, internally device will not be initialized, and the class will not work. I think that I need to find a way to let the caller know that there was an error, in case an invalid configuration data was supplied. How do I structure this to be in line with object oriented principles?

Or, alternatively, do I need to concern myself with this? I think there is a principle that if you supply garbage, you get garbage back, aka my class only needs to work properly with proper data. If improper data is supplied, it can bake a cake instead, or do nothing (and possibly fail silently). Well, I am not sure if this principle will be great. I do need something to complain if supplied configuration data is bad.

Here is some code of what I am thinking:

$device = new Device($x, $y); 
$device->getData();

The above will fail or produce bad or no data if $x or $y are outside of device specs. I don't know how to handle this failure. I also want to assume that $device is valid when I call getData() method, and I can't make that assumption.

or

$device = new Device($x, $y); 
if ($device->isValid())
    $device->getData();
else
    blow_up("invalid device configuration supplied");

The above is better, but the caller has to now they are to call isValid() function. This also "waters down" my class. It has to do two things: 1) create device, 2) verify device configuration is valid.

I can create a DeviceChecker class that deals with configuration vefication. And maybe that's a solution. It bothers me a little that DeviceChecker will have to contain some part of the logic that is already in Device class.

Questions

Upvotes: 0

Views: 51

Answers (1)

user3099794
user3099794

Reputation: 66

I think you need to use below code to verify your passed arguments in construct
  class Device {
        public function __constructor($modelNumber, $particleCount) {
            if(!$this->isValid($modelNumber, $particleCount) {
                return false; //or return any error 
            }
        }
    }   
This will check the passed params are valid or not and create object based on that only, otherwise return false or any error.

Upvotes: 1

Related Questions