lundi 5 septembre 2016

Approaches to working with a 'testing version' of a section of code

I often insert code into my project that I require to test a part of the site's functionality.

However, I find myself leaving this test code lying around in my code, commented out.

For example:

function getFoo() {
   return "Foo";
}

//function getFoo() {
//   return "Foo!!";
//}

When testing, I would need to toggle the commented state of each function so that I can use my testing version of getFoo().

One way around this is the following:

var testing = false;

function getFoo() {
    if (testing) {
        return "Foo"
    } else {
        return "Foo!!"
    }
}

However, to me this is a bad solution because it obscures what the function is doing, especially if it already starts with an if statement.

How can I optimise this approach so that I am not constantly toggling the commented state of a function, while maintaining clean, easy to read code?

Aucun commentaire:

Enregistrer un commentaire