U
U
Urukhayy2015-03-07 09:34:06
Programming
Urukhayy, 2015-03-07 09:34:06

Narrowly specialized or broadly?

What is the best way to write functions for a small number of objects?
I will give a vivid example: We have 3 apples of different breeds. The user selects one of the apples and he should be shown a dialog - "Purchasing an apple of breed N ....... Would you like to purchase?", In the dialog there are 2 buttons - "Yes" and "No". Processing the result of the dialog occurs in a separate function.
So. Make a common structure for processing all dialogues, which includes recognition of the apple breed already inside the structure, or for each breed its own structure?
What case 1 would look like (general structure):

function test(){
// Для начала нужно определить породу яблок. В текущей задаче это решаемо только циклом
for(var i in apples)
{
    switch(apples[i].type)
    {
        case 1: // обработка для сорта 1
        case 2: // обработка для сорта 2
        case 3: // обработка для сорта 3
    }
}
}

How case 2 (individual structure) would look like:
function test(type){ // порода яблока приходит сразу
// обработка для сорта
}

The bottom line is that the type of apple for the second case is stored not in the apples object, but in global variables (var sort1, sort2, sort3), and when the user selects an apple, we directly send the global variable.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Armenian Radio, 2015-03-07
@gbg

Get rid of global variables, this is your main problem.

F
fr33zy, 2015-03-07
@fr33zy

The simplest solution, in my opinion, is to use a list of handlers, something like:

var appleHandler = {};
appleHandler.antonovka = function antonovkaHandler() {
  // Обрабатываем
}

At the right moment, we simply get the handler and call it.

M
Mercury13, 2015-03-10
@Mercury13

This is a "strategy" design pattern, and is nicely implemented as handlers or virtual functions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question