闭幕:他们为什么这么有用?(Closures: why are they so useful?)
作为OO开发者,也许我很难看到它的价值。 他们给了什么附加值? 他们适合在OO世界吗?
As an OO developer, maybe I have difficulty seeing its value. What added value do they give? Do they fit in an OO world?
最满意答案
关闭不给你任何额外的权力。
任何你可以实现与他们,你可以实现没有他们。
但是它们非常有用,可以使代码更清晰可读。 而且我们都知道清洁可读的短代码是一个易于调试并且包含较少错误的代码。
让我给你简短的可能用法的Java示例:
button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Pressed"); } });将被替换(如果Java有闭包):
button.addActionListener( { System.out.println("Pressed"); } );Closures don't give you any extra power.
Anything you can achieve with them you can achieve without them.
But they are very usable for making code more clear and readable. And as we all know clean readable short code is a code that is easier to debug and contains fewer bugs.
Let me give you short Java example of possible usage:
button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Pressed"); } });Would be replaced (if Java had closures) with:
button.addActionListener( { System.out.println("Pressed"); } );更多推荐
发布评论