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
Nirav MNirav M 

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.  
Nirav MNirav M
Hmm I did not get any answer. May be i did not ask the question correctly.
I just want to know what is wrong with it. Why it is not assigning correct value to errMessage variable.
Footprints on the MoonFootprints on the Moon
Hi Nirav,
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 -
public String errMessage { get; set; }

Let me know if this helps!