Prerequisite:

We have seen various methods to write if conditional depending upon number of conditions which includes if, if..else, else..if, nested..if etc. Switch can be used to replace else..if conditional statement and is used when there are multiple options to make the code simple. In this video, we will learn how to write switch and understand its importance over if conditional in various circumstances. We will also look at keywords such as break and exit, and learn the concept of ternary operation.

The second construct in Actionscript3.0 for comparison-based branching

Now, you must be wondering: "I have just completed a course on conditionals and if-else constructs; why another video course on conditionals?" Indeed, why another conditionalconstruct in the language itself? The if-else construct is intuitive enough and mimics the real world events and communication pretty accurately.

The answer is, as the experienced champion jockey will tell you: have horses for courses. With the if-else construct, we saw there are myriad ways of structuring and combining these constructs to form rich and complex reasoning code chunks.

We did discuss the various pros and cons of each combination, whether it be nesting clauses, or combining multiple conditionals, or testing for the complement. But we did not go deep into one particularly important desirable property of production-strength software : code readability.

Code readability is important because software engineering consists of a large cycle of stages from technical specifications, design specs, development, testing (Q/A) and enhancement. The stages that are relevant to this discussion are implementation (development) and maintenance (enhancement). Because of the sheer size and duration of such projects, it often turns out that the developer who wrote the original source for a module might not be around (in the team) by the time the enhancement phase is entered. Maintenance engineers fresh to the project have enough on their plates including complex and obscure code -- to cause them to pull their hair out!

The language designers found that while programmers would want to use the easy-to-understand and intuitive if-else if-else construct for the lion's share of decision making, there are exceptions to this practice. It's well known that many conditionals involve testing a single variable for a variety of values, and then performing tasks which need not be mutually exclusive across conditional blocks. That's, multiple if clauses could have the same code being executed. One might argue that such separate if-else clauses could be easily combined by logically chaining together these conditional expressions into one single, combined conditional.

But the major drawback of this approach is reduced code readability, which is what we set out to minimize. Clearly, the chinks in the if-else construct's armor lie exposed! The problem lies in the fact that the if-else if-else construct is not flexible enough for optimizing these borderline cases. Hence, language designers came up with an alternative: the switch construct, which had the functionality of the if-else if-else construct, and also some added flexibility. we'll examine the mechanism of the switch construct in detail in the relevant section of this course; let's now focus on other introductory information.

Main Advantage of Switch Construct

The main advantage of the switch construct is that its usage, as intended when a single variable is compared in multiple, cascading conditionals, reduces code clutter. The variable by name appears just once in the switch conditional, and is not repeated anywhere inside the body of the construct. So, if there are a series of comparisons and checks (say, 20 such checks) the occurrence of the identifier is reduced by 95 percent! This is a very significant figure, considering the fact that production-grade software usually has more than a million lines of code ( a maintenance nightmare!)

An important feature of a switch construct is that cases(as they are called) are not mutually exclusive in terms of flow of program control. That's, unless the break keyword is used in a standalone statement near the end of the current case, control falls through to the next case (even if the value being compared is not the original one!) This is mostly a bad thing, and that's why if-else statements are more predictable (due to the property of mutual exclusion) and as a result, more popular.

But the switch construct, with this property, gives programmers the power to control the elegance and readability of the code they develop, and this is where the beauty of exit-mechanism-control is seen. we'll explain this term and see more of it in a later summary.

A feature worth mentioning about the switch construct is the 'default' case. In the if-else if-else construct, the final 'else' handles the default case; that's, the situation where none of the preceding conditionals evaluated to true. The default case in a switch plays the same role. But, again, it may also be executed in the non-default scenario if the preceding case did not use the break statement to exit from the switch! we'll illustrate the facts discussed in this paragraph and the previous one, with concrete examples later in the course.

These exceptions apart, it's usually left to programmers to decide which construct they want to use in their code. Switch constructs can be used in a nested fashion as well, one inside another; just as in the case of if conditional constructs. A switch can also be nested inside an if conditional , and the other way round as well, when either construct can be used to provide the same functionality. The intention should always be to improve code readability, and optimization is not the issue. The major part of this course is dedicated to help the programmer in making such decisions.

Finally, there is another important topic to introduce, which almost always suffers the ignominy of neglect and is feared by most novice and inexperienced programmers: the ternary operator. Because we as students are exposed 99 percent of the time to unary and binary (Logical and arithmetic) operators, be it while learning programming, English or math, we are instinctively wary of this operator. But in reality, it surpasses the switch construct in the power to express code in a more readable and optimized manner (although in a totally separate context). The sections on ternary operators (the last two summary sections) explains these issues in detail with intuitive examples that are simple to understand.

We'll also examine a rather intriguing and unique functionality that can be realized by using the switch construct, where we can control the number of cases of a switch that are executed, depending on the input value and the order of the individual cases -- including the default -- in the switch block. It's something that cannot be realized at all by an if-else if-else construct, in any order of nesting/combination. This, you can say, is the switch construct's lethal weapon. Though not frequently used, it's elegance and power personified. Again, this feature is a result of the flexibility provided by the switch construct with regard to its exit mechanism.

So, looks like we're all set to start off with the course! Initially, we'll focus on the switch construct: the syntax, keyword, semantics and how to combine multiple features to gain flexibility in program output. we'll put special emphasis on code readability and reduced clutter. We'll also be careful to point out that along with switch comes immense power, and with power, comes great responsibility. If we can make that adjustment , we're safe and ready to go!

At a later stage we'll explore the ternary operator, and how it can improve code efficiency and reduce code clutter as well. We show a couple of examples comparing it to equivalent best-effort if-else implementations, and explain the difference.

With this background, you will find it easier to understand the basis for the language features being discussed, which, hopefully, will make you better programmers. With proper effort, this section should not be difficult to master. After all, Rome wasn't built in a day! Good luck!

Our free content is sponsored by these ads become a prime member and get rid of them.