7

For example, if I wanted to generate some HTML based on some input. Which is the preferred way out of:

<?php

function generate_html($type, $input){
    switch($type){
        case 'paragraph':
            //Generate and return the HTML code for a paragraph
            break;
        case 'ul':
            //Generate and return the HTML code for an unordered list
            break;
        default:
            error('Invalid type specified');
            break;
    }
}

generate_html('paragraph', 'This is a paragraph');
generate_html('ul', [
    'This is the first item in a list',
    'This is the second item in a list'
]);

or:

<?php

function generate_paragraph($input){
    //Generate and return HTML for a paragraph
}

function generate_ul($input){
    //Generate and return HTML for a list
}

generate_paragraph('This is a paragraph');
generate_ul([
    'This is the first item in a list',
    'This is the second item in a list'
]);

I know about the idea of a function doing only one "thing", but I'm not sure how specific that "thing" should be. The first type could only be doing one thing (generating HTML), or it could be doing two things (generating lists, paragraphs). It depends how you look at it. What would be the preferred way of doing something like this?

0

2 Answers 2

5

I would suggest to create seperate functions like

  • generate_paragraph
  • generate_ul

instead of one general purpose function

  • generate_html

Because in later case we are controlling the behavior of function by passing parameters. Based on different parameters, function will behave differently. This is high coupling (Code Complete by Steve McConnell), which is discouraged in OO programming.

Regarding duplicate code, we can wrap that in a common function, which can be used by other functions.

1

I can find equal argument for both, except in one case. If the functions are similar enough, then usually a lot of the inner workings and plumbing is the same. So having multiple functions could mean code repetition. If that is the case then having one monolithic function that handles different types of output depending on an input argument could be the way to go.

1
  • 2
    Or it's a case for having an underlying function that both those functions call.
    – Tim B
    Dec 18, 2013 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy