Skip to content

Abstract test conditions into well-named helper functions. #3

@sdhunt

Description

@sdhunt

if ((playerName && playerMove1 && playerMove1Val && playerMove2 && playerMove2Val && playerMove3 && playerMove3Val)
&& (ensureGameOptions(playerMove1))
&& (ensureGameOptions(playerMove2))
&& (ensureGameOptions(playerMove3))){
//console.log("Not null")
//Check values less than 1, greater than 99, totals greater than 99.
if ((playerMove1Val && playerMove2Val && playerMove3Val) > 1 &&
(playerMove1Val + playerMove2Val + playerMove3Val) <= 99 &&
(playerMove1Val && playerMove2Val && playerMove3Val) <= 100)
{

This is "quite a mouthful" and difficult to verify for correctness at a glance. Also, notice because you have used "positive" tests, each test adds a level of indentation.

My suggestion would be to reverse the sense of the tests, so you can exit the function as soon as you determine that the input is bad (this is known as "fail fast"). This has the benefit of reducing the levels of indentation required. Also, abstract the tests into helper methods, to aid readability of the code.

Note too, that I've chosen shorter names for the parameters to the function.

For example:

const setPlayerMoves = (playerName, m1type, m1value, m2type, m2value, m3type, m3value) => {
    if (!m1type || !m1value || !m2type || !m2value || !m3type || !m3value) {
        return null;
    }
    if (!validTypes(m1type, m2type, m3type) || !validValues(m1value, m2value, m3value)) {
        return null;
    }
    // at this point, we know the types and values are good... 
    // ...
};

const validTypes = (t1, t2, t3) => isValidType(t1) && isValidType(t2) && isValidType(t3);

const validValues = (v1, v2, v3) => ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions