2

Should you design a method where it's params are static variables? In the example below, the calc method is pretty reusable, but it seems wierd to pass in static variables....

Setup

In class A, i have a static variable num and a static method genBalance. In my utility class B, i have a static method that does some calculations and uses the varialbe. Id does not modify it.

public class A{
    public static Integer num;

    static{
    num = 0;
    } 

    public static String genBalance(){
        return 'You have a balance of : ' + B.calc(num);
    }

}

public Class B{
    public static Integer calc(integer a){
        return a*10;
    }
}
2
  • Should this line be "return 'You have a balance of : ' + B.calc(num);" instead of "return 'You have a balance of : ' + calc(num);" Aug 7, 2016 at 19:38
  • thx, fixed that Aug 7, 2016 at 19:47

2 Answers 2

1

You certainly can. Usually, this is because the method being called is in a utility class, where the method itself is used in a number of places, and the static member is a constant (static final). It's certainly unusual, and I'd argue that it's rarely the best design, especially given the CPU cost of static final members, but there's nothing wrong with it if you need to.

2
  • Could you help me with a better design? Aug 7, 2016 at 21:24
  • @user11235813 It really depends on the use case. It might be a local variable, a class variable, a custom label, or something else. I don't think that there's a "one size fits all" solution.
    – sfdcfox
    Aug 8, 2016 at 0:37
0

This link explains the use of static variable/methods compared to other types of variables/methods. Hope this explains why they have to be used. I have used this as a reference in my coding. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_static.htm

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .