Software principles

Guardians Of The Program

Let’s say we have a special chef robot in a restaurant which can cook a variety of meals for customers.

It has a function who’s responsible for cooking a meal called cook:

class Chef:
	def __init__(self, name):
		print(f"Chef name: {name}")

	def cook(self, meal):
		pass

While meal is defined as:

class Meal:
	def __init__(self, mealId):
		print(f"Initializing meal: {mealId}")

	def ingredients(self):
		pass

	def instructions(self):
		pass

Every customer chooses the meal they want to eat and the kitchen manager tells the available chef to cook it.

Let’s say we picked cheeseburger. The chef receives the order (which is an instance of Meal class) and starts cooking it:

It takes 300 grams of ground beef, salt, pepper, chopped garlic, etc. Then it shapes the ingredients like a ring and puts it on the grill. In the meanwhile, the chef chops some tomatoes, lettuce, red onions and pickles. It flips the meat, cuts the bun, and heats it on the grill too. Then, after working on this dish and almost finishing with this order, the chef wants to add the cheese. There is no cheese. Where is the cheese? Oh, man. Where is it? Here? no. Behind this? no. ERROR ERROR NO cheese beep boop. The dish is ruined. The customer is furious and the ingredients are now in the recycle bin waiting for some stray cats to find it.

How the chef could prevent this mess before start cooking?

It could check if all the ingredients are available (and acquire them):

class Chef:
	def __init__(self, name):
		print(f"Chef name: {name}")

	def cook(self, meal):
		if not self.canStartCooking(meal):
			return

		# cooking logic

	def canStartCooking(self, meal):
		for ingredient in meal.ingredients():
			if not ingredient.acquire():
				return False
		return True

In this case, the robot won’t start working on the new order if it knows it can’t at the moment.

According to Wikipedia:

guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question.

canStartCooking is a guard in our program.

Like a security guard, using guards in programs can save us trouble.


If you have any questions feel free to comment or contact me directly.

Thank you for reading this. Please share and visit soon again,

Orian Zinger.

Note: This post was written right before lunchtime. I was hungry šŸ™‚

One thought on “Guardians Of The Program

Leave a comment