You need to sign in to do that
Don't have an account?
bozotheclown
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
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;
}
Thanks. Much appreciated.