What's the name of the design pattern that makes a part of a class reusable. - objective-c

I'm doing Objective-C for iOS, say I have several UIViewControllers.
Some of these view controllers will have a particular feature that I developed and I want to be able to reuse it easily.
The feature in question consists of two methods that use an instance variable of the UIViewController.
In Objective-C, it's similar to a category but that could be used theoretically with any kind of class.
I know this is not very clear but any help is appreciated.

You might be able to implement your functionality as a decorator using the decorator pattern.

You can subclass UIViewController, creating a custom UIViewController (say "sub1"). Then all of the UIViewControllers that need that functionality can subclass sub1. This way you can easily reuse the code written once for sub1 simply using inheritance.

...The feature in question consists of two methods... that could be used theoretically with any kind of class.
well without knowing more details I'd say Extract Class looks generally worth considering. For particular use cases, more specialized ones might be better fit than that (Strategy, Specification etc etc etc)

Related

Code re-design to reduce redundancy

I am refactoring my static library to reduce code redundancy.
I have come across a certain situation which is depicted in the below image.
In this case, is going with the Utility class the best way out, or is there some better design pattern?
Thanks for your help.
Your approach looks like a good one. It's simple.
There are other patterns, but given only the information you provided, that's exactly what I would do.
One other thing to consider would be to make class A and Class B both inherit from the same super class and then place the logic in the super class.
Or better yet, make your classes POCO model objects only with no logic, and apply the logic to the superclass using a category.
Hope that helps.
I try and abstract out any common code into a Utility or Helper class. It's neat, bug fixes will apply to both and you know that both are using exactly the same method to do the same thing.
Either extract common functionality to one superclass, or keep the superclasses as they are and reflect the common functionality in a protocol.
Deciding which solution depends on the nature of the problem, that the reflected by classes.
You can't create the utility class as you draw in your diagram because in objective C you cannot inherit from more than one superclass.

Sharing code between Objective-C classes, like Traits in PHP

How can I share code between classes in Objective-C, the way Traits in PHP work?
I thought of using categories, but I wondered if there is something more suitable when it wouldn't be sensible to use inheritance.
There are several ways to share code between classes and each one has its own importance, depending upon the situation:
You can use inheritance.
You can declare Global Methods.
You can put the sharable code in AppDelegate.
You can use Singleton Class and put the common code in that class. (Not preferred for sharing code but we can still do it.)
All methods have their own pros/cons. You need to study their applications and use. Hope it helps.
Depends. You should ask yourself why do you want to have the same behaviour in various classes. You can use: Inheritance or design patterns (e.g. Composite pattern).
See:
Does Objective-C support traits/mixins?
Not sure if this is the best practice, or what you mean by "sharing code" but I usually have a static class which can hold global values.
The class is static and you can access it from anywhere like this:
[dataModel getMyValue];
[dataModel setMyValue];
It only becomes an issues if you try to write to it from multiple threads, but other than that its a good way to store shared data in your app.
Sharing code in Objective-C can be done only via subclassing or doing composition.
There is no equivalent of PHP's traits here. Categories work in a little bit different way. They're are assigned to a certain class, so you can't use code from category in any class. Unless you create NSObject category, which is good idea only in rare cases. You can treat category as a class extension.
It's possible 'share' interfaces having many different protocols. But it's not exactly what you need, I guess.

Subclassing UIView vs UIScrollView

Ok, this might not be possible, but I've got a class (called CompositeView) that's a subclasses UIView. It uses some core graphics work to produce a custom background based on some options. Not a huge class, but bound to grow as my demands change/increase/whatever. The problem I'm having is I use this class a lot, in a lot of different places. But in a few of the places I need it to be a subclass of UIScrollView instead of a UIView. Interestingly enough, I can simply change the superclass and it all works perfectly fine. But not only do I not want all my other views to be a UIScrollView, it also interferes with the operation of some of them. So I need a class that's sometimes a subclass of UIScrollView and sometimes a subclass of UIView.
For now, I've literally copied all of the interface/implementation of the CompositeView, changed the class name to CompositeScrollView, and changed it's inheritance to UIScrollView. It works fine, but now I've got two sets of code that do exactly the same thing, just inherited from different parent classes. This makes keeping them both up to date a pain.
Is there a better way to do this?
Single inheritance languages force you to use delegation. You'd factor out the added functionality into a separate class that you instantiate for your derived classes and then write forwarding shims from the derived class to the instances. It's painful.
Objective C has protocols which would describe the added functions (any shims that are not overrides) and then the compiler would error-out if you didn't write the shim ... which you still have to do manually.
Objective C also has categories that allow you to extend existing classes but these can't be shared (you have to extend each class individually) so it doesn't really help.
The best thing to do is impossible, of course: have a UIScrollView inherit from YOUR UIView subclass.
#smparkes' answer is good, but sometimes delegation does not do what you want, or it's too inconvenient. In this case, it's probably the latter.
Consider using the thing as a UIScrollView everywhere, but breaking the functionality that you don't need. UIScrollView instances act exactly like UIView instances -- well, they ARE UIView instances -- so you might just resolve this simple problem, "interferes with the operation of some of them" and go on your way. Shut off zoom, shut off scrolling, etc...
Unfortunately, this is the reality of single inheritance languages. Whatever you do, do not try to solve this with anything like changing the isa. Should you ever have any success, it will not be lasting. Objective-C is only slightly dynamic and does not allow for this kind of thing to be used seriously by regular programmers.
Ok, maybe this is totally crazy, but is ISA switching an option?
object->isa = [SomeClass class];
See: Objective-C: How to change the class of an object at runtime?
If you implemented a UIView-subclass that knew how to switch its ISA pointer to the UIScrollView-subclass, you would only have to deal with one class and could even decide dynamically which of the views you want at runtime.
Please note, that this is purely theoretical. I have never used ISA switching in live code and I personally don't think it makes for a good design :P
EDIT:
But again, it isn't reducing any redundancies ...
I've read a bit more into the topic and it really doesn't seem to be recommendable (memory structure of old object stays unchanged e.g.)
Yes, you may be interested in using Class-cluster. This can produce objects let's say MyCompositeClass which will produce either MyCompositeScrollClass objects or MyCompositeViewClass objects.
Apple uses class cluster a lot for instance in NSArray, when you use it, behind the scene your manipulating different objects. The difference is based on the size of the array, for instance for some small arrays NSArray will instanciate a class that is specialized in small data structure, etc...
This has the advantage of having nice performance and the complexity is totally hidded from the user by this concept of class cluster.
I invite you to read some documentation about that, it might be more understandable.
https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/ClassCluster.html
Hope this was helpful :)

When to use Categories

I've recently discovered categories and was wondering when it might be appropriate to use them in a user defined class/new class. For example, I can see the benefits of adding a category to an existing class like NSString, but when creating a new class what would be the advantage of adding a category to this rather than just implementing a normal method?
Hope this makes sense.
Many thanks
Jules
The answer isn't really any different for your own classes than it is for framework classes. If you have multiple projects, you'll likely end up sharing some classes between them. However, you may want to extend some of your classes so that they work more easily with a specific project, but not want to include those extra methods in your other projects, where they might not make sense. You can use a category to extend your class without needing to subclass.
If I understand your question correctly, creating a "new class" is always "subclassing" because you're subclassing NSObject at the very least.
You could use categories on a new class to separate out sections of responsibility of a complex class. For example, all the basic functionality (instance variables, accessors, description, etc.) can go in one file (the "main" class file) while all methods to support a protocol (such as NSTableViewDataSource) can go in another.
Some take this approach to keep things "neat". I'm a firm believer in "if it's my own custom class, all its code should be in one file" so I do not personally do this. I demarcate different logical aspects of the class' code with "#pragma mark Some Section Name" to help navigation and readability. Your mileage may vary.
Adding a Category on NSString is useful when you want to call a method on every single NSString instance you will encounter. This is a real improvement over inheritance for this kind of object because they are used by the core framework and you don't have to convert a NSString object to your subclass when you want to call your custom method.
On the other hand, you can just put methods in, no instance variables.
In the book Refactoring by Martin Fowler, he has a section titled "Introduce Foreign Method" (A server class you are using needs an additional method, but you can't modify the class.) That's what categories are good for.
That said, there are times when using a category, instead of changing the class, is appropriate. A good example on using a category, even though you could change the server class, is how Apple handled the UIViewController MediaPlayer Additions. They could have put these two methods in UIViewController itself but since the only people who would ever use them are people who are using the Media Player framework, it made more sense to keep the methods there.

Abstract design / patterns question

I had a bunch of objects which were responsible for their own construction (get properties from network message, then build). By construction I mean setting frame sizes, colours, that sort of thing, not literal object construction.
The code got really bloated and messy when I started adding conditions to control the building algorithm, so I decided to separate the algorithm to into a "Builder" class, which essentially gets the properties of the object, works out what needs to be done and then applies the changes to the object.
The advantage to having the builder algorithm separate is that I can wrap/decorate it, or override it completely. The object itself doesn't need to worry about how it is built, it just creates a builder and 'decorates' the builder with extra the functionality that it needs to get the job done.
I am quite happy with this approach except for one thing... Because my Builder does not inherit from the object itself (object is large and I want run-time customisation), I have to expose a lot of internal properties of the object.
It's like employing a builder to rebuild your house. He isn't a house himself but he needs access to the internal details, he can't do anything by looking through the windows. I don't want to open my house up to everyone, just the builder.
I know objects are supposed to look after themselves, and in an ideal world my object (house) would build itself, but I am refactoring the build portion of this object only, and I need a way to apply building algorithms dynamically, and I hate opening up my objects with getters and setters just for the sake of the Builder.
I should mention I'm working in Obj-C++ so lack friend classes or internal classes. If the explanation was too abstract I'd be happy to clarify with something a little more concrete. Mostly just looking for ideas or advice about what to do in this kind of situation.
Cheers folks,
Sam
EDIT: is it a good approach to declare a
interface House(StuffTheBuilderNeedsAccessTo)
category inside Builder.h ? That way I suppose I could declare the properties the builder needs and put synthesizers inside House.mm. Nobody would have access to the properties unless they included the Builder header....
That's all I can think of!
I would suggest using Factory pattern to build the object.
You can search for "Factory" on SO and you'll a get a no. of questions related to it.
Also see the Builder pattern.
You might want to consider using a delegate. Add a delegate method (and a protocol for the supported methods) to your class. The objects of the Builder class can be used as delegates.
The delegate can implement methods like calculateFrameSize (which returns a frame size) etc. The returned value of the delegate can be stored as an ivar. This way the implementation details of your class remain hidden. You are just outsourcing part the logic.
There is in fact a design pattern called, suitable enough, Builder which does tries to solve the problem with creating different configurations for a certain class. Check that out. Maybe it can give you some ideas?
But the underlying problem is still there; the builder needs to have access to the properties of the object it is building.
I don't know Obj-C++, so I don't know if this is possible, but this sounds like a problem for Categories. Expose only the necessary methods to your house in the declaration of the house itself, create a category that contains all the private methods you want to keep hidden.
What about the other way around, using multiple inheritance, so your class is also a Builder? That would mean that the bulk of the algorithms could be in the base class, and be extended to fit the neads of you specific House. It is not very beautiful, but it should let you abstract most of the functionality.