Example of hiding mechanism in Squeak, similar to C++ - smalltalk

I was wondering if it's possible to achieve the Hiding mechanism in Squeak, similar to the one in languages like C++ and C#, where its one of the main features. I know that I can override methods in Squeak and that I can't overload methods because its a dynamic languages, but Is it possible to hide methods/fields? I tried to dig in the Squeak logs but I could not find the answer. If it is possible to achieve hiding in Squeak I would be glad to see an example. If it's possible, what could be the reason? Maybe some OOP value which prohibits it?

While there is no explicit syntax that prohibits a call to super, if you don't call super from a method override, then the inherited implementation is effectively hidden. And, no, you can't prevent a subclass from having access to the superclass instance variables.

Please read first #JamesFoster's answer.
It should be relatively easy to add support for disallowing super. As super is not always valid, or at least it shouldn't be when the superclass is nil (e.g., ProtoObject), the compiler should somewhere check for this condition before allowing super as a valid pseudo variable. Then it would be a matter of tweaking that check by asking the class whether it supports super or not (rather than whether its superclass is nil).
I've tried in Pharo and there is no check at all (meaning that you can send to super in ProtoObject). So, modifying the Pharo compiler could be a little harder.

Related

TDD in Objective-c: property/constructor injection or method swizzling?

Since I've started using TDD I've been firmly convinced that it's a great way to write good correct pattern compliant code, without forcing my design decisions.
And I found this true in 80% scenarios, but I have problems when it comes to test certain tipe of objects which, for some reason, wrap and hide an object inside the implementation.
To give you an example let's think of a MyLocationManager objects which gives a common interface to my objects to be used, and wraps inside an NSLocationManager.
When I want to test such an object I have to supply a mock NSLocationManager of course.
I have of course the property/constructor injection method, but this means adding a property, or a constructor parameter, with an objects that I simply want to hide from the other objects: I've created MyLocationManager to wrap and hide NSLocationManager, why should I be exposing a property just to test it?
A method I've found which is pretty straightforward is to method swizzle NSLocationManager's methods, so I can exchange the actual implementation of a method with a mock one, but this seems pretty unclean and I don't know how safe it is.
As far as I can understand, there might be a Demeter Law's violation in not exposing a property constructor, but on the other hand, I think that in objective-c some flexibility on this pattern is accepted.
So my question is, there should be any way I'm not clearly seeing to adopt property/constructor injection, or method swizzling is a commonly used practice?
Are there any other techniques for this scenario adopted that I should better use?
On a footnote:
This problem is true even with objects that wraps networking code and classes like NSUrlSession.
Well, at one point the testing set-up can be more complicated than the code to test, so one might remember, what testing was invented for.
I think a pragmatic way is, to expose the property you need only in a separate header containing a separate class continuation.
After a long time of Test Driven Development experience, I find this old question of mine pretty simple to answer.
For some reason I was thinking that property injection and dependency injection where to avoid to mask something.
I simply don't think this anymore.
In the previous scenario of my original question the right answer from present-me is:
You have to expose the dependency of NSLocationManager, maybe providing a constructor injector method, and a convenience constructor method, to initialise the location manager with NSLocationManager.
There is no real need to hide the dependency even if it is a wrapper class, because in the exact moment you find yourself with the need to swizzle some methods, you're hacking the "internals" of your object and tweaking it without testing the interface, modifying the runtime behaviour in an uncontrolled manner.
If you wanna swizzle, swizzle ahead, but it's not the right choice.

Is using C functions instead of static methods for making pure functions a bad design?

If I am implementing a function that does some calculation based on certain input and returns the output without causing any side effects.
I always use Regular C functions instead of having static methods in a class.
Is there a rationale behind using static methods forcefully put into a class ?
I am not talking about methods that create singletons or factory methods but the regular methods like there:
Instead of having something like this:
+(NSString *)generateStringFromPrefixString:(NSString *)prefixString word:(NSString *)word;
won't this be better ?
NSString *generateString(NSString *prefixString, NSString *word);
In terms of efficiency also, wont we be saving, lookup for the selector to get the function pointer ?
Objective-C doesn't have such a thing as "static methods". It has class methods. This isn't just picking a nit because class methods are dispatched dynamically, not statically. And that can be one reason to use a class method rather than a function: it allows for subclasses to override it.
By contrast, that can also be a reason to use a function rather than a class method – to prevent it from being overridden.
But, in general, there's no rule that you have to use class methods. If a function suits your needs and your preferences, use a function.
I don't think it is bad design, no, but there are certain circumstances where one may be considered more appropriate than the other. The key questions are:
Does this method belong to a class?
Is this method worth adding to a class?
A class is something that is self-contained and reusable. For the method in your example, I would be tempted to answer "Yes, it does/is," because it is something specific to NSString and is a method you (presumably) want to use fairly often. Its parameters are also of type NSString. I would therefore use the message form in a class extension and #import the extension when you need it.
There are two situations (off the top of my head) where this is not really appropriate. Firstly is the situation where the method interacts specifically with other entities outside of the 'main class'. Examples of this can be found near the bottom of Apple's NSObjcRuntime.h file. These are all standard C functions. They don't really belong to a specific class.
The second situation to use a standard C function is when it will only be used once (or very few times) in a very specific circumstance. UIApplicationMain is the perfect example, and helper methods for a specific UIView subclass's -drawRect: method also come to mind.
A final point on efficiency. Yes, selector lookup is fractionally slower standard C calls. However, the runtime (Apple's at least, can't comment on GCC's) does use a caching system so that the most commonly sent messages quickly gravitate to the 'top' of the selector table.
Disclaimer: This is somewhat a question of a style and the above recommendations are the way I would do it as I think it makes code more organised and readable. I'm sure there are other equally valid ways to structure/interleave C and Objective-C code.
One important factor is testability. Does your c-functions specifically need testing? (off-course everything has to be ideally tested, but sometimes you just can test a thing by calling what calls it). If you need to, can you access those functions individually?
Maybe you need to mock them to test other functionality?
As of 2013, if you live in the Apple/Xcode/iOS/MacOS world, it is much more likely you have more built-in tools for testing things in objc than plain c. What I am trying to say is: Mocking of c-functions is harder.
I like very much C functions. At first I didn't like them to be in my good-looking objc code. After a while, I thought that doesn't matter too much. What it really matters is the context. My point is (as same as PLPiper's on NSObjcRuntime.h) that sometimes, by judging by its name or functionality, a function does not belong to any class. So there is no semantic reason to make them a class method. All this ambiguous-like thing went away when I started writing tests for code that contained several inline c functions. Now, if I need some c function be specifically tested, mocked, etc. I know it is easier to do it in objc. There are more/easier built-in tools for testing objc things that c.
For the interested: Function mocking (for testing) in C?
For sake of consistency and programmer expectation, i'd say to use Objective C style. I'm no fan of mixing calling notation and function notation, but your mileage may differ.

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.

Using Objective-C Introspection vs. Forcing Additional Message Override?

I have a base class which adds some functionality to a number of derived classes in my app.
One of these features is only used by some subclasses.
Currently I'm using a method which returns a BOOL which defaults to NO to "short-circuit" this feature. Subclasses which want the feature must override this method and return YES.
This feature is only useful if you've also overridden at least one of two other methods.
I'd prefer to use class_copyMethodList to determine if the subclass implemented either of these two methods (instead of using the method which returns a BOOL).
What barriers/roadblocks/cons to this approach should I be aware of? Is there a standard implementation of this idiom which I can use?
If I may suggest an alternative approach, have you considered using -instanceMethodForSelector on the relevant subclass instance and comparing to the result on the base class?
That method returns an IMP, which is a C function pointer to the implementation for the given selector. So if the subclass has a different implementation from the base class, it'll return a different IMP.
EDIT: as discussed in the comments below, a further alternative is to declare a formal protocol that the sub classes may implement, and to use NSObject's -conformsToProtocol: to determine whether the protocol is implemented. Since conformsToProtocol returns whether the class has declared support for the protocol (in its #interface via the angle brackets syntax), that's a lot like adding a custom BOOL method that defaults to returning NO but without the syntactic and semantic overhead of adopting your own ad hoc solution.
I have a base class which adds some functionality to a number of derived classes in my app.
This sentence should cause you to rethink your design. A base class should never do anything to derived classes. It should be ignorant of its subclasses. (Class Clusters notwithstanding. That's a separate design approach and require the superclass to be aware in the construction, making it the Factory pattern, which is fine.)
One of these features is only used by some subclasses.
This is a strong indication of a "Square/Rectangle" mistake. In OOP (forget ObjC, this is just CS theory), a square is not a rectangle. You need to ensure that your types conform to Liskov's Substitution Principle. Again, this has nothing to do with any particular language; it's true of all OOP design. It may seem very "theoretical" but it will seriously screw up your implementation if you fail LSP, and you will chase subtle bugs for much longer than you like.
The pattern you probably want here is Decorator rather than subclassing. If you have some special functionality that exists on some classes, you want to encapsulate that functionality into a separate object and attach it to subclasses where it makes sense. Another possible pattern is Strategy (which is generally implemented as a "delegate" in ObjC, which is another way of thinking about Decorator). The point is that you don't want logic in the superclass that is only applicable to some subclasses. You want to put that logic into something that only exists in the appropriate subclasses.
If all of those things fail you, then I strongly recommend a simple (BOOL) function over anything that introspects the method implementations. That way is fragile because it relies on ever-deeper implementation details. respondsToSelector: is definitely better than testing instanceMethodForSelector:.

Best way to define an immutable class in Objective C

I am a newbie in Objective C and I was wondering what is
the best way to define an immutable class in Objective-C (like NSString for example).
I want to know what are the basic rules one has to follow to make a class immutable.
I think that :
setters shouldn't be provided
if properties are used, they should be readonly
to "disable" Key Value Coding , accessInstanceVariablesDirectly must be override and return NO
Did I forget something ?
Thanks
The first and foremost thing you should do is to include usage comments in your .h file that explain that this is an immutable class, along with the class's purpose and general usage guidance. Far too often people go to great lengths to try to "enforce" with the compiler what could be achieved by just informing the caller.
You should certainly not provide public setters or readwrite properties if you intend the class to be immutable (but of course you should provide private setters so that you can use accessors within the class; you should always avoid, even internally, messing with ivars directly except in a few places). I guess you could add your accessInstanceVariablesDirectly override if you saw this as a likely error on the part of the caller.
But the key to understanding Objective-C is to understand and embrace the fact that the caller is not the enemy. The called code does not need to be "protected" from the caller. The caller needs to be protected from likely error. Everyone is on the same side here; caller and called want the program to work.
The caller is the customer and should be treated as such. The customer is not always right, but the customer is always the customer. Sometimes that means protecting the customer from himself if there is an easy mistake he might make. NSAssert() is particularly useful for that. And providing public setters to an immutable class is almost tricking the caller into making a mistake, so that would be bad for everyone.
In any case, you shouldn't make your class overly complex to try to enforce immutability. The caller can almost (*) always violate encapsulation by accessing the struct directly (object->ivar). The caller would be foolish to do so, but you would be even more foolish to try to prevent it. Note the immutability, hide your setters and mark your properties readonly, and in almost all cases you should be fine.
(*) Yes, it's possible to even more hide your data by nesting a private struct/object as an ivar, but then the caller can still modify the data with pointer arithmetic so it's still not "enforced." Always ask yourself what problem you're really trying to solve.
I believe they way I'd accomplish this is to have the header file contain only the publicly needed information. The rest would go in to the source file to limit possible override exposure.
Since Objective-C apparently has no definitive way of defining a class as final (sealed, etc), everything you'd be able to do isn't really all encompassing.
I've long ago came to the conclusion that you really can't use Objective-C like you'd use Java, C++ or C#. Objective-C is simply too different. In fact I believe there are drastic paradigm differences such as static vs. dynamic method dispatch/calls.
The reason I mention this is because perhaps no class in Objective-C is truly final. Perhaps this is by language design and not something you should try to get around. If you do, you'd ultimately needlessly complicate your code.