function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhishek KedariAbhishek Kedari 

How to declare and use constants in apex coding

Hi All,

    I have many apex classed and everhwere I have some values store in different variables. Now depending upon the value contained by that variable, I want to get some other value from Constant declared file (in short Mapping). How I can do that.  I tried this with few ways -

1) declare Constants.cls but problem with this apprach is - suppose variable 'x' contains value 'a' which i want to replace with 'A' from Constants file,  I can't use Constants.x to get the value A, I need to use Constants.a .  Is there any solution to this. (I really dont want to check string everytime with some constant value)

2) using Maps, but I dont know how I can use Maps (key,value) to declare constant values. Because I want this data as static and dont want to use new operator to create new Map everytime.  I would prefer this apprach if anyone helps mw to find out how to use this approach.

Please let me now if I am not clear.

I would recormmend to use Enums instead of Constant class. Enums have flexibiliy which you need.

To answer part of your question: 
If I understand the requirement correctly, you wsh to have variables which can be used in code and there value can be changed without disturbigb the code:
custom settings might be the answer for you:

Decalring constant value totally depent on your requirment.

1) If you want to decalare some value and want to use in your code, and you also want the you can change the value according to you your need. Then you should need to go with Custom setting. It is a best option.
For example : You have written a code to send email and you want you want to send this email a specific user then you can maintain the email of that user in custome setting and in future you can change the email id. In production we can't change the apex code but we can update the value of custom setting.

2) Second case : We know that some value are fixed no body can change in future for exmaple  status of any success API is 200, So you can create a constant class in which you can maintiain many status by intilize in static property so, when you hit any api then you can check the status with your constant, We declare in class becuse many api never change it's status code you user don't need to update and we can put in our class.