1. Introduction

In this tutorial, we’ll discuss conditionals – a programming construct that allows a program to make decisions based on certain conditions. We’ll focus on two relevant related practices  –  encapsulating conditionals and avoiding negative conditionals.

2. Conditionals

Conditionals are a fundamental programming element that allows a computer to make decisions depending on specific criteria. They enable a program to execute distinct code branches based on particular conditions.

We have several types of conditionals used in programming languages, including if statements, switch-case, and ternary statements. For clarity, we’ll discuss the if statements using python syntax in this section.

2.1. If Statement

If Statement is the most basic form. It is a programming construct that allows the specification of a code block executed if a given condition is satisfied.

The syntax is written as follows:

algorithm IfStatement(condition):
    // INPUT
    //   condition = a boolean expression
    // OUTPUT
    //   Executes code blocks if condition is true

    if condition:
        // code blocks 

2.1. If-Else Statement

If-else statement allows a program to execute one code block if a condition evaluates to true or a different one if the condition evaluates to false.

The syntax for the if-else statement follows:

algorithm IfElseStatement(condition):
    // INPUT
    //   condition = A boolean expression
    // OUTPUT
    //   Executes one of two sets of code blocks based on the condition

    if condition:
        // code blocks 
    else:
        // code blocks

Example for clarity:

algorithm IfElseExample(country):
    // INPUT
    //   country = a string representing a country code
    // OUTPUT
    //   Converts a country code to its full name if the code is "sk", otherwise sets it to "Unknown"

    if country = "sk":
        country <- "Slovakia"
    else:
        country <- "Unknown"

In the presented example, the program will assign “Slovakia to the variable “country” once the condition height > 160 is true; consequently, the code for the else statement will not execute.

2.3. If-Else-If

Other forms of if statements include the if-else-if. Adding one or more else-if clauses enables it to test for additional conditions.

The syntax for using the if-else-if statement is shown next:

algorithm IfElseIfStatement(condition1, condition2):
    // INPUT
    //   condition1, condition2 = Boolean expressions
    // OUTPUT
    //   Executes code based on which condition is satisfied

    if condition1:
        // code to execute if condition1 is true
    else if condition2:
        // code to execute if condition1 is false and condition2 is true
    else:
        // code to execute if none of the conditions are satisfied

3. Encapsulating Conditionals

The method of arranging and merging several conditional statements (e.g., if-else statements) into a single structure or function is called encapsulating conditionals. This method can help improve the readability and maintainability of a code and reduce code duplication. Let’s consider an example using conditional with and without encapsulation.

The following code uses conditionals without encapsulation:

algorithm ConditionalsWithoutEncapsulation(customer_type, order_total):
    // INPUT
    //   customer_type = the type of the customer ('regular', 'premium', etc.)
    //   order_total = the total amount of the order
    // OUTPUT
    //   Assigns a discount based on customer type and order total

    discount <- 0
    if customer_type = 'regular': 
        if order_total > 100:
            discount <- 0.15
    else if customer_type = 'premium': 
        if order_total > 100:
            discount <- 0.2
    else:
        discount <- 0.1

In this code version, the conditional statements are not encapsulated within a function. Instead, the code directly assigns a value to the discount variable based on the conditions.

The code next shows an encapsulated version of the previously presented code:

function getOrderDiscount(order_total, customer_type):
    // INPUT
    //   order_total = the total amount of the order
    //   customer_type = the type of the customer ('regular', 'premium', etc.)
    // OUTPUT
    //   Returns the discount rate based on customer type and order total

    discount <- 0
    if customer_type = 'regular':
        if order_total > 100:
            discount <- 0.15
    else if customer_type = 'premium':
        if order_total > 100:
            discount <- 0.2
    else:
        discount <- 0.1

    return discount

In the second example, we have a function getOrderDiscount that takes an order_total and a customer_type as input and returns a discount amount based on these values. The discount amount is determined by a series of nested if-else statements encapsulated within the function.

This structure makes it easy to reuse the function whenever the need to calculate an order discount arises without duplicating the conditional logic in multiple places in our code. Thus, we can achieve a cleaner code.

4. Avoiding Negative Conditionals

Avoiding negative conditionals refers to the practice of writing conditional statements in a way that avoids using negative language or negation (e.g., not, !). It means writing conditional statements that check for the presence of a condition (e.g., if Peter in names) rather than its absence (e.g., if Peter not in names).

It makes code easier to read and understand because it can be more intuitive to think in terms of positive conditions rather than negative ones.

There are different ways to avoid negative conditionals, including using positive conditions, employing positive language, and inverting the logic of the conditional. Some details and examples of such strategy are presented next:

Use positive conditions: instead of negative conditions, use positive conditions that specify what should happen when a given condition is satisfied. For example:

algorithm PositiveConditionExample(x):
    // INPUT
    //   x = A numeric value
    // OUTPUT
    //   Executes code based on the value of x

    // Negative conditional
    if x != 0:
        // code to execute if x is not equal to 0

    // Positive conditional
    if x = 0:
        // code to execute if x is equal to 0

Use positive language/word: use positive language, like if success, to specify the condition you are checking, instead of negative language if not error. For example:

algorithm PositiveLanguageExample(tall, short):
    // INPUT
    //   tall, short = Boolean variables
    // OUTPUT
    //   Executes code based on the values of tall and short

    // Negative conditional
    if not tall:
        // code to execute

    // Positive conditional
    if short:
        // code to execute

Invert the logic of the conditional: instead of using a negative conditional, we invert the logic of the conditional so that it becomes positive. For example:

algorithm InvertLogicExample(x):
    // INPUT
    //   x = A numeric value
    // OUTPUT
    //   Executes code based on the value of x

    // Negative conditional
    if not x > 10:
        // code to execute

    // Positive conditional
    if x <= 10:
        // code to execute

Using positive conditionals whenever possible is always a good idea. They are easier to read and understand, more efficient, and less prone to errors.

6. Conclusion

In this article, we discussed conditionals. Conditionals are an important tool for making decisions in a program. Encapsulating conditionals and avoiding negative conditionals helps in improving code readability and maintainability.


» 下一篇: 无权树的中心