AutoPolicy
Case Study: string
s in switch
Statementsstring
s can be used in switch
expressions, and string
literals can be used in case
labels. To demonstrate this, we’ll implement an app that meets the following requirements:
You’ve been hired by an auto insurance company that serves these northeast states— Connecticut, Maine, Massachusetts, New Hampshire, New Jersey, New York, Pennsylvania, Rhode Island and Vermont. The company would like you to create a program that produces a report indicating for each of their auto insurance policies whether the policy is held in a state with “no-fault” auto insurance—Massachusetts, New Jersey, New York and Pennsylvania.
The app contains two classes—AutoPolicy
(Fig. 6.11) and AutoPolicyTest
(Fig. 6.12).
AutoPolicy
Class AutoPolicy
(Fig. 6.11) represents an auto insurance policy. The class contains:
auto-implemented int
property AccountNumber
(line 5) to store the policy’s account number,
auto-implemented string
property MakeAndModel
(line 6) to store the car’s make and model (such as a "Toyota Camry"
),
auto-implemented string
property State
(line 7) to store a two-character state abbreviation representing the state in which the policy is held (e.g., "MA"
for Massachusetts),
a constructor (lines 10–15) that initializes the class’s properties and
read-only property IsNoFaultState
(lines 18–37) to return a bool
value indicating whether the policy is held in a no-fault auto insurance state; note the property name—a common naming convention for a bool
property is to begin the name with "Is"
.
In property IsNoFaultState
, the switch
expression (line 25) is the string
returned by AutoPolicy
’s State
property. The switch
statement compares the switch
expression’s value with the case
labels (line 27) to determine whether the policy is held in Massachusetts, New Jersey, New York or Pennsylvania (the no-fault states). If there’s a match, then line 28 sets local variable noFaultState
to true
and the switch
statement terminates; otherwise, the default
case sets noFaultState
to false
(line 31). Then IsNoFaultState
’s get
accessor returns local variable noFaultState
’s value.
For simplicity, we do not validate an AutoPolicy
’s properties, and we assume that state abbreviations are always two uppercase letters. In addition, a real AutoPolicy
class would likely contain many other properties and methods for data such as the account holder’s name, address, birth date, etc. In Exercise 6.28, you’ll be asked to enhance class AutoPolicy
by validating its state abbreviation using techniques that you’ll learn in Section 6.11.
AutoPolicyTest
Class AutoPolicyTest
(Fig. 6.12) creates two AutoPolicy
objects (lines 10–11 in Main
). Lines 14–15 pass each object to static
method policyInNoFaultState
(lines 20–28), which uses AutoPolicy
methods to determine and display whether the object it receives represents a policy in a no-fault auto insurance state.