开发者

How can I avoid passing variables through multiple functions?

While doing GUI programming (in Perl), I often have the case where I have a main package/function x that calls a package/function y, which in turn calls package/function z. But, when I have a variable in x (e.g. a reference to a widget) that I need to access in z, I have to开发者_如何学JAVA then pass it through y because I don't want to use globals.

Is there a better way to do this? As my program gets bigger, I seem to have more and more variables being passed through packages/functions just so that I can access them in sub packages/functions.


You seem to think this is a bug. It's a feature! It means that if you come back to the program in months or years, you know how and where your data is being used.

Keep in mind that it is not in general empty information to pass a variable a through y to get to z. The reason is that y might instead generate its own version of a; from looking at x or z alone you wouldn't be able to tell with global variables. If you pass it through y, at least you know that y starts out with something generated by x.

Keep in mind that you also might find that you need to refactor your code:

x produces a
x calls y with a
  y produces b
  y calls z with a and b

could be changed to

x produces a
x calls y
  y produces and returns b
x calls z with a and b

in some cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜