In Java you can use generics to force the use of objects of a certain class.
Example: ArrayList forces the ArrayList to have instances of TestObject in it. This provides a strict list of objects.
I know you can also do this in Actionscript with the Vector class.
Is there any way to do this in Objective-C?
No, there is no equivalent. The only thing even remotely close is creating your own collection that, at runtime, enforces the class you've picked, but Java generics is a compile-time thing and there's no equivalent in obj-c.
From iOS 9 there are generics.
I can't find the reference to docs but this article contains a couple of words about the topic:
http://iosdevtips.co/post/121053658888/wwdc-ios-9-swift-2-notes
UPDATE:
There is also a new related feature called KindOf Types.
You can read about this one at the end of the article:
https://medium.com/the-traveled-ios-developers-guide/objective-c-in-2015-3cb7dab3690c
Related
I've been learning Kotlin and I've faced with Collections API. Before Kotlin I'd been learning Java and I know that in Java there's a lot of different types of Collections API. For example, instead of general List, Map, Queue, Set we use ArrayList, HashMap, LinkedList, LinkedMap and etc. Though in Kotlin we only use general types like Map, List, Set but also we can use HashMap and etc. So, what's going on there? Can you help me to figure out?
While Kotlin's original and primary target is the JVM, there is a huge push by JetBrains to make it multiplatform, and support JS and Native as well.
If you're using Kotlin on the JVM, the implementations of any collections you're using will still be the original JDK classes, e.g. java.util.ArrayList or java.util.HashSet. These are not reimplemented by the Kotlin standard library, which has some great benefits:
These are well-tested implementations, which are maintained anyway.
Using the exact same classes makes interop with Java a breeze, as you can pass them back and forth without having to perform conversions or mapping of any kind.
What Kotlin does do is introduce its own collection semantics over these existing implementations, in the form of the standard library interfaces such as List, Map, MutableList, MutableMap and so on. A small bit of compiler magic makes it so that these interfaces are implemented by the existing JDK classes as well.
If you don't need a specific implementation of a certain type of collection, you can use your collections via these interfaces plus the respective factory methods of the standard library (listOf, mapOf, mutableListOf, mutableMapOf, etc.). This keeps your code more generic, and independent of the concrete underlying implementations. You don't know what specific class the standard library mutableListOf function will create for you, only that it will be an object that satisfies the contract of the MutableList interface.
You should basically use these interfaces by default in your code, especially in public API:
In the case of function parameters, this lets clients provide the function with whatever implementation of the collection they wish to give you. If your function can operate on anything that's a List, you should ask for just that interface - no reason to require an ArrayList or LinkedList specifically.
If this is a return type, using these interfaces lets you change the specific implementation that you create internally in the future, without breaking client code. You can promise to just return a MutableList of things, and what implementation backs that list is not exposed to your clients.
If you look at all the collection handling functions of the Kotlin standard library, you'll see that on the surface, they almost exclusively operate on these interfaces. If you dig down deep enough, you'll find ArrayList instances being created, but this is not exposed to the client code, as it doesn't have to care about the concrete implementation most of the time.
Going back to the multiplatform point once more, if you write your code in a way such that it only relies on Kotlin standard library defined types, that code will be easily usable for non-JVM targets. If you reference kotlin.MutableList in your imports, that can immediately compile to JS code, because there's a Kotlin standard library implementation of that interface on each platform. Whether that maps to an existing class directly, wraps an existing class somehow, or is implemented for Kotlin from scratch, again, doesn't have to concern you. But if you refer to java.util.TreeSet in your code, that won't fly for the JS target, as the Java platform classes are not available there.
Can you still use classes such as java.util.ArrayList directly? Of course.
If you don't see your code going multiplatform at some point, using Java collections directly is perfectly okay.
If you need a specific implementation for a List or a Set for performance reasons, sometimes you'll have to use the Java classes directly.
Interestingly, in recent releases of Kotlin, these specific types of implementations (such as an array based list) are wrapped under standard library typealiases too, so that they're platform independent by default: see kotlin.collections.ArrayList or kotlin.collections.HashSet for examples of this. These Kotlin-defined types will usually show up first in IntelliJ completion, so you'll find yourself being pushed towards using them wherever possible. Same thing goes for most exceptions, e.g. IllegalArgumentException.
TL;DR: You can use either Kotlin collection types of Java types in Kotlin, but you should probably do the former whenever you can.
I'm new to VB.Net, and I am curious about the use cases for extension methods. Specifically, why would I use an extension method when I have inheritance and interfaces at my disposal? At first glance, extension methods don't seem to me like a very OO practice, and it seems like they would lead to less readable code as opposed to using subclasses and/or interfaces to achieve the same purpose. Is there something special about extension methods that I'm missing? When do you use them?
Before implementing an extension method, people should always try to see if it could fit inside a standard OO class.
However, there's 2 situations I can think of where those extension may be very handy:
1) Extension of primitive type: You don't want to derive a primitive type (like Int or Date) just to add an method to it. I'm not even sure if you're allowed to derive a primitive type but even if you could, it doesn't mean that you should.
2) Extension of common object: Let's say you want to write some addons functionalities to a very common object; let's say add a ToJSON method to a DbDataReader. You may force users the use your derived Type of DbDataReader (CustomDbDataReader) but they would have to change the code all over the place to use your new class. Using an extension would allow them to use your new method on a native DbDataReader.
You'll also notice that the DbDataReader is an abstract class. SqlDataReader and OleDbDataReader both derive from the DbDataReader class. If you want to write a legit OO function, you would have to write one for SqlDataReader and another one for the OleDbDataReader, even if the function does exactly the same thing.
You are right that extension methods are not a very important tool in the OO-toolbox. So you might not use them very often to extend classes in your own code.
As you also write, they might lead to confusion when reading other developers' code because you can only use extension methods that are located in a namespace that you have imported.
Nevertheless, extension methods are very handy if you want to create helper methods that extend classes that you cannot change. That is the main use case extension methods are created for.
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).
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.
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.