SchweeDubulus
SchweeDubulus

Reputation: 61

Proper way to handle incorrect instance creation of a class?

I have a Shape class with child classes such as Rectangle and Triangle. My provided code attempts to create a Rectangle class with only 3 'sides' in the array passed in. Right now, there is an exception thrown, which seems correct for this case. The only issue is that this prevents the rest of the code from being excuted. The obvious way to fix this is to remove the incorrect creation call but I am wondering if there is a more sophisticated way to handle this? Something along the lines of automatically creating it as a triangle instead of a Rectangle when only 3 sides are provided? Thanks.

Upvotes: 0

Views: 52

Answers (1)

Jim Wright
Jim Wright

Reputation: 6058

You could use a factory method to do this, for example:

class ShapeFactory {
    public function shapeFromSides($sides) {
        if (count($sides) == 4) {
            return $this->createRectangle($sides);
        }
        if (count($sides) == 3) {
            return $this->createTriangle($sides);
        }
        throw new \Exception('Unable to create shape from sides provided');
    }

    public function createRectangle($sides) {
        return new Rectangle($sides);
    }

    public function createTriange($sides) {
        return new Triangle($sides);
    }
}

Obviously this doesn't create your objects and the parameters are likely wrong, but it should give you an idea of how this method could work.


However, I agree with @deceze's comment. I don't really think creating a shape with an invalid amount of sides is logic that you should ever come across as it is most likely a programmer error.

Upvotes: 4

Related Questions