Is it neccessary to create this class to achieve OCP?

Hi;

I found some code in Laracast website that does not make sense to me. He is trying to explain OCP (open close prncipals).

Why is he even creating area_calculator class? square class is doing everything anyway, isn’t it? I think the whole area_calculator can just go.

interface shape
	{
		public function area();
	}

class square implements shape
	{
		public $width;
		public $height;

		public function __construct($width, $height)
			{
				$this->height = $height;
				$this->width = $width;
			}
		public function area()
			{
				return $this->width * $this->height;
			}
	}

class area_calculator
	{
		public function calculates($shape)
			{
				foreach($shapes as $shape)
					{
						$area[] = $shape->area();
					}
				return array_sum($area);	
			}
	}

Granted, it’s been more than a few years since I had a geometry class. but it looks like the “square” class is mis-named. i.e. squares have equal height and width.

Maybe it would better be named "rectangle’ or is that code meant as an example of something else and not meant to be mathematically correct?

And what about other shapes?

What I am asking is that if each shapes class contains the formula in it anyways, why even have an extra class?

I agree.

On the other hand, it seems that the whole point of the code is to demonstrate a principle, not to be refined production code.

On the other other hand, I’m not sure I see the open/closed principle being demonstrated in the code posted.

:confused:

Can you see https://laracasts.com/lessons/open-closed-principle ?

Cheers

Nope. They want money.