In Objective-C when you have
[A something]
A is referred to as the 'receiver'. I am wondering what the equivalent term is in other object-orientated languages, particularly method calling ones as opposed to message passing ones.
Caller/Callee refers to the actual methods themselves I think, not the object. Also I'm not sure about 'instance' as in the language I'm working with, Vala, you can actually call methods on structs and namespaces, which you wouldn't classify as objects or instances.
What are people's thoughts?
I think the most common term is just "the object". In Python it is traditionally called self.
It's method-invoking rather than message-passing, so another common term, particularly among Perl hackers, is invocant.
When you call a method, you do so with an invocant. When you call new() on Cat, the name of the class, Cat, is new()'s invocant. [...] When you call a method on an object, that object is the invocant.
-- chromatic, Modern Perl
Related
The book I am reading just introduced the concepts of subsumption, covariance, contravariance and its implications for the design of programming languages. Now, in the section about method specialization, I'm getting into trouble.
The book points out that, when we override methods in subclasses, parameter types may be generalized, and result types may be specialized. However, the book argues, that for methods that aren't overridden but inherited, another type of method specialization is at play where parameter types are specialized, and result types are generalized, because we can interpret the self keyword as an argument:
"There is another form of method specialization that happens implicitly by inheritance. The occurrences of self in the methods of C can be considered of type C, in the sense that all objects bound to self have type C or a subtype of C. When the methods of C are inherited by C', the same occurrences of self can similarly be considered of type C'. Thus the type of self is silently specialized on inheritance (covariantly!)."
And here is my problem: Can't we consider the self keyword a covariant argument in overridden methods as well? Then we would end up with the this keyword as a covariant argument, even though we just established that, as a consequence of the substitution principle, arguments of overridden methods need to be contravariant. Am I overlooking something?
Thanks for your help!
Implementation of variance in programming languages
...when we override methods in subclasses, parameter types may be generalized (covariance), and result types may be specialized (contravariance)
Even though this can be true, it depends on the specific language, whether it actually implements this functionality. I have found examples on wiki:
C++ and Java implement only covariant return types and the method
argument types are invariant.
C# does not implement either variancy (so both are invariant).
There is an example of a language (Sather) with contravariant argument type and covariant return type - this is what you mentioned.
However, there is also one (Eiffel) with covariant return & argument type, but this can normally cause runtime errors.
Controlling and "left-over" arguments
There is also a nice paragraph dividing arguments between controlling arguments and "left-over" arguments. The controlling ones are covariant and the non-controlling ones are contravariant. This is regarding multiple dispatch langauges, although most certainly you were referring to a single dispatch language. But even there is a single controlling argument (self/this).
Here is the paragraph (I did not have time to study the paper it is referring to, please feel free to read it if you have the time and post your findings):
Giuseppe Castagna[3] observed that in a typed language with multiple dispatch, a generic function can have some arguments which control dispatch and some "left-over" arguments which do not. Because the method selection rule chooses the most specific applicable method, if a method overrides another method, then the overriding method will have more specific types for the controlling arguments. On the other hand, to ensure type safety the language still must require the left-over arguments to be at least as general. Using the previous terminology, types used for runtime method selection are covariant while types not used for runtime method selection of the method are contravariant.
Conventional single-dispatch languages like Java also obey this rule: there only one argument is used for method selection (the receiver object, passed along to a method as the hidden argument this), and indeed the type of this is more specialized inside overriding methods than in the superclass.
The problem
According to the paragraph I assume that the self argument in its nature is not a regular method argument (which may be contravariant), because self is an another kind of argument - controlling argument - which are covariant.
...even though we just established that, as a consequence of the substitution principle, arguments of overridden methods need to be contravariant.
Well, it looks like not all of them.
Is there any way to get all methods defined for object and check if object responds to specified method?
Looking for something like Ruby's "foo".methods
(list-methods *myobj*) ;; -> (method0 method1 methodN)
And also something like ruby's "foo".respond_to? :method
(has-method-p *myobj* 'foo-method) ;; -> T
For slots there is slot-exists-p, what's for methods?
Thanks.
You can use the MOP function SPECIALIZER-DIRECT-GENERIC-FUNCTIONS to find all the generic functions that contain a method that specializes specifically on a class, which is close to what you are asking for in Ruby. You can actually find all the generic functions that specialize on a class or any of its superclasses with (for SBCL; for other implementations check out closer-mop or the implementation's mop package):
(defun find-all-gfs (class-name)
(remove-duplicates
(mapcan (lambda (class)
(copy-list (sb-mop:specializer-direct-generic-functions class)))
(sb-mop:compute-class-precedence-list (find-class class-name)))))
The problem with this function is that many built-in generic functions specialize on the universal supertype T, so in SBCL you get a list of 605 generic functions which might not be all that interesting. However, you can build some interesting tools with this general approach e.g., by filtering the list of superclasses or generic functions based on package.
Common Lisp object model is based on the notion of a generic function, so methods are attached to GFs, not to ordinary objects, see generic-function-methods (it is in MOP, not ANSI CL, so you need to find the package it lives in using apropos or find-all-symbols).
The Common Lisp Object System has a very powerful MetaObject Protocol.
You can use it to view (and often modify!) a lot of internal information about your objects and functions.
I have identified an area in an application I am developing where the factory method pattern seems appropriate. I am reasonably familiar with this pattern in other languages (C#, Java), but I was reading the book "Cocoa Design Patterns" and it contains a chapter on Dynamic Creation, which shows how to use the NSClassFromString() method. Of this function, it says:
This single function effectively reduces the well-known Factory Method pattern to a single line of code in many cases.
I am wondering whether I should use this dynamic creation method instead of a typical factory method pattern? Does the dynamic creation method win over the normal method every time, or are there occasions where one is more suitable than the other?
Right now, I am leaning towards using a regular factory method pattern, but I was wondering what others think?
Regards,
Nick
The claim in the book is a little strong, I'd say.
You should use NSClassFromString in two circumstances:
You're reading the class name as a string at runtime. Obviously if you get the class name as a string, you have to convert it to a class object somehow, and NSClassFromString is one way to do that. You should probably be testing the string (or the returned class object) against a whitelist of allowable classes, if you don't trust the source of the string.
You're weak-linking a framework and using an SDK/platform that doesn't support the NS_CLASS_AVAILABLE feature. Check out the SDK Compatibility Guide for more information about this.
In any other circumstance, it's probably better to get the class object using an expression like [MyClass class]. That way, you'll get an error at compile-time if the class doesn't exist (for example because you misspelled the class name).
There are quite a few dynamically typed object oriented languages in which a class itself is an object. Smalltalk, and Python for example. Is there any statically typed language in which a class is an object?
EDIT:
By the term "object", I mean a first class entity. For example, classes in Python can be passed to other methods, can be returned from methods etc.
In a lot of statically typed languages, like JAVA, a class is an object with its own methods.
For example, in Java, the object that represents the "String" class is accessible as "String.class" and then you can invoke methods on this class as "String.class.getFields()", "getMethods()", getConstructor()", "cast(obj)", etc. You can see in the API documentation all the methods of the "Class" class.
Nevertheless, given that the language is statically typed, you cannot dynamically modify a class.
In other words, you are not going to find a method called "class.addField()" in the Class class. The more you can do is "extend" the class (if it is not final) by inheritance.
In yet other words, the a "Class" object is read-only.
By the term "object", I mean a first class entity. For example, classes in Python can be passed to other methods, can be returned from methods etc.
As any other object, you can pass them to methods and return them from methods (they are just regular objects, but that expose only "read" methods). Example (I omit generics for clearness):
public Class myMethod(Class someClassObject) {
System.out.println(someClassObject.getCanonicalName());
Class anotherClass = String.class;
return anotherClass ;
}
I don't fully agree with #edutesoy answer.
First-class means that an implicit constructs is reified as an explicit construct that can be passed around like any object. Classes in Java are not "first-class", they are mirrors where you can inspect some properties but are not the the object itself.
That you can not change the structure of the class at run-time is fine, e.g. add fields, change method body or signature, and that under this perspective it's partly "read-only" is ok.
But let's consider static fields. I guess everybody agrees that unless final static fields are mutable, just like instance fields. In Smalltalk, these are just fields defined on the class itself, rather than on instances of the class. Also, in Smalltalk, class-side methods are polymorphic just like any other method, and :
aClass field: aValue.
might resolve differently depending on the class that is passed. This is not possible in Java ; a static field or method must be referenced via its type. This also means that it does not allow overriding static methods (read the link for more details) as would be the case if they were truely first class.
The fact that reflection is possible in Java doesn't make classes "first-class"--you can only pass a representation of the class around. And to come back to the original question: I don't know of any statically typed language with first-class classes (but my knowledge is limited, maybe one exists).
EDIT
Actually, now I remember it exists StrongTalk (http://www.strongtalk.org/) which is Smalltalk with static typing. The typing issues are discussed in this paper: Strongtalk: Typechecking Smalltalk in a Production Environment
From Oleg Kiselyov and Ralph Lammel's "Haskell's overlooked object system" (emphasis mine),
Not only OOHaskell provides the conventional OO idioms; we have also
language-engineered several features that are either bleeding-edge or unattainable
in mainstream OO languages: for example, first-class classes and class closures; statically type-checked collection classes with bounded polymorphism of implicit collection arguments; multiple inheritance with user-controlled sharing; safe co-variant
argument subtyping.
Well, the benefits of that are reduced in an early-bound language. However, Java reflection objects for classes would basically be what you are asking for.
Why, incidentally, do you want this? Is it more than idle curiousity?
Take a look at the concept of homoiconicity which refers to the extant that a language can refer to its own structures. Also take a look at this post by Eric Lippert.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I wonder if can I say that a constructor is a special case of a method?
You can say anything. Whether anyone will disagree with you depends on the context. Some language communities and standards define things that way.
More elaborately, it depends on what you mean by a 'method.' In C++, for example, one way to analyze the creation process is to say that it consists of a call to an operator new (perhaps just placement) followed by a call to a constructor method. From an implementation standpoint, a constructor looks, walks, and quacks like a method. In some compilers, you can even invoke one explicitly.
From a more theoretical viewpoint, someone might claim that constructors are some distinctive species. However, there is no single, true, privileged conceptual model of methods, constructors, or purple unicorns.
Gosh this is all subjective.
You could say so, just as you can say that a human is a special case of animal, however in most contexts mentioning animals implies non-human animals and mentioning methods implies non-constructor methods.
Technically, a constructor usually is a method. Whether it really is or is not depends largely on the particular environment. For example, in .NET constructors are methods called actually after an object is created. However, it's also possible to create an object without having a constructor called right after.
Update: Regarding .NET, or the Common Language Infrastructure to be more precise, ECMA 335, section 8.9.6.6 Constructors states:
New values of an object type are created via constructors. Constructors shall be instance methods, defined via a special form of method contract, which defines the method contract as a constructor for a particular object type.
I think a constructor is too special to be called a method
It doesn't return anything
It modifies the object before the object is initialized
It cannot call itself (imagine that)
blah blah blah
There might be difference between languages, but I don't think I'm going as far as calling a constructor "special method".
In languages that have constructors, you can usually think of a constructor as a special case of a factory method. (Note: I don't mean the GoF Factory Method Software Design Pattern, I'm just talking about any class method that creates new instances.) Usually, this "special casing" generally takes the form of annoying restrictions (e.g. in Java, you can only call the parent constructor at the beginning of the constructor), which is why even in languages that do have constructors, you often end up using or writing factory methods anyway.
So, if constructors are basically factory methods with restrictions, there is really no need to have them both, and thus many languages simply get rid of constructors. Examples include Objective-C, Ruby, Smalltalk, Self, Newspeak, ECMAScript/JavaScript, Io, Ioke, Seph and many others.
In Ruby, the closest thing to a constructor is the method Class#allocate, which simply allocates an empty object and sets that object's class pointer. Nothing more. Since such an empty object is obviously unusable, it needs to initialized. Per convention, this initialization is performed by #initialize. As a convenience, because it is cumbersome to always have to remember to both allocate and initialize (as any Objective-C developer can probably attest), there is a helper method called Class#new, which looks something like this:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
return obj
end
end
This allows you to replace this:
foo = Foo.allocate
foo.initialize(bar)
With this:
foo = Foo.new(bar)
It is important to note that there is nothing special about any of these methods. Well, with one exception: Class#allocate obviously has to be able to set the class pointer and to allocate memory, which is something that is not possible in Ruby. So, this method has to somehow come from outside the system, which e.g. in MRI means that it is written in C, not Ruby. But that only concerns the implementation. There are no special dispatch rules, no special override rules. It's just a method like any other that can e.g. call super whereever, whenever and how often it wants and can return what it wants.
"Special" is the magic word here. There's absolutely nothing wrong with calling a constructor a special method, but what "special" implies can vary depending on the language.
In most cases, "special" means they can't return values or be called as a method without creating a new object. But there are always exceptions: a prime example is JavaScript, where a constructor is no different from a normal function, it can return its own values and it can be called either as a constructor or as a simple function.
At least in vb.net, constructors can have a non-standard control flow. If the first statement of a constructor is a call to New (of either the same type or a base type), the sequence of events will be: (1) perform the call; (2) initialize all the fields associated with the type; (3) finish handling the rest of the constructor. No normal method has that sort of control flow. This control flow makes it possible to do things like pass constructor parameters to field initializers of a derived type, if the base type is written to allow such.
#Tom Brito, personally I would agree with you that a constructor is a special case of method.
Also, see below:
A constructor in a class is a special type of subroutine called at the creation of an object.
... A constructor resembles an instance method, but it differs from a method in that it never has an explicit return-type...
Source:
Wikipedia
Also, you may read my comments on others' comment (woot4moo, phunehehe).