“폐쇄는 가난한 사람의 물건이고 그 반대의 경우도 마찬가지입니다.”-이것은 무엇을 의미합니까?
폐쇄는 가난한 사람의 물건이며 그 반대의 경우도 마찬가지입니다.
나는이 진술 을 웹의 많은 곳 ( SO 포함 )에서 보았지만 그것이 무엇을 의미하는지 잘 이해하지 못한다. 누군가 그것이 정확히 무엇을 의미하는지 설명해 주시겠습니까?
가능한 경우 답변에 예를 포함하십시오.
개체는 가난한 사람의 폐쇄입니다.
Java를 고려하십시오. Java는 실제 어휘 폐쇄에 대한 언어 수준 지원이없는 객체 지향 프로그래밍 언어입니다. 해결 방법으로 Java 프로그래머는 어휘 범위에서 사용할 수있는 변수를 닫을 수있는 익명 내부 클래스를 사용합니다 (인 경우 final). 이런 의미에서 물건은 가난한 사람의 폐쇄입니다.
폐쇄는 가난한 사람의 물건입니다.
Haskell을 고려하십시오. Haskell은 실제 객체에 대한 언어 수준 지원이없는 기능적 언어입니다. 그러나 Oleg Kiselyov와 Ralf Lammel 의이 우수한 논문에 설명 된대로 클로저를 사용하여 모델링 할 수 있습니다 . 이런 의미에서 폐쇄는 가난한 사람의 물건입니다.
OO 배경에서왔다면 사물에 대한 생각이 더 자연 스럽기 때문에 클로저보다 더 근본적인 개념으로 생각할 수 있습니다. FP 배경에서 온 경우 클로저 측면에서 더 자연스럽게 생각할 수 있으므로 객체보다 더 근본적인 개념으로 생각할 수 있습니다.
이야기의 도덕은 클로저와 객체가 서로 표현할 수있는 아이디어이며 다른 것보다 더 근본적인 것은 없다는 것 입니다. 이것이 고려중인 성명서의 전부입니다.
철학에서는이를 모델 의존적 사실주의 라고합니다 .
요점은 클로저와 객체가 동일한 목표를 달성한다는 것입니다. 데이터 및 / 또는 기능을 단일 논리 단위로 캡슐화하는 것입니다.
예를 들어 다음과 같이 개를 나타내는 Python 클래스를 만들 수 있습니다.
class Dog(object):
def __init__(self):
self.breed = "Beagle"
self.height = 12
self.weight = 15
self.age = 1
def feed(self, amount):
self.weight += amount / 5.0
def grow(self):
self.weight += 2
self.height += .25
def bark(self):
print "Bark!"
그런 다음 클래스를 객체로 인스턴스화합니다.
>>> Shaggy = Dog()
Shaggy 객체에는 데이터와 기능이 내장되어 있습니다. 내가를 호출 Shaggy.feed(5)하면 그는 파운드를 얻습니다. 그 파운드는 개체의 속성으로 저장된 변수에 저장되며, 이는 개체 내부 범위에 있음을 의미합니다.
Javascript를 코딩하는 경우 비슷한 작업을 수행합니다.
var Shaggy = function() {
var breed = "Beagle";
var height = 12;
var weight = 15;
var age = 1;
return {
feed : function(){
weight += amount / 5.0;
},
grow : function(){
weight += 2;
height += .25;
},
bark : function(){
window.alert("Bark!");
},
stats : function(){
window.alert(breed "," height "," weight "," age);
}
}
}();
여기에서는 개체 내에 범위를 만드는 대신 함수 내에 범위를 만든 다음 해당 함수를 호출했습니다. 이 함수는 일부 함수로 구성된 JavaScript 객체를 반환합니다. 이러한 함수는 로컬 범위에 할당 된 데이터에 액세스하기 때문에 메모리가 회수되지 않으므로 클로저에서 제공하는 인터페이스를 통해 계속 사용할 수 있습니다.
가장 단순한 객체는 그 상태에서 작동하는 상태와 함수의 모음 일뿐입니다. 클로저는 또한 상태의 모음이며 해당 상태에서 작동하는 함수입니다.
Let's say I call a function that takes a callback. In this callback, I need to operate on some state known before the function call. I can create an object that embodies this state ("fields") and contains a member function ("method") that performs as the callback. Or, I could take the quick and easy ("poor man's") route and create a closure.
As an object:
class CallbackState{
object state;
public CallbackState(object state){this.state = state;}
public void Callback(){
// do something with state
}
}
void Foo(){
object state = GenerateState();
CallbackState callback = new CallbackState(state);
PerformOperation(callback.Callback);
}
This is pseudo-C#, but is similar in concept to other OO languages. As you can see, there's a fair amount of boilerplate involved with the callback class to manage the state. This would be much simpler using a closure:
void Foo(){
object state = GenerateState();
PerformOperation(()=>{/*do something with state*/});
}
This is a lambda (again, in C# syntax, but the concept is similar in other languages that support closures) that gives us all the capabilities of the class, without having to write, use, and maintain a separate class.
You'll also hear the corollary: "objects are a poor man's closure". If I can't or won't take advantage of closures, then I am forced to do their work using objects, as in my first example. Although objects provide more functionality, closures are often a better choice where a closure will work, for the reasons already stated.
Hence, a poor man without objects can often get the job done with closures, and a poor man without closures can get the job done using objects. A rich man has both and uses the right one for each job.
EDITED: The title of the question does not include "vice versa" so I'll try not to assume the asker's intent.
The two common camps are functional vs imperative languages. Both are tools that can accomplish similar tasks in different ways with different sets of concerns.
Closures are poor man's objects.
Objects are poor man's closures.
Individually, each statement usually means the author has a some bias, one way or another, usually rooted in their comfort with one language or class of language vs discomfort with another. If not bias, they may be constrained with one environment or the other. The authors I read that say this sort of thing are usually the zealot, purist or language religious types. I avoid the language religious types if possible.
Closures are poor man's objects. Objects are poor man's closures.
The author of that is a "pragmatist" and also pretty clever. It means the author appreciates both points of view and appreciates they are conceptually one and the same. This is my sort of fellow.
Just so much sugar, as closures hide anonymous objects under their skirts.
"Objects are a poor man's closures" isn't just a statement of some theoretical equivalence — it's a common Java idiom. It's very common to use anonymous classes to wrap up a function that captures the current state. Here's how it's used:
public void foo() {
final String message = "Hey ma, I'm closed over!";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println(message);
}
});
}
This even looks a lot like the equivalent code using a closure in another language. For example, using Objective-C blocks (since Objective-C is reasonably similar to Java):
void foo() {
NSString *message = @"Hey ma, I'm closed over!";
[[NSOperationQueue currentQueue] addOperationWithBlock:^{
printf("%s\n", [message UTF8String]);
}];
}
The only real difference is that the functionality is wrapped in the new Runnable() anonymous class instance in the Java version.
'Program Club' 카테고리의 다른 글
| 현재 Magento 사용자입니까? (0) | 2020.12.14 |
|---|---|
| UIImageView에서 이미지 제거 (0) | 2020.12.14 |
| 터미널을 사용하여 파일 이름을 일괄 적으로 변경하려면 어떻게해야합니까? (0) | 2020.12.14 |
| Javascript / jQuery : 낙타 문자 문자열을 분할하고 공백 대신 하이픈 추가 (0) | 2020.12.14 |
| setOnCancelListener 및 setOnDismissListener는 뒤로 버튼을 누르거나 외부를 터치하는 경우 AlertDialog에 대해 호출되지 않습니다. (0) | 2020.12.14 |