I'm working a project that has multiple components. Some of those components will need to be re-useable between apps -- the apps are related but cannot themselves be merged for business reasons. Thankfully the problem below isn't actually going to cause me issues, but I'm highly curious about how I'd solve it. Because someday I may just need to implement the following pattern.
So assuming I've got a CocoaPod named Foo and another named Bar. Foo reports to it's delegates using objects that implement the Foo.BussinessLogic protocol. Bar just happens to have an identical Bar.BussinessLogic protocol. I can write objects that conform to both protocols readily enough, but other than directly making Foo conform to Bar.BussinessLogic, how do I connect to the two without writing a pair of wrappers around each whose only job is to say item as! Bar.BussinessLogic when Foo sends a message to bar, and vice versa?
If the protocols share a bunch of methods, then my instinct would be to have them both conform to a common protocol in a third library that they both can depend on.
In Swift you can't just trick the compiler and say "trust me, they have the same methods".
However, I'm not sure if that answers your question since the types in your question are so nebulous. There are lots of other possible solutions. It depends on the situation.
Related
With time I started using the same "framework" I built myself for many projects, but I'm in the process of refactoring a lot of it now. I will have to break the interface of many classes (changing return types, poor naming, functions that modified their input argument, some have nasty side effects...), and my older programs are obviously relying on them.
My question is: how do you make such big changes and keep older code working? Start making "version" folders?
Or is it a bad practice to use classes across projects directly? (e.g. a custom Math class, and everyone accesses the same file)
If you meant actual interfaces:
As far as I know, you should try to avoid changing interfaces as much as possible. They're a contract and as such are set in stone. If you ever want to add or change something, you could overwrite it and add the new method to the subInterface.
In general:
I'd keep all the old methods, but deprecate them and rewire their functionality to your new overloads.
It seems a lot of Objective-C code is using Singleton nowadays.
While a lot of people complaining about Singleton, e.g. Google (Where Have All the Singletons Gone?), their fellow engineers also use it anyway: http://code.google.com/mobile/analytics/docs/iphone/
I know we had some answers in Stack Overflow already but they are not totally specific to Objective-C as a dynamic language: Objective C has categories, while many other languages do not.
So what is your opinion? Do you still use Singleton? If so, how do you make your app more testable?
Updated: I think we need to use codes as example for more concrete discussion, so much discussions on SO are theory based without a single line of code
Let's use the Google Analytics iOS SDK as an example:
// Initialization
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-0000000-1"
dispatchPeriod:kGANDispatchPeriodSec
delegate:nil];
// Track page view
[[GANTracker sharedTracker] trackPageview:#"/app_entry_point"
withError:&error];
The beauty of the above code is once you have initialized using the method "startTrackerWithAccountID", you can run method "trackPageview" throughout out your apps without passing through configurations.
If you think Singleton is bad, can you improve the above code?
Much thanked for your input, have a happy Friday.
This post is likely to be downvote-bait, but I don't really understand why singletons get no love. They're perfectly valid, you just have to understand what they're useful for.
In iOS development, you have one and only one instance of the application you currently are. You're only one application, right? You're not two or zero applications, are you? So the framework provides you with a UIApplication singleton through which to get at application-level os and framework features. It models something appropriately to have that be a singleton.
If you've got data fields of which there can and should be only one, and you need to get to them from all over the place in your app, there's totally nothing wrong with modeling that as a singleton too. Creating a singleton as a globals bucket is probably a misuse of the pattern, and I think that's probably what most people object to about them. But if you're modeling something that has "singleness" to it, a singleton might well be the way to go.
Some developers seem to have a fundamental disgust for singletons, but when actually asked why, they mumble something about globals and namespaces and aesthetics. Which I guess I can understand, if you've really resolved once and for all that Singletons are an anti-pattern and to be abhorred in all cases. But you're not thinking anymore, at that point. And the framework design disagrees with you.
I think most developers go through the Singleton phase, where you have everything you need at your fingertips, in a bunch of wonderful Singletons.
Then you discover that unit testing with Singletons can be difficult. You don't actually want to connect to the database, but your Singleton does. Add a layer of redirection and mock it.
Then you discover that unit testing isn't the only time you need different behaviour. You make your Singleton configurable to have different behaviour based on a parameter. You start to wonder if you need to split it into two Singletons. Then your code needs to know which Singleton to use, so you need a Singleton that knows which Singleton to use.
Then some other code starts messing with the values in your Singleton, while you're using it. How dare they! If you wanted just anybody to get at those values from anywhere, you'd make them global...
Once you get to this point, you start wondering if Singletons were the right solution. You start to see the dangers of global data, particularly within an OO design, where you just assume your data won't get poked at by other people.
So you go back and start passing the data along, rather than looking it up (this used to be called good OO design, but now it has a fancy name like "Dependency Injection").
Eventually you learn that Singletons are fine in moderation. You learn to recognize when your Singleton needs to stop being single.
So you get shared objects like UIApplication and NSUserDefaults. Those are good uses of Singletons.
I got burned enough in the Java Singleton craze a decade ago. I don't even consider writing my own Singletons. The only time I've needed anything similar in recent memory is wanting to cache the result of [NSCalendar currentCalendar] (which takes a long time). I created a category on NSCalendar and cached it as a static variable. I felt a bit dirty, but the alternative was painfully slow code.
To summarize and for those who tl;dr:
Singletons are a tool. They're not likely to be the right tool, but you have to discover that for yourself.
Why do you need an answer that is "total Objective C specific"? Singletons aren't totally Obj-C specific either, and you're able to use those. Functions aren't Obj-C-specific, integers aren't Obj-C specific, and yet you're able to use all of those in your Obj-C code.
The obvious replacements for a singleton work in any language.
A singleton is a badly-designed global.
So the simplest replacement is to just make it a regular global, without the silly "one instance only" restriction.
A more thorough solution is, instead of having a globally accessible object at all, pass it as a parameter to the functions that need it.
And finally, you can go for a hybrid solution using a Dependency Injection framework.
The problem with singletons is that they can lead to tight coupling. Let's say you're building an airline booking system: your booking controller might use an
id<FlightsClient>
A common way to obtain it within the controller would be as follows:
_flightsClient = [FlightsClient sharedInstance];
Drawbacks:
It becomes difficult to test a class in isolation.
If you want to change the flight client for another implementation, its necessary to search through the application and swap it out one by one.
If there's a case where the application should use a different implementation (eg OnlineFlightClient, OfflineFlightClient), things get tricky.
A good workaround is to apply the dependency injection design pattern.
Think of dependency injectionas telling an architectural story. When the key actors in your application are pulled up into an assembly, then the application’s configuration is correctly modularized (removing duplication). Having created this script, its now easy to reconfigure or swap one actor for another.”. In this way we need not understand all of a problem at once, its easy to evolve our app’s design as the requirements evolve.
Here's a dependency injection library: https://github.com/typhoon-framework/Typhoon
I am a beginner to programming, and a beginner to Objective-C. I learned basic C and decided to start learning Objective-C. I am reading "Programming in Objective C 2.0" by Steven Kochan.
His section on Protocols is vague. He doesn't thoroughly explain WHY someone would want to use protocols in their programs, nor does he give a concrete example with it implemented in a program.
He writes:
"You can use a protocol to define methods that you want other people who subclass your class to implement."
He also says that Protocols are good for sub-classes to be able to implement certain methods, without having to first define the actual methods. He also says protocols can be used across different classes because they are classless.
I know there must be a valid and smart way to implement protocols, but based on what he wrote, I don't see why someone would use protocols instead of just creating a class method outside of the reason that more than one class can adhere to a protocol (I know there are some more good reasons though!).
I was wondering if someone could help me understand:
how, why and when I would use Protocols in my program in an intelligent way.
If you've done any kind of object-oriented programming, you probably know protocols as interfaces (they're not identical, but the concept is similar). If not, think of protocols as blueprints.
The main reason why you'd use protocols is so you can use objects without knowing everything about them; all you need to know is that they implement a set of methods. For example, if the classes Business and Person conform to the protocol Contact, which defines the method - (NSString *)phoneNumber, the class AddressBook can call -(NSString *)phoneNumber without knowing whether or not the object is of type Business or Person.
Once you start to learn about Cocoa and delegates, you'll see how powerful and important protocols are.
One word, delegates.
Objective-c uses delegates all over the place to allow classes to talk to each other.
To see an example see UITableViewDelegate Protocol
That's not the only place #protocol is used, but it's probably the most common use for it.
Protocols are better versions of callback functions in C.
Protocols are useful constructs when you want to implement MVC architecture yourself.
The Views need to be notified when Model changes,You can use protocols to notify appropriate events to Observers.
You could have a class that is a UIViewController, and it implements several protocols, such as UITableViewDelegate, UITableViewDataSource. A class can do more than one thing.
Like #conmulligan says Objective-C uses protocols to make classes talk to each other.
Its one of many ways to communicate between classes.
But protocols is necessarily a bad way.
I use protocols if I was to create a re-usable object, that is usually used for many projects.
So I create protocols to make my code easy to maintain.
I'm writing an iPhone application and I find that there are three controllers in the application that have very similar functionality. They are similar enough that it doesn't make sense to separate them into three separate classes, so I have a "mode" property that clients of the class use to specify how the controller should behave in certain situations. But again, maybe 95% of the functionality is identical. There are three separate modes with only minor differences in behavior.
This feels messy to me. Is there a better pattern for this?
You could try inheritance ... the three controllers can all inherit from a common base that implements the shared functionality.
Aside from that, you could look at the Strategy Pattern.
Which one you use depends on what your code is doing and what the bits that change look like :-)
A similar approach would involve not to use inheritance (i.e.: use the same controller for the three screens) and use the state pattern to define specific behavior for each of the screens.
I think the title speaks for itself guys - why should I write an interface and then implement a concrete class if there is only ever going to be 1 concrete implementation of that interface?
I think you shouldn't ;)
There's no need to shadow all your classes with corresponding interfaces.
Even if you're going to make more implementations later, you can always extract the interface when it becomes necessary.
This is a question of granularity. You cannot clutter your code with unnecessary interfaces but they are useful at boundaries between layers.
Someday you may try to test a class that depends on this interface. Then it's nice that you can mock it.
I'm constantly creating and removing interfaces. Some were not worth the effort and some are really needed. My intuition is mostly right but some refactorings are necessary.
The question is, if there is only going to ever be one concrete implementation, should there be an interface?
YAGNI - You Ain't Gonna Need It from Wikipedia
According to those who advocate the YAGNI approach, the temptation to write code that is not necessary at the moment, but might be in the future, has the following disadvantages:
* The time spent is taken from adding, testing or improving necessary functionality.
* The new features must be debugged, documented, and supported.
* Any new feature imposes constraints on what can be done in the future, so an unnecessary feature now may prevent implementing a necessary feature later.
* Until the feature is actually needed, it is difficult to fully define what it should do and to test it. If the new feature is not properly defined and tested, it may not work right, even if it eventually is needed.
* It leads to code bloat; the software becomes larger and more complicated.
* Unless there are specifications and some kind of revision control, the feature may not be known to programmers who could make use of it.
* Adding the new feature may suggest other new features. If these new features are implemented as well, this may result in a snowball effect towards creeping featurism.
Two somewhat conflicting answers to your question:
You do not need to extract an interface from every single concrete class you construct, and
Most Java programmers don't build as many interfaces as they should.
Most systems (even "throwaway code") evolve and change far past what their original design intended for them. Interfaces help them to grow flexibly by reducing coupling. In general, here are the warning signs that you ought to be coding to an interface:
Do you even suspect that another concrete class might need the same interface (like, if you suspect your data access objects might need XML representation down the road -- something that I've experienced)?
Do you suspect that your code might need to live on the other side of a Web Services layer?
Does your code forms a service layer to some outside client?
If you can honestly answer "no" to all these questions, then an interface might be overkill. Might. But again, unforeseen consequences are the name of the game in programming.
You need to decide what the programming interface is, by specifying the public functions. If you don't do a good job of that, the class would be difficult to use.
Therefore, if you decide later you need to create a formal interface, you should have the design ready to go.
So, you do need to design an interface, but you don't need to write it as an interface and then implement it.
I use a test driven approach to creating my code. This will often lead me to create interfaces where I want to supply a mock or dummy implementation as part of my test fixture.
I would not normally create any code unless it has some relevance to my tests, and since you cannot easily test an interface, only an implementation, that leads me to create interfaces if I need them when supplying dependencies for a test case.
I will also sometimes create interfaces when refactoring, to remove duplication or improve code readability.
You can always refactor your code to introduce an interface if you find out you need one later.
The only exception to this would be if I were designing an API for release to a third party - where the cost of making API changes is high. In this case I might try to predict the type of changes I might need to do in the future and work out ways of creating my API to minimise future incompatible changes.
One thing which no one mentioned yet, is that sometimes it is necessary in order to avoid depenency issues. you can have the interface in a common project with few dependencies and the implementation in a separate project with lots of dependencies.
"Only Ever going to have One implementation" == famous last words
It doesn't cost much to make an interface and then derive a concrete class from it. The process of doing it can make you rethink your design and often leads to a better end product. And once you've done it, if you ever find yourself eating those words - as frequently happens - you won't have to worry about it. You're already set. Whereas otherwise you have a pile of refactoring to do and it's gonna be a pain.
Editted to clarify: I'm working on the assumption that this class is going to be spread relatively far and wide. If it's a tiny utility class used by one or two other classes in a single package then yeah, don't worry about it. If it's a class that's going to be used in multiple packages by multiple other classes then my previous answer applies.
The question should be: "how can you ever be sure, that there is only going to ever be one concrete implementation?"
How can you be totally sure?
By the time you thought this through, you would already have created the interface and be on your way without assumptions that might turn out to be wrong.
With today's coding tools (like Resharper), it really doesn't take much time at all to create and maintain interfaces alongside your classes, whereas discovering that now you need an extra implementation and to replace all concrete references can take a long time and is no fun at all - believe me.
A lot of this is taken from a Rainsberger talk on InfoQ: http://www.infoq.com/presentations/integration-tests-scam
There are 3 reasons to have a class:
It holds some Value
It helps Persist some entity
It performs some Service
The majority of services should have interfaces. It creates a boundary, hides implementation, and you already have a second client; all of the tests that interact with that service.
Basically if you would ever want to Mock it out in a unit test it should have an interface.