I have some data which I want to wrap up in a collection. The data comes from two different sources using two different techniques so I'm trying to implement two structs which can conform to a common protocol. I would like to return a type which looks something like this:
Collection<Media>
But Collection is not generic. I have two data sources and therefore two classes which need to implement Collection but which I need to return through a single method.
My problem is that I want to return a type which can represent either of the two implementation and which the calling code will understand to represent Media.
I've tried building a protocol like this:
protocol MediaCollection:Collection {
subscript(i:Int) -> Media { get }
}
But I get complication errors because the code in Collection references Self and Swift doesn't like that. Telling me that MediaCollection cannot be used as a generic constraint because it has Self or associated type requirements.
I've also found that if I do something like this:
class MediaConnection:Collection {
var startIndex:Int {...}
var endIndex:Int {...}
func index(after i:Int) -> Int {...}
subscript(i:Int) -> Media {...}
}
It will compile the MediaCollection class, but when I try to use Collection as a type in a method signature I get the same problem.
I'm thinking at the moment the only option is to create a AbstractMediaCollection class. Then create a MediaCollection:AbstractMediaCollection and use AbstractMediaCollection in my method signatures. Really UGLY!
I've done lots of reading but I'm really not sure how to approach this problem.
Related
In Java, it is very common to have a list of utility functions
public class Utils {
private Utils() {
}
public static void doSomething() {
System.out.println("Utils")
}
}
If I were in Swift, should I use class or struct to achieve the similar thing? Or, it really doesn't matter?
class
class Utils {
private init() {
}
static func doSomething() {
print("class Utils")
}
}
struct
struct Utils {
private init() {
}
static func doSomething() {
print("struct Utils")
}
}
I think a conversation about this has to start with an understanding of dependancy injection, what it is and what problem it solves.
Dependancy Injection
Programming is all about the assembly of small components into every-more-abstract assemblies that do cool things. That's fine, but large assemblies are hard to test, because they're very complex. Ideally, we want to test the small components, and the way they fit together, rather than testing entire assemblies.
To that end, unit and integration tests are incredibly useful. However, every global function call (including direct calls to static functions, which are really just global functions in a nice little namespace) is a liability. It's a fixed junction with no seam that can be cut apart by a unit test. For example, if you have a view controller that directly calls a sort method, you have no way to test your view controller in isolation of the sort method. There's a few consequences of this:
Your unit tests take longer, because they test dependancies multiple times (e.g. the sort method is tested by every piece of code that uses it). This disincentivizes running them regularly, which is a big deal.
Your unit tests become worse at isolating issues. Broke the sort method? Now half your tests are failing (everything that transitively depends on the sort method). Hunting down the issue is harder than if only a single test-case failed.
Dynamic dispatch introduces seams. Seams are points of configurability in the code. Where one implementation can be changed taken out, and another one put in. For example, you might want to have a an MockDataStore, a BetaDataStore, and a ProdDataStore, which is picked depending on the environment. If all 3 of these types conform to a common protocol, than dependant code could be written to depend on the protocol that allows these different implementations to be swapped around as necessary.
To this end, for code that you want to be able to isolate out, you never want to use global functions (like foo()), or direct calls to static functinos (which are effectively just global functions in a namespace), like FooUtils.foo(). If you want to replace foo() with foo2() or FooUtils.foo() with BarUtils.foo(), you can't.
Dependancy injection is the practice of "injecting" dependancies (depending on a configuration, rather than hard coding them. Rather than hard-coding a dependancy on FooUtils.foo(), you make a Fooable interface, which requires a function foo. In the dependant code (the type that will call foo), you will store an instance member of type Fooable. When you need to call foo, call self.myFoo.foo(). This way, you will be calling whatever implementation of Fooable has been provided ("injected") to the self instance at the time of its construction. It could be a MockFoo, a NoOpFoo, a ProdFoo, it doesn't care. All it knows is that its myFoo member has a foo function, and that it can be called to take care of all of it's foo needs.
The same thing above could also be achieve a base-class/sub-class relationship, which for these intents and purposes acts just like a protocol/conforming-type relationship.
The tools of the trade
As you noticed, Swift gives much more flexibility in Java. When writing a function, you have the option to use:
A global function
An instance function (of a struct, class, or enum)
A static function (of a struct, class, or enum)
A class function (of a class)
There is a time and a place where each is appropriate. Java shoves options 2 and 3 down your throat (mainly option 2), whereas Swift lets you lean on your own judgement more often. I'll talk about each case, when you might want to use it, and when you might not.
1) Global functions
These can be useful for one-of utility functions, where there isn't much benefit to " grouping" them in a particular way.
Pros:
Short names due to unqualified access (can access foo, rather than FooUtils.foo)
Short to write
Cons:
Pollutes the global name space, and makes auto-completion less useful.
Not grouped in a way that aids discoverability
Cannot be dependancy injected
Any accessed state must be global state, which is almost always a recipe for a disaster
2) Instance functions
Pros:
Group related operations under a common namespace
Have access to localized state (the members of self), which is almost always preferable over global state.
Can be dependancy injected
Can be overridden by subclasses
Cons:
Longer to write than global functions
Sometimes instances don't make sense. E.g. if you have to make an empty MathUtils object, just to use its pow instance method, which doesn't actually use any instance data (e.g. MathUtils().pow(2, 2))
3) Static functions
Pros:
Group related operations under a common namespace
Can be dependancy in Swift (where protocols can support the requirement for static functions, subscripts, and properties)
Cons:
Longer to write than global functions
It's hard to extend these to be stateful in the future. Once a function is written as static, it requires an API-breaking change to turn it into an instance function, which is necessary if the need for instance state ever arrises.
4) Class functions
For classes, static func is like final class func. These are supported in Java, but in Swift you can also have non-finals class functions. The only difference here is that they support overriding (by a subclass). All other pro/cons are shared with static functions.
Which one should I use?
It depends.
If the piece you're programming is one that would like to isolate for testing, then global functions aren't a candidate. You have to use either protocol or inheritance based dependancy injection. Static functions could be appropriate if the code does not nned to have some sort of instance state (and is never expected to need it), whereas an instance function should be when instance state is needed. If you're not sure, you should opt for an instance function, because as mentioned earlier, transitioning a function from static to instance is an API breaking change, and one that you would want to avoid if possible.
If the new piece is really simple, perhaps it could be a global function. E.g. print, min, abs, isKnownUniquelyReferenced, etc. But only if there's no grouping that makes sense. There are exceptions to look out for:
If your code repeats a common prefix, naming pattern, etc., that's a strong indication that a logical grouping exists, which could be better expressed as unification under a common namespace. For example:
func formatDecimal(_: Decimal) -> String { ... }
func formatCurrency(_: Price) -> String { ... }
func formatDate(_: Date) -> String { ... }
func formatDistance(_: Measurement<Distance>) -> String { ... }
Could be better expressed if these functions were grouped under a common umbrella. In this case, we don't need instance state, so we don't need to use instance methods. Additionally, it would make sense to have an instance of FormattingUtils (since it has no state, and nothing that could use that state), so outlawing the creation of instances is probably a good idea. An empty enum does just that.
enum FormatUtils {
func formatDecimal(_: Decimal) -> String { ... }
func formatCurrency(_: Price) -> String { ... }
func formatDate(_: Date) -> String { ... }
func formatDistance(_: Measurement<Distance>) -> String { ... }
}
Not only does this logical grouping "make sense", it also has the added benefit of bringing you one step closer to supporting dependancy injection for this type. All you would need is to extract the interface into a new FormatterUtils protocol, rename this type to ProdFormatterUtils, and change dependant code to rely on the protocol rather than the concrete type.
If you find that you have code like in case 1, but also find yourself repeating the same parameter in each function, that's a very strong indication that you have a type abstraction just waiting to be discovered. Consider this example:
func enableLED(pin: Int) { ... }
func disableLED(pin: Int) { ... }
func checkLEDStatus(pin: Int) -> Bool { ... }
Not only can we apply the refactoring from point 1 above, but we can also notice that pin: Int is a repeated parameter, which could be better expressed as an instance of a type. Compare:
class LED { // or struct/enum, depending on the situation.
let pin: Int
init(pin: Int)? {
guard pinNumberIsValid(pin) else { return nil }
self.pin = pin
}
func enable() { ... }
func disable() { ... }
func status() -> Bool { ... }
}
Compared to the refactoring from point 1, this changes the call site from
LEDUtils.enableLED(pin: 1)`
LEDUtils.disableLED(pin: 1)`
to
guard let redLED = LED(pin: 1) else { fatalError("Invalid LED pin!") }
redLED.enable();
redLED.disable();
Not only is this nicer, but now we have a way to clearly distinguish functions that expect any old integer, and those which expect an LED pin's number, by using Int vs LED. We also give a central place for all LED-related operations, and a central point at which we can validate that a pin number is indeed valid. You know that if you have an instance of LED provided to you, the pin is valid. You don't need to check it for yourself, because you can rely on it already having been checked (otherwise this LED instance wouldn't exist).
I want a function that accepts a sequence of Int. Here is what I want to write:
func process(items: Sequence<Int>) {
items.forEach { ... }
}
Error: "Cannot specialize non-generic type 'Sequence'".
Corrected (I think):
func process<S: Sequence>(items: S) where S.Iterator.Element == Int {
items.forEach { ... }
}
Quite a bit more verbose.
I know that the Sequence protocol has an associated type of Iterator which has Element. But I'm not quite sure why I have to resolve the Int requirement in such a weird way.
What are the underlying concepts that make the first version not work but the second? What does the error mean?
Your question is to do with the difference between generic types and associated types. See here (sections titled "Generic Types", "Associated Types") for a basic explanation of their purposes in Swift. Protocols, like Sequence, use associated types, rather than generic types. Your first code sample would make sense if Sequence was a concrete class with a generic type - this difference should explain the error message.
As for why protocols use associated types, rather than generic types, see the top answer to this question. Essentially, though they seem to serve the same purpose, associated types are meant to be more flexible and descriptive, where generic types are about implementation. This makes your code sample more verbose, but overall, makes many code samples simpler.
In fact, from the Sequence source code, Sequence has an associated type Iterator, which conforms to the IteratorProtocol protocol, which in turn has its own associated type Element (which can be any type).
Why are you not using an array of Int?
func process(items: [Int]) {
items.forEach { ... }
}
You can use Variadic Parameters:
func process(items: Int...) {
items.forEach { (item) in
//do stuff with your 'item'
}
}
I have the following class which represents a custom array structure:
class MyArrayClass {
...
}
Now I want to create an extension on this class to make it type save. I would like to do something like this:
extension MyArrayClass<T> {
func getAtIndex(i:Int) -> T {
return self.getAtIndex(i) as! T
}
}
Is it possible to extend a class with a generic parameter?
No, you can't extend a class so as to change it from nongeneric to generic or vice versa. However, it is hard to see why you didn't just make this class generic to start with. In other words, instead of trying to this with an extension, do it with your original class declaration.
Alternatively, you can make individual methods of your nongeneric class generic. For example, getAtIndex could be generic even if MyArrayClass is not.
However, guessing what sort of thing you're probably up to, I think a generic MyArrayClass is going to make the most sense.
if I want to add something to the implementation of
public static function createPopUp(parent:DisplayObject,
className:Class,
modal:Boolean = false,
childList:String = null,
moduleFactory:IFlexModuleFactory = null):IFlexDisplayObject
{
return impl.createPopUp(parent, className, modal, childList, moduleFactory);
}
do I have to put all the arguments in my function declaration or does it pick them up implicitly?
Yes - ActionScript doesn't support method overloading only overriding, in which case your method's signature must exactly match that of the overridden method.
But you are trying to override a static method which is not possible in ActionScript at all. If you want something like in the code snippet create your class not inheriting anything, put a static createPopUp method inside and let it call static createPopUp method from the class you want to decorate and call your class'es static method instead of the original one.
This impossibility to sensible inherit (or inherit at all) static methods is one of the reasons why one should try to restrain from using statics as much as possible - statics take away the power of inheritance from OO languages.
Could someone share the way how this should be designed:
Let's say I have some data model, which is built using Entries.
Basically, I have one abstract class Entry (or interface IEntry - that's not so important for the case) and have several implementations of this class - MovieEntry, SoundEntry, FoodEntry, whatever...
Each of those is a wrapper for some data (url, description, number of calories, etc) and this data is grouped together in each corresponding class.
Now - if I wish to display the data for the entries on the screen (let's say movie posters and annotations for the MovieEntry) - how should I design that?
Obviously I could provide another interface / abstract class and call it DrawableEntry (and it would inherit Sprite) and then build a bunch of classes like DrawableMovieEntry and DrawableSoundEntry which could look like:
class DrawableMovieEntry extends DrawableEntry { // which also extends 'Sprite'
private movieEntry:MovieEntry;
public override function draw(backend:*) {
// Draw everything using the 'movieEntry' reference
// stored.
};
But this seems to be kind of an overkill for a small application.
Another approach is to make the MovieEntry, SoundEntry, ... extend sprite and provide the drawing implementations themselves - but this is obviously bad, because data becomes strongly coupled with it's visualization routines.
So - how should this be done? Maybe MVC approach has something to offer for this case?
Your use case seems to be the perfect example for the Strategy pattern or the Command pattern.
Strategy being the simpler one, here is an example:
Create an IDrawStrategy interface like this:
package {
public interface IDrawStrategy {
function draw( obj:Object ) : void;
}
}
Implement several DrawStrategies:
package {
public class SoundEntryDrawStrategy implements IDrawStrategy {
public function draw (obj:Object) : void {
// cast obj to SoundEntry and do all the drawing necessary,
// or fail if obj is null or not a SoundEntry
}
}
}
package {
public class MovieEntryDrawStrategy implements IDrawStrategy {
public function draw (obj:Object) : void {
// cast obj to MovieEntry and do all the drawing necessary
// or fail if obj is null or not a MovieEntry
}
}
}
etc.
Then add a new member to your base Entry class:
private var _drawStrategy:IDrawStrategy;
and create a setter:
public function set drawStrategy ( strat:IDrawStrategy ) : void {
_drawStrategy = strat;
}
and a draw method:
public function draw () : void {
_drawStrategy.draw( this );
}
You can now assign and execute the fitting strategies to each of your entries:
var mov:MovieEntry = new MovieEntry();
mov.drawStrategy = new MovieEntryDrawStrategy();
mov.draw();
BTW the Sprite you draw the information in can, but doesn't have to, be a member of the DrawStrategy class, but if you wanted to add a clear() method later, it would be better to keep a reference ;).
The entries you build your data model with are, among others, referred to as value objects (VO) or data value objects (DVO). To answer your last question first, I'd never have a VO extend something other than a base VO class, so don't extend Sprite, you'll regret it later.
Over to the hierarchy. You're extending the abstract class Entry to create concrete subclasses, but since you also mention a possible interface, I'm not sure you should use extend. Only use a common base class if your value objects actually share common properties. If every entry has a title property, fine, put that one in Entry and subclass it. If your abstract would be empty, I'd recommend using a marker (=empty) interface instead.
I have a common marker interface for value objects, that have more specific subinterfaces to add features like xml parsing or composition. Once you start using interfaces for this, it's easy to enhance.
Then the displaying. There's not one right answer to this one, the more because your example is still pretty broad. But I'd pass the VO to the object as a whole, through a method that states that it's going to store the VO and redraw itself.
interface IEntryDisplay {
redrawWithEntry(entry:IEntry):void;
}
Use the IEntry interface to pass the object as a whole. In your implementation, use an if cascade with is Type conditions to do the drawing.
public function redrawWithEntry(entry:IEntry):void {
this.entry = entry;
if (entry is MovieEntry) {
title.text = MovieEntry(entry).title;
} else if (entry is SoundEntry) {
title.text = "(Sound) "+SoundEntry(entry).fileName;
}
}
If you decide to use a base class for the Entry hierarchy, use that one instead of the interface. You want your methods asking for the value object type that is as close to the needed object as neccessary.
Because you store the entry in your display class, it's easy to pass along some time later when you click the display or when you want to have it do something else.
Does this help?