Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of passing a function as a parameter

Just studying for an exam and I can't find the answer to this question in our notes. Any help would be great.

Many languages permit subroutines/functions to be passed as parameters. List two advantages provided by this, and motivate each advantage with a clear explanatory example (this need not be code of pseudo-code).

like image 570
Darren Avatar asked Dec 12 '10 00:12

Darren


1 Answers

Think you are a manager of a charming singer ( in computer life : a program) , in the following two ways to start your morning.

Situation 1: You have to tell some underling to do the following a) get breakfast for the star and take great care with the kind of croissants she likes, remember she is very upset when she wakes up etc.. b) Put all cables on the stages using such and such power this lights but not that one , these colors ...

Situation 2: Ask your underling: Ask the majordomo to give our star her usual breakfast. Then ask the crew to take care of the stage for the usual songs.

Situation One is wrong from a computer point of view, it is typical of a quick and dirty way of doing. Yes you have the guy at hand but he is doing all the errands and handling several responsibilities of different types so he may be confused and moreover the order is long and detailed.

In situation two you are delegating, this handles the complexity , the order are short, we know who is doing the which jobs so we won't find a pink huge light bulb in the tea cup of the star (you think it is a joke but that is exactly what a bug is) . In a few words complexity is partitioned in a meaningful way.

If you do not see why situation two is like calling functions here is a pseudo code.

extern FUNCTION majordomo( client , service , options ) ;
extern FUNCTION crew ( task , options ) ;

FUNCTION startMorning() BEGIN

call ( underling, majordomo( for_ourstar, usual_breakfast, she_is_picky));
call ( underling, crew(usual cables, bright lights));
END

like image 145
Jérôme JEAN-CHARLES Avatar answered Sep 25 '22 13:09

Jérôme JEAN-CHARLES