开发者

How to access declared script fields from within classes in Groovy?

Let's say I have the next groovy code snippet:

def weightArg = args[0]

class Box {

   def width

   def height  

   def double weight() {
       //I want to return the value of weightArg here. How can I do that? 
   }
}

I want to let my class Box开发者_开发百科 use some variables from its environment. What's the correct way to do it?

It seems that weightArg should be static and I should be able to get it from Box static initializer, but I cannot manage to overcome the compiler.


Regardless of whether it's "right" to do so or not, the way that you can access your weight variable from within the Box class is to simply remove the word "def". The reason why is described here.


Declaring a class in a middle of a script and making it dependent on scripts local variables is a definite sign of a bad design. If you can't design this whole system in OO way than stick to procedural programming. The main purpose of writing OO programs is factoring them to little independent pieces. In your case it's neither factoring, nor independent, and I'm pretty sure it has no purpose you could express in words.

In other words either don't declare a Box type at all or do it similar to this way:

class Box {
  Box(weight) { this.weight = weight }
  def width, height, weight
}

And use it like this:

def box = new Box(args[0])

Thus you get it abstracted from weightArg and args[0] and also become able to reuse it in different scenarios.

Otherwise you foredoom your program to be unmanageable and therefore dead after first revision. In decades of existence of OO programming it's been pretty much proven.

Another thing to note is that when you get a feeling that you need to introduce classes in your script it is a reliable sign that your program should be written as a normal application with packages and stuff - not as a script.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜