You need to sign in to do that
Don't have an account?

Understanding setter and action methods
Following is my Apex class:
public class Calculator {
public Decimal Operand1 {get;set;}
public Decimal Operand2 {get;set;}
public Decimal Result {get;set;}
public String errMessage {
get { return errMessage;}
set { errMessage='No Error';
system.debug('in setter errMessage: '+ errMessage);}
}
public Void Addition (){
Result=Operand1+Operand2;
//errMessage=null;
}
public Void Substraction (){
Result=Operand1-Operand2;
//errMessage=null;
}
public Void Multiplication (){
Result=Operand1*Operand2;
//errMessage=null;
}
public Void Division (){
if (Operand2 != 0 ){
Result=Operand1/Operand2;
//errMessage=null;
}
else
{
Result=Null;
errMessage= ' Operand can not be Zero';
system.debug('in Action method errMessage: '+ errMessage);
}
}
}
And Following is from Anonymous block to run the above class.
---------------------------------------------------------------
Calculator Calc = new Calculator();
Calc.Operand1=5;
Calc.Operand2=0;
Calc.Division();
system.debug('Final Result: ' + Calc.Result);
system.debug('Final errMessage: ' + Calc.errMessage);
--------------------------------------------------------
Why I don't see the error message "Operand can not be Zero" when i run the above.
public class Calculator {
public Decimal Operand1 {get;set;}
public Decimal Operand2 {get;set;}
public Decimal Result {get;set;}
public String errMessage {
get { return errMessage;}
set { errMessage='No Error';
system.debug('in setter errMessage: '+ errMessage);}
}
public Void Addition (){
Result=Operand1+Operand2;
//errMessage=null;
}
public Void Substraction (){
Result=Operand1-Operand2;
//errMessage=null;
}
public Void Multiplication (){
Result=Operand1*Operand2;
//errMessage=null;
}
public Void Division (){
if (Operand2 != 0 ){
Result=Operand1/Operand2;
//errMessage=null;
}
else
{
Result=Null;
errMessage= ' Operand can not be Zero';
system.debug('in Action method errMessage: '+ errMessage);
}
}
}
And Following is from Anonymous block to run the above class.
---------------------------------------------------------------
Calculator Calc = new Calculator();
Calc.Operand1=5;
Calc.Operand2=0;
Calc.Division();
system.debug('Final Result: ' + Calc.Result);
system.debug('Final errMessage: ' + Calc.errMessage);
--------------------------------------------------------
Why I don't see the error message "Operand can not be Zero" when i run the above.
I just want to know what is wrong with it. Why it is not assigning correct value to errMessage variable.
Got your point.
The error is being displayed as "No Error", because at line errMessage= 'Operand can not be Zero'; you are setting some value to errMessage,
which will eventually direct towards setter method. Inside setter, you are overriding 'Operand can not be Zero' this value with 'No Error'.
To have proper error message simple change errMessage declaration to -
Let me know if this helps!