Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

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.

share|improve this answer
add comment

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.

share|improve this answer
1  
Or it's a case for having an underlying function that both those functions call. –  Tim B Dec 18 '13 at 22:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.