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
bozotheclownbozotheclown 

Simple Way to Repeat Pieces of Code?

Hello.  I have a quick question.

 

I have three buttons which utilize a few exact lines of code.  For this example, let's say two lines of code (although in reality, it is much more).

 

Is there a way in Apex for me to only list those lines of code once...and for each pagereference to go to those shared lines somewhere?

 

The reason for asking this is that I likely will revise the shared code...and ideally would like to only have to edit it once.

 

Thanks in advance.

 

public PageReference button1() {
// unique code here for button1
// insert identical code lines 1 and 2
return Page.AAA;
}


public PageReference button2() {
// unique code here for button2
// insert identical code lines 1 and 2
return Page.BBB;
}


public PageReference button3() {
// unique code here for button3
// insert identical code lines 1 and 2
return Page.CCC;
}



// identical code used across the three buttons - I ideally would only like to type these three lines
// just one time since I might edit it at a later date (so it would be simpler to only edit the code once)
IntegerA = IntegerB+IntegerC;  // Identical code line #1
IntegerZ = IntegerA+IntegerD;  // Identical code line #2

 

Kiran  KurellaKiran Kurella

You can simply create a seperate function for the common code.

 

public void commonCode() {   // be sure to change the function name as per the functionality.

  // insert identical code lines 1 and 2

IntegerA = IntegerB+IntegerC; // Identical code line #1
IntegerZ = IntegerA+IntegerD; // Identical code line #2

 

}

 

public PageReference button1() {
// unique code here for button1
commonCode();
return Page.AAA;
}


public PageReference button2() {
// unique code here for button2
commonCode();
return Page.BBB;
}

 

public PageReference button3() {
// unique code here for button3
commonCode();
return Page.CCC;
}

 

 

bozotheclownbozotheclown

Thanks.  Much appreciated.