Inconsistencies in smalltalk - oop

I'm a new comer to Smalltalk, and learned it in Squeak. But I find many things confusing in Smalltalk. In Squeak, MetaClass and MetaClass class are each other's class mutually. If I want to create the object MetaClass I should send a message new to its class which is MetaClass class. But it must have already existed as an object in the first place to accept the message. So I must create the object MetaClass class first, which can only be done by sending a message new to the object MetaClass which has not been created yet. So it is a chicken-or-the-egg problem.
Of course I can create the objects in Squeak now, because the MetaClass and MetaClass class objects have already been created auto-magically when Squeak is opened. But I don't know how. Maybe they are created somehow rather by sending messages. But then it contradicts Smalltalk's spirits: everything happens by sending messages except a few points (variable declaration, assignments, returns and primitives).
Is there something wrong with the above reasoning? Thanks in advance.

Your question is twofold, lets answer them separately.
How do mutual dependent classes get created?
You are right, Metaclass and Metaclass class are a singularity in the parallel hierarchy of the Smalltalk classes and metaclasses. How are they created?
That depends on the Smalltalk you are using. For GNU Smalltalk I am unsure, but for the descendants of the original Smalltalk-80 (VisualWorks, VA aka VisualAge, SqueakPharo) the are created in a Bootstrap process that creates an initial image.
However, at least for Squeak, this bootstrap happened at least 15 years ago, if not more. Metaclass and its class may even be as old as 30 years.
Long story short, both classes are created outside the typical image processing and linked together manually.
But if the objects are years old, that leads to the question
What happens at Smalltalk’s startup?
Contrary to languages like Ruby or Python, which are object-oriented, too, Smalltalk does not need to create a basic object environment with things like Object on every startup. Why?
When Smalltalk saves and shuts down, it basically takes a snapshot of all its object and saves those live object to a file. When it starts up again, it just has to read the objects from the snapshot and “revive” them.
Hence, for Metaclass and Metaclass class, both objects are read from the snapshot and revived, and from this point on, they are fully functional; they don’t need to be manually created anymore.

The 'automagically created' process actually is called bootstrapping. This is how the chicken-and-egg problem gets solved. Once the system is bootstrapped, all the rest can be expressed in terms of the system itself. So, there is no contradiction with Smalltalk's philosophy that everything happens by sending messages because it only becomes a Smalltalk system once it's bootstrapped.

Metaclass class class = Metaclass is a classical academic example of strange loop. But if you inquire a bit, you could find many others in Smalltalk.
Object superclass is nil which is an instance of UndefinedObject which is a subclass of Object (longer chain via ProtoObject in Squeak Object superclass superclass class superclass = Object)
The methods of MethodDictionary are stored in an instance of MethodDictionary (MethodDictionary methodDictionary class = MethodDictionary).
The name of Symbol is an instance of Symbol (works with ByteSymbol in Squeak ByteSymbol name class = ByteSymbol).
The subclasses of ArrayedCollection are stored in an instance of Array which is a subclass of ArrayedCollection (Array superclass subclasses class = Array).
Smalltalk is a SystemDictionary which points to Smalltalk via the #Smalltalk key (This is less direct in Squeak, (Smalltalk globals at: #Smalltalk) = Smalltalk).
I let you continue the list by yourself.
Whatever the implementation, the ultimate question is whether or not you can devise a self-describing system like Smalltalk without these strange loops, and you may glimpse a not so positive answer if you follow the sublinks of http://en.wikipedia.org/wiki/Kurt_G%C3%B6del#The_Incompleteness_Theorem
Related to the the bootstrap problem encountered with such system, an efficient way is to clone oneself to change oneself, and this is particularly true in Smalltalk image when you want to change base classes that you are using for changing / describing classes.
Hence my previous and concise answer which was deleted by applying the letter of the rules (https://stackoverflow.com/help/deleted-answers) more than the spirit in my opinion:
And here is how it was resolved: http://en.wikipedia.org/wiki/Drawing_Hands
Last point, I would have preferred to read, Incredible Consistency of Smalltalk, but I'm definitely biased.

Related

Is class an object in object oriented language

Is class an object in object oriented language? How are Class methods accessed by just name of the class.method name? (internal working). Is this same as a object.method?
And If the Class is same as object (belong to object class which is super class of every thing in OO) and we instantiate it (make object of it), can we make instance of an instance of an class other than Object class.
(Mainly interested in the theoretical perspective even if practically not required ever)
Well, it depends on the language that you are using; in pure OO languages where everything is an object (e.g. Smalltalk) classes are no exception and are objects too. In other languages where classes are not considered as first class citizens they are just special language constructs or primitive types. From now on I'll use Smalltalk as a target language, due to its reflection support and homogeneous style.
How Class methods are accessed by just name of the class.method name?
(internal working). Is this same as as object.method?
Since classes are objects, they are in turn instances of a class (a metaclass). Thus, sending a message to the class is just sending a message to an object whose role is to represent how classes behave. There is a lot of literature out there, you can take a look for example here and here for some introduction.
And If the Class is same as object (belong to object class which is
super class of every thing in OO) and we instantiate it (make object
of it), can we make instance of an instance of an class other than
Object class.
I'm not sure I follow you here, but just for clarification it is not always the case that Object is the superclass of all the classes. The thing is that If you start following the relationships between classes and metaclasses, you may reach a sort of infinite loop. Different languages work this out in different ways and for example, in VisualWorks Smalltalk, Object is a subclass of nil. The thing is that nil is also an object (remember, everything is an object) and it actually represents "nothing". As you may expect, nil is an instance of a class (UndefinedObject) and it also implements some of the class protocol. As a result it can be used to represent a class form where nothing is inherited :).
Finally, I don't know if this answers your question, but yes, you can do many cool things with full reflective capabilities, like creating new classes on the fly or reshaping existing ones. I'll leave you here some documents that you may find interesting regarding this topic:
Metaclasses
Understanding Metaclasses
Debugging Objects
A class isn't an object, you can think of it as a 'blueprint' for an object. It describes the shape and behaviour of that object. Objects are instances of a class.
See here for more information.
Is class a object in object oriented language?
The notion of class is first and foremost theoretical. You can define a thing with "class" semantics even if your language does not support the formal notion of "class" (e.g. Javascript). A class is a template for an object, from which you create instances.
How Class methods are accessed by just name of the class.method name?
I'm not quite sure what you mean. Some languages support "static" or "class" methods, which are methods that are not invoked within the context of an instance of the class. So its not the same as "object.method" which is a normal method on the class where the 'this' (or equivalent) will be the instance on which the method is invoked.
Java (from comments)
For Java, there is a class called Object, and a class called Class. See this. These Java constructs are separate from the notion of Class and Object. The former are implementation details -- they are how the designers constructed the language, the latter are general concepts. So in Java, you can have an instance of an Object, where the instance is an object(the concept) of type Object(the Java construct).
A Basic notion of object means that has been allocated some memory. As devdigital said class is just a blueprint for an object which holds the bare-bone structure and determines how the object will behave when it's it will be instantiated.
Classes are just bodies(without soul) and objects are living bodies(having a soul) that interact with environment or in biological terms respond to external stimuli(public methods and properties) in an analogy to philosophy of life :)
Technically classes are just machine interpretable code residing in memory(not necessary main memory or registers). Objects are code loaded into executable memory(registers/main memory)

can overriding of a method be prevented by downcasting to a superclass?

I'm trying to understand whether the answer to the following question is the same in all major OOP languages; and if not, then how do those languages differ.
Suppose I have class A that defines methods act and jump; method act calls method jump. A's subclass B overrides method jump (i.e., the appropriate syntax is used to ensure that whenever jump is called, the implementation in class B is used).
I have object b of class B. I want it to behave exactly as if it was of class A. In other words, I want the jump to be performed using the implementation in A. What are my options in different languages?
For example, can I achieve this with some form of downcasting? Or perhaps by creating a proxy object that knows which methods to call?
I would want to avoid creating a brand new object of class A and carefully setting up the sharing of internal state between a and b because that's obviously not future-proof, and complicated. I would also want to avoid copying the state of b into a brand new object of class A because there might be a lot of data to copy.
UPDATE
I asked this question specifically about Python, but it seems this is impossible to achieve in Python and technically it can be done... kinda..
It appears that apart from technical feasibility, there's a strong argument against doing this from a design perspective. I'm asking about that in a separate question.
The comments reiterated: Prefer composition over inheritance.
Inheritance works well when your subclasses have well defined behavioural differences from their superclass, but you'll frequently hit a point where that model gets awkward or stops making sense. At that point, you need to reconsider your design.
Composition is usually the better solution. Delegating your object's varying behaviour to a different object (or objects) may reduce or eliminate your need for subclassing.
In your case, the behavioural differences between class A and class B could be encapsulated in the Strategy pattern. You could then change the behaviour of class A (and class B, if still required) at the instance level, simply by assigning a new strategy.
The Strategy pattern may require more code in the short run, but it's clean and maintainable. Method swizzling, monkey patching, and all those cool things that allow us to poke around in our specific language implementation are fun, but the potential for unexpected side effects is high and the code tends to be difficult to maintain.
What you are asking is completely unrelated/unsupported by OOP programming.
If you subclass an object A with class B and override its methods, when a concrete instance of B is created then all the overriden/new implementation of the base methods are associated with it (either we talk about Java or C++ with virtual tables etc).
You have instantiated object B.
Why would you expect that you could/would/should be able to call the method of the superclass if you have overriden that method?
You could call it explicitely of course e.g. by calling super inside the method, but you can not do it automatically, and casting will not help you do that either.
I can't imagine why you would want to do that.
If you need to use class A then use class A.
If you need to override its functionality then use its subclass B.
Most programming languages go to some trouble to support dynamic dispatch of virtual functions (the case of calling the overridden method jump in a subclass instead of the parent class's implementation) -- to the degree that working around it or avoiding it is difficult. In general, specialization/polymorphism is a desirable feature -- arguably a goal of OOP in the first place.
Take a look at the Wikipedia article on Virtual Functions, which gives a useful overview of the support for virtual functions in many programming languages. It will give you a place to start when considering a specific language, as well as the trade-offs to weigh when looking at a language where the programmer can control how dispatch behaves (see the section on C++, for example).
So loosely, the answer to your question is, "No, the behavior is not the same in all programming languages." Furthermore, there is no language independent solution. C++ may be your best bet if you need the behavior.
You can actually do this with Python (sort of), with some awful hacks. It requires that you implement something like the wrappers we were discussing in your first Python-specific question, but as a subclass of B. You then need to implement write-proxying as well (the wrapper object shouldn't contain any of the state normally associated with the class hierarchy, it should redirect all attribute access to the underlying instance of B.
But rather than redirecting method lookup to A and then calling the method with the wrapped instance, you'd call the method passing the wrapper object as self. This is legal because the wrapper class is a subclass of B, so the wrapper instance is an instance of the classes whose methods you're calling.
This would be very strange code, requiring you to dynamically generate classes using both IS-A and HAS-A relationships at the same time. It would probably also end up fairly fragile and have bizarre results in a lot of corner cases (you generally can't write 100% perfect wrapper classes in Python exactly because this sort of strange thing is possible).
I'm completely leaving aside weather this is a good idea or not.

inner classes in smalltalk

I wonder why smalltalk doesn't make use of java-style inner class. This mechanism effectively allows you to define a new instance of a new class, on-the-fly, where you need it, when you need it. It comes handy when you need an object conforming to some specific protocol but you don't want to create a normal class for it, because of its temporary and local nature being very implementation specific.
As far I know, it could be done easily, since syntax for subclassing is standard message sending. And you can pass self to it so it has the notion of the "outer" object. The only issue is anonymousity - the class should not be present in object browser and must be garbage collected when no instances of it exit.
The question is: Has anyone thought of this?
There are really two answers here:
1 - Yes, it is not hard to create anonymous classes that automatically get garbage collected. In Squeak they are called "uniclasses" because the typical use case is for adding methods to a single object. Systems that use this are for example Etoys and Tweak (although in Etoys the classes are actually put into the SystemDict for historic reasons). Here's some Squeak code I recently used for it:
newClass := ClassBuilder new
newSubclassOf: baseClass
type: baseClass typeOfClass
instanceVariables: instVars
from: nil.
baseClass removeSubclass: newClass.
^newClass
Typically, you would add a convenience method to do this. You can can then add methods, and create an instance, and when all instances are gone, the class will be gc'ed too.
Note that in Java, the class object is not gc'ed - an inner class is compiled exactly like a regular class, it's only hidden by the compiler. In contrast, in Smalltalk this all happens at runtime, even the compiling of new methods for this class, which makes it comparatively inefficient. There is a much better way to create anonymous precompiled behavior, which brings us to answer 2:
2 - Even though it's not hard, it's rarely used in Smalltalk. The reason for that is that Smalltalk has a much more convenient mechanism. Inner classes in Java are most often used for making up a method on the fly implementing a specific interface. The inner class declaration is only needed to make the compiler happy for type safety. In Smalltalk, you simply use block closures. This lets you create behavior on the fly that you can pass around. The system libraries are structured in a way to make use of block closures.
I personally never felt that inner classes were something Smalltalk needed.
If you are thinking of using inner classes for tests, then you can also take a look to the class ClassFactoryForTestCase
Creating an anonymous class(es) in smalltalk is a piece of cake.
More than that, any object which has 3 its instance variables properly set to: its superclass, method dictionary and instance format could serve as a class (have instances).
So, i don't see how the problem here.
If you talking about tool(s) support, like browsing or navigating code which contained in such classes, this is different story. Because by default all classes in system are public, and system dictionary is a flat namespace of them (yes , some implementations has namespaces). This simple model works quite well most of the times.
I am pretty sure it could be done with some hacking around the Class and Metaclass protocol. And the question pops quite often from people who have more experience in Java, and Smalltalk becomes interesting to them. Since inner classes have not been implemented inspite of that, I take it to be the sign that most Smalltalk users do not find them usable. This might be because Smalltalk has blocks, which in simpler manner solve many if not all problems that led to the introduction of inner classes to Java.
(a) You could send the messages to create a new class from inside the method of another class
(b) I doubt that there is any benefit in hiding the resulting class from the introspection system
(c) The reason you use inner classes in Java is because there are no first-class functions. If you need to pass a piece of code in Smalltalk, you just pass a block. You don't need to wrap it up with some other type of object to do so.
The problem (in Squeak at least) comes from the lack of a clean separation of concerns. It's trivial to create your own subclass and put it in a private SystemDictionary:
myEnv := SystemDictionary new.
myClass := ClassBuilder new
name: 'MyClass'
inEnvironment: myEnv
subclassOf: Object
type: #normal
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'MyCategory'
unsafe: false.
But even though you put that class in your own SystemDictionary, the 'MyCategory' category added to the system navigation (verifiable by opening a Browser), and - worse - the class organisers aren't created, so when you navigate to MyClass you get a nil pointer.
It's certainly not impossible, theoretically. Right now the tooling's geared towards a single pool of globally visible class definitions.

"Finding" an object instance of a known class?

My first post here (anywhere for that matter!), re. Cocoa/Obj-C (I'm NOT up to speed on either, please be patient!). I hope I haven't missed the answer already, I did try to find it.
I'm an old-school procedural dog (haven't done any programming since the mid 80's, so I probably just can't even learn new tricks), but OOP has my head spinning! My question is:
is there any means at all to
"discover/find/identify" an instance
of an object of a known class, given
that some OTHER unknown process
instantiated it?
eg. somthing that would accomplish this scenario:
(id) anObj = [someTarget getMostRecentInstanceOf:[aKnownClass class]];
for that matter, "getAnyInstance" or "getAllInstances" might do the trick too.
Background: I'm trying to write a plugin for a commercial application, so much of the heavy lifting is being done by the app, behind the scenes.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
I've spent untold hours and days going over Apples documentation, tutorials and lots of example/sample code on the web (including here at Stack Overflow), and come up empty. Seems that everything requires a known target object to work, and I just don't have one.
Since I may not be expressing my problem as clearly as needed, I've put up a web page, with diagram & working sample pages to illustrate:
http://www.nulltime.com/svtest/index.html
Any help or guidance will be appreciated! Thanks.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
If this is a publicly declared class with publicly declared instance methods (i.e., you have the header for the class and it has instance methods in it), there is probably a way in this application's API to get an instance of the class. Either you are meant to create one yourself, or the application has one (or more) and provides a way to get it (or them). Look at both the header for the class in question and the other headers.
I initially said “there must be a way…”, but I changed it, because there is an alternative reason why the header would have instance methods: The application developer does not intend those instance methods for plug-in use (and didn't mark them appropriately), or did not mean to include that header in the application/SDK (they included it by accident). You may want to ask the application developer for guidance.
If it is not a publicly declared class or its instance methods are not publicly declared, then the application does not support you working with instances of the class. Doing so is a breach of the API contract—not a legal contract, but the expectations that the application has of its plug-ins. If you breach the API contract, you will cause unexpected behavior, either now (not necessarily on your own machine/in your own tests) or in the future.
If the class's public declaration contains only class methods, then perhaps what you're after is not an instance at all—you're supposed to send those messages to the class itself.
This is not possible without having you register each instance in a dictionary as it is created. I.e., override some common factory method at a higher level which does this bookkeeping work. This will fall down when you use delegates that you may not control though, keep that in mind.
I do question the need to even do this at all, but I don't know your problem as well as I perhaps would need to, to recommend a different, more apt way of accomplishing the actual task at hand.
Just as a corollary to the above; I did look at the runtime to see if there was anything that I actually forgot about, but there is not. So my above statement with regards to you requiring to do that bookkeeping yourself, still holds I'm afraid.
Edit:
Based on your diagram (my apologies, just noticed the link after I posted this answer); I would suggest that if you control the classes that are being returned to you, just add a property to them. I.e., add a "name" property that you can set and keep unique. Then just pass the message to each instance, checking whether or not that object is the one you want. It's not particularly clever or anything like that, but it should work for your purposes.

Discover subclasses of a given class in Obj-C

Is there any way to discover at runtime which subclasses exist of a given class?
Edit: From the answers so far I think I need to clarify a bit more what I am trying to do. I am aware that this is not a common practice in Cocoa, and that it may come with some caveats.
I am writing a parser using the dynamic creation pattern. (See the book Cocoa Design Patterns by Buck and Yacktman, chapter 5.) Basically, the parser instance processes a stack, and instantiates objects that know how to perform certain calculations.
If I can get all the subclasses of the MYCommand class, I can, for example, provide the user with a list of available commands. Also, in the example from chapter 5, the parser has an substitution dictionary so operators like +, -, * and / can be used. (They are mapped to MYAddCommand, etc.) To me it seemed this information belonged in the MyCommand subclass, not the parser instance as it kinda defeats the idea of dynamic creation.
Not directly, no. You can however get a list of all classes registered with the runtime as well as query those classes for their direct superclass. Keep in mind that this doesn't allow you to find all ancestors for the class up the inheritance tree, just the immediate superclass.
You can use objc_getClassList() to get the list of Class objects registered with the runtime. Then you can loop over that array and call [NSObject superclass] on those Class objects to get their superclass' Class object. If for some reason your classes do not use NSObject as their root class, you can use class_getSuperclass() instead.
I should mention as well that you might be thinking about your application's design incorrectly if you feel it is necessary to do this kind of discovery. Most likely there is another, more conventional way to do what you are trying to accomplish that doesn't involve introspecting on the Objective-C runtime.
Rather than try to automatically register all the subclasses of MYCommand, why not split the problem in two?
First, provide API for registering a class, something like +[MYCommand registerClass:].
Then, create code in MYCommand that means any subclasses will automatically register themselves. Something like:
#implementation MYCommand
+ (void)load
{
[MYCommand registerClass:self];
}
#end
Marc and bbum hit it on the money. This is usually not a good idea.
However, we have code on our CocoaHeads wiki that does this: http://cocoaheads.byu.edu/wiki/getting-all-subclasses
Another approach was just published by Matt Gallagher on his blog.
There's code in my runtime browser project here that includes a -subclassNamesForClass: method. See the RuntimeReporter.[hm] files.