Constants
Not Started

Sometimes, an Apex variable needs to retain its original value and never be allowed to change. Imagine a scenario where you have a baseDiscount variable that's used to calculate a total amount. The business states that the baseDiscount should never be allowed to change.

As the original developers, we know that - but how can we make it clear to whoever reads the code later? Relying on a comment like this would just be silly:

// WARNING!!! DO NOT REASSIGN baseDiscount, THE CALCULATION WILL BE WRONG Integer baseDiscount = 10;

Instead of relying on comments, let's be more explicit with our code. We can tell the Apex compiler to prevent baseDiscount from ever changing its value.

To do that, we'll use the final keyword, which prevents the variable from ever being reassigned after it's initialized. The code rewritten would look like this:

final Integer BASE_DISCOUNT = 10;

Some folks call these constant variables others call them final variables.

Since Apex is case insensitive, it's not required, but it is considered a proper styling convention to use UPPER_SNAKE_CASE when declaring constants. Every letter is capitalized and every word is separated by an underscore.

Suppose we reassign a constant variable later in the code. In that case, we’d face this compilation error: Final members can only be assigned in their declaration, init blocks, or constructors. Even though it's an error, it's great because it guarantees that the variable will never be reassigned. Here is an example of code that would result in a compilation error:

final Integer MAXIMUM_DISCOUNT = 60; //this is fine MAXIMUM_DISCOUNT = 50; //NOT ALLOWED! Results in a compile-time error.

We can do this with any of the datatypes we've learned. In the example below, a constant string will initialize the final error message:

final String DEFAULT_ERROR_MESSAGE = 'An unknown error has occurred. Reach out to your Salesforce Admin'; String finalErrorMessage = DEFAULT_ERROR_MESSAGE; // setting a default value until we figure out what specifically went wrong // imagine there is logic here to figure out what went wrong. finalErrorMessage = 'Could not calculate because ....'; // replacing with a more specific error message

We can assign the constant DEFAULT_ERROR_MESSAGE to a non-constant like finalErrorMessage. We can still reassign finalErrorMessage, but we can't ever reassign the constant DEFAULT_ERROR_MESSAGE.

Challenge

Create a String called STAGE_CLOSED_WON and assign it to the value Closed - Won.