Most likely an OO concept question/situation:
I have a library that I use in my program with source files available. I've realized I need to tailor the library to my needs, say I need to modify the behavior of a single functions F in class C, while leaving the original library's source intact, to be able to painlessly upgrade it when needed.
I realize I can make my own class C1 inherited from C, place it in my source tree, and write the function F how I see it fit, replacing all occurrences of
myObj = new C();
with
myObj = new C1();
throughout my code.
What is the 'proper' way of doing this? I suspect the inheritance method I described has problems, as the library in its internals would still use C::F instead of my C1::F, and it would be way cooler if I could still refer to C::F not some strange C1::F in my code.
For those that care - the language is PHP5, and I'm kinda OOP newbie :)
I think subclassing is pretty much the best way to add functionality to an external library.
The alternative is the decorator pattern whereby you have to wrap every method of the C class. (There is a time and place for the decorator pattern, but I think this isn't it)
You say:
as the library in its internals would still use C::F instead of my C1::F
Not necessarily true. If you pass an instance of the C1 class to a library function, then any calls to method F of that object would still go through your C1::F method. The same also happens when the C class accesses its own method by calling $this->F() -- because it's still a C1 object. This property is called polymorphism
Of course this does not apply when the library's code itself instantiates a new object of class C.
Related
I left the original, so people can understand the context for the comments. Hopefully, this example will better help explain what I am after.
Can I create a class in Obj-C that has file-scope visibility?
For example, I have written a method-sqizzling category on NSNotificationCenter which will automatically remove any observer when it deallocs.
I use a helper class in the implementation, and to prevent name collision, I have devised a naming scheme. The category is NSNotificationCenter (WJHAutoRemoval), so the private helper class that is used in this code is named...
WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
That's a mouthful, and currently I just do this...
#define BlockObserver WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
and just use BlockObserver in the code.
However, I don't like that solution.
I want to tell the compiler, "Hey, this class is named Bar. My code will access it as Bar, but I'm really the only one that needs to know. Generate a funky name yourself, or better yet, don't even export the symbol since I'm the only one who should care."
For plain C, I would is "static" and for C++ "namespace { }"
What is the preferred/best/only way to do this in Obj-C?
Original Question
I want to use a helper class inside the implementation of another. However, I do not want external linkage. Right now, I'm just making the helper class name painfully unique so I will not get duplicate linker symbols.
I can use static C functions, but I want to write a helper class, with linker visibility only inside the compilation unit.
For example, I'd like to have something like the following in multiple .m files, with each "Helper" unique to that file, and no other compilation unit having linker access. If I had this in 10 different files, I'd have 10 separate classes.
#interface Helper : NSObject
...
#end
#implementation Helper : NSObject
...
#end
I have been unable to find even a hint of this anywhere, and my feeble attempts at prepending "static" to the interface/implementation were wrought with errors.
Thanks!
I don't believe you will be able to do what you want because of the Objective-C Runtime. All of your classes are loaded into the runtime and multiple classes with the same name will conflict with each other.
Objective-C is a dynamic language. Unlike other languages which bind method calls at compile time, Objective-C does method resolution at invocation (every invocation). The runtime finds the class in the runtime and then finds the method in the class. The runtime can't support distinct classes with the same name and Objective-C doesn't support namespaces to seperate your classes.
If your Helper classes are different in each case they will need distinct class names (multiple classes with the same name sounds like a bad idea to me, in any language). If they are the same then why do you want to declare them separately.
I think you need to rethink your strategy as what you are trying to do doesn't sound very Objective-C or Cocoa.
There's no way to make a class "hidden." As mttrb notes, classes are accessible by name through the runtime. This isn't like C and C++ where class are just symbols that are resolved to addresses by the linker. Every class is injected into the class hierarchy.
But I'm unclear why you need this anyway. If you have a private class WJHAutoRemovalHelper or whatever, it seems very unlikely to collide with anyone else any more than private Apple classes or private 3rdparty framework classes collide. There's no reason to go to heroic lengths to make it obscure; prefixing with WJHAutoRemoval should be plenty to make it unique. Is there some deeper problem you're trying to fix?
BTW as an aside: How are you implementing the rest of this? Are you ISA-swizzling the observer to override its dealloc? This seems a lot of tricky code to make a very small thing slightly more convenient.
Regarding the question of "private" classes, what you're suggesting is possible if you do it by hand, but there really is no reason for it. You can generate a random, unique classname, call objc_allocateClassPair() and objc_registerClassPair on it, and then assign that to a Class variable at runtime. (And then call class_addMethod and class_addIvar to build it up. You can then always refer to it by that variable when you need it. It's still accessible of course at runtime by calling objc_getClassList, but there won't be a symbol for the classname in the system.
But this is a lot of work and complexity for no benefit. ObjC does not spend much time worrying about protecting the program from itself the way C++ does. It uses naming conventions and compiler warning to tell you when you're doing things wrong, and expects that as a good programmer you're going to avoid doing things wrong.
What advantage is there, if any, to using Modules rather than classes in VB? How do they differ, and what advantages/disadvantages are there in using modules? In VB or VB.NET, I use both.
(A) Modules
and
(B) Classes with only Shared functions
solve the same problem: Both allow you to logically group a set of functions.
Advantages of using a module:
It allows you to define extension methods.
For someone reading your code, it is immediately obvious that this is not a class representing a group of stateful objects but just a "function container".
Advantages of using a class with shared functions:
It's easy to extend it with instance (= non-shared) variables, functions and properties later on.
So, if you are writing a set of helper functions and want to logically group them (where the concept of a state of this group just doesn't make sense), use a module -- this is exactly what they are here for. On the other hand, if you have a function that conceptually fits to an already existing class, add it as a shared function to that class.
A major difference is that methods in modules can be called globally whereas methods in classes can't. So instead of ModuleName.MyMethod() you can just call MyMethod(). Whether that is an advantage or disadvantage depends on the circumstances.
Module are come earlier and now VB.NET just let it for backward compatibility. Modules and Class are nearly same. You can call Module.Function() directly as it treat as Shared Function in a class. Class you can define Shared Function/Method and additionally can create an instance like Dim c as Class = New Class().
Avoid use of Module, instead use Class. it is good for you to write a better OOP programming.
This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.
In object-oriented programming, it's sometimes nice to be able to modify the behavior of an already-created object. Of course this can be done with relatively verbose techniques such as the strategy pattern. However, sometimes it would be nice to just completely change the type of the object by changing the vtable pointer after instantiation. This would be safe if, assuming you're switching from class A to class B:
class B is a subclass of class A and does not add any new fields, or
class B and class A have the same parent class. Neither do anything except override virtual functions from the parent class. (No new fields or virtual functions.)
In either case, A and B must have the same invariants.
This is hackable in C++ and the D programming language, because pointers can be arbitrarily cast around, but it's so ugly and hard to follow that I'd be scared to do it in code that needs to be understood by anyone else. Why isn't a higher-level way to do this generally provided?
Because the mindset of most languages designers is too static.
While such features are dangerous in the hand of programmers, they are necessary tools for library builders. For example, in Java one can create objects without calling a constructor (yes, you can!) but this power is only given to library designers. Still however, many features that library designers would kill for are alas not possible in Java. C# on the other hand is adding more and more dynamic features in each version. I am really looking forward to all the awesome libraries one can build using the upcoming DLR (dynamic language runtime).
In some dynamic languages such as Smalltalk (and also as far as I know Perl and Python, but not Ruby) it is totally possible to change the class of an object. In Pharo Smalltalk you achieve this with
object primitiveChangeClassTo: anotherObject
which changes the class of object to that of anotherObject. Please note that this is not the same as object become: anotherObject which exchanges all pointers of both objects.
You can do it in Python, by modifying the instance __class__ attribute:
>>> class A(object):
... def foo(self):
... print "I am an A"
...
>>>
>>> class B(object):
... def foo(self):
... print "I am a B"
...
>>>
>>> a = A()
>>> a.foo()
I am an A
>>> a.__class__
<class '__main__.A'>
>>> a.__class__ = B
>>>
>>> a
<__main__.B object at 0x017010B0>
>>> a.foo()
I am a B
However in 12 years of Python programming I have never had a use for it, and never seen anyone else use it. IMHO there is a huge danger that casual use of this feature will make your code hard to maintain and debug.
The only situation where I can imagine using it is for runtime debugging, e.g. to change an instance of a class whose creation I don't have control into a mock object or into a class that has been decorated with logging. I would not use it in production code.
You can do it in higher level languages - see the Smalltalk "become" message. The fact that this feature is almost impossible to use correctly even in ST could be the reason that statically typed languages like C++ don't support it.
To paraphrase the XoTcl documentation, it is because most languages which proclaim to be "object oriented" are not--they are class oriented. It sounds like XoTcl mixins, Ruby mixins, and Perl6 roles provide the functionality you're looking for.
What you're talking about is monkey patching, that is available in several high level dynamic language :
A monkey patch (also spelled
monkey-patch, MonkeyPatch) is a way to
extend or modify the runtime code of
dynamic languages (e.g. Smalltalk,
JavaScript, Objective-C, Ruby, Perl,
Python, Groovy, etc.) without altering
the original source code.
What is the standard way of incorporating helper/utility functions in Obj-C classes?
I.e. General purpose functions which are used throughout the application and called by more than 1 class.
Can an Obj-C method exist outside of a class, or does it need to be a C function for it to have this kind of behaviour?
I would group similar functions as static methods in a helper class. These can then be called using the classname rather the instance name. Static methods are defined with a + instead of the usual -.
like so:
#interface HelperClass: superclassname {
// instance variables - none if all methods are static.
}
+ (void) helperMethod: (int) parameter_varName;
#end
This would be called like so.
[HelperClass helperMethod: 10 ];
As this is static you do not init/alloc the class. This has the advantage of clearly grouping like Helper functions. You could use standalone C functions but as your Application gets larger it can become a right mess! Hope this helps.
Tony
I don't see why people are avoiding creating functions. Objective-C is a superset of C, which means that C is part of it. Moreover, it's completely integrated—there's no wall between them.
Create functions! It's fine! Foundation does it. Application Kit does it. Core Animation does it. Core Media does it.
I see no reason not to.
There are a number of options for this in Objective-C. First, since Obj-C is a strict superset of C, you can define all your library functions in a separate module (source file) and happily call them from any Obj-C object/code you already have. If you create an obj-c source file (.m file) you can then call back into/use objects.
If your generic functions are logically manipulating other, established objects (for instances, operates on an NSString), you can use categories to graph your functions on already existing classes (where that makes sense).
Finally, as Tony points out, you can create classes with static methods (although I like this option the least, personally). I tend to use a mix of one an two... adding categories where appropriate and using standard functions for others. I generally only make a new class where it makes sense to design a class.