Best Practices : Page Reference method return null

I read about Page Reference, and the documentation states the usage of Page Reference:

  • To view or set query string parameters and values for a page

  • To navigate the user to a different page as the result of an action method

But when I go through some code examples it seems like developers code it like this:

  public PageReference retrievePlan(){

     //logic bla bla
     return null;

Why does this code use PageReference as a return type while it only returns null? Can we just use public void retrievePlan instead of PageReference and returning null? Does doing this have any significance?


There seem to be two cases where developers use this pattern. The first case is the developer learns about action methods for the first time, and is led to believe they must use a PageReference return type for the function to work, since nearly all tutorials seem to do this. The second case is where a developer does this because they want to have the return type already set “just in case they need it later.”

The truth is, this is a bad practice, and should be avoided. First, many developers come to rely on the method’s return type to quickly figure out what the method’s output will be. Seeing a return type of PageReference will trick developers into thinking a possible redirect could occur. This later gets codified into test methods, and so becomes reinforced.

It might not seem like a big deal when there are only five lines of code, but if a method contains two hundred lines of code, it becomes difficult to diagnose when something needs to be fixed. Or, a later developer might break something, assuming the return type is intentional, and changes the null to some PageReference.

There is no valid use for this anti-pattern, and you should never return a value when the result is always null. This also applies to other types of methods; never return a type if you only intend to return null.

Source : Link , Question Author : unidha , Answer Author : sfdcfox

Leave a Comment