How to read Page Parameters quickly | Apex quick tips and tweaks with best practices

by - 10:13 PM

Apex Coding Good Practices 

Reading variable from url and retrieving values for parameters is most common practice we do in web development. Like for example, if you want to read the current value of page parameter q from url as shown below

You can read url by invoking implicit methods called
ApexPages.currentPage().getParameters().get('q'); like shown her

Let talk little more about this, lets add little more complexity with four (4) variables

Wonderful but can we improve this idea a little more ? Yes lets make this process little efficient by using some standard data-structures like Map. So if I can store all variable in map with <Key,Value> pair, I can get all information I need at one place and easily can retrieve those values at any time.

Good Idea, lets implements this approach here. You might be knowing that the Apex method  ApexPages.currentPage().getParameters. return a map of Map<string, string> type. This sound good, but how can I use this ?

Well, once I have this map, I can retrieve any value I want through this map, sound cool so let me a write a controller Apex class that read this url efficiently

Wonderful but can we improve this idea a little more ? Yes we can, we all awesome developers hate writing redundant code, so lets design a simple method that do that same job for us, so here I am adding new method called GetValueFromParam(string);

Wonderful but can we improve this idea a little more ? Yes we can, what if take this method into a static helper class in this way, for everytime we can skip writing this method for every class and rather just invoke this method of helper class. This clearly, promotes scalability, integrity (change one place affect all), less code meaning more beauty, wow sounds lucrative. Let me jump in designing a quick helper class

Here is a basic ApexHelper.cls Class with only one method

Let utilize this helper class in our controller and just look at  this, wooh looks beautiful  Bingo!

This is a good example explaining how to write maintainable code using good engineering design practices so as to make your code more modular, maintainable and scalable in a beautiful fashion. I hope this demo help you learning some efficient practices of writing organized code

You May Also Like