Simple container bindings in Swift? - swift

Disclaimer: I'm still learning Swift so forgive me if I haven't understood certain concepts/capabilities/limitations of Swift.
With the Swinject framework, if you wanted to bind a protocol to a class - it seems you have to return the class instance in a closure such as:
container.register(Animal.self) { _ in Cat() }
Is is possible to be able to instead pass in two types to the register() method and have the framework instantiate the class for you? It would need to recursively see if that class had any initializer dependencies of course (Inversion of Control).
This is possible in the PHP world as you have the concept of reflection, which allows you to get the class types of the dependencies, allowing you instantiate them on the fly. I wonder if Swift has this capability?
It would be much nicer to write this:
container.register(Animal.self, Cat.self)
This would also allow you to resolve any class from the container and have it's dependencies resolved also (without manually registering the class):
container.resolve(NotRegisteredClass.self)
Note: This only makes sense for classes that do not take scalar types as a dependency (as they need to be explicitly given of course).

The second case - resolving a type without the explicit registration - is currently not possible because of Swift's very limited support for the reflection.
However, there is a SwinjectAutoregistration extension which will enable you to write something very close to your first example:
container.autoregister(Animal.self, initializer: Cat.init)

Related

When I should define operations-type-traits for a USTRUCT

For some USTRUCT structs within UnrealEngine, type traits TStructOpsTypeTraits<T> are defined. These provide a list of bools (encapsulated in an enumeration) about the implemented capabilities of struct T.
What is the usage of those traits?
When I should define those traits for my custom USTRUCTs within my project?
*Example usage from within the Engine:
struct TStructOpsTypeTraitsBase2
{
enum
{
WithZeroConstructor = false, // struct can be constructed as a valid object by filling its memory footprint with zeroes.
WithNoInitConstructor = false, // struct has a constructor which takes an EForceInit parameter which will force the constructor to perform initialization, where the default constructor performs 'uninitialization'.
WithNoDestructor = false, // struct will not have its destructor called when it is destroyed.
WithCopy = !TIsPODType<CPPSTRUCT>::Value, // struct can be copied via its copy assignment operator.
// ...
}
}
Which is used like
template<>
struct TStructOpsTypeTraits<FGameplayEffectContextHandle> : public TStructOpsTypeTraitsBase2<FGameplayEffectContextHandle>
{
enum
{
WithCopy = true, // Necessary so that TSharedPtr<FGameplayEffectContext> Data is copied around
WithNetSerializer = true,
WithIdenticalViaEquality = true,
};
};
It seems that traits are used for USTRUCTs that are used in blueprints; and that they are required for structs which have a NetSerialize() function. I made spot checks:
WithIdenticalViaEquality -> UScriptStruct::HasIdentical() -> EStructFlags::STRUCT_IdenticalNative is used only in ::IdenticalHelper() which is intended for Blueprints
EStructFlags::STRUCT_NetSerializeNative is used for error messages (when the structs are used in blueprints) and in FObjectReplicator and FRepLayout, where this trait is required to be present for custom property replication
the description of TStructOpsTypeTraitsBase2 seems to tell, that these traits are only important, when the USTRUCTs are used within blueprints
type traits to cover the custom aspects of a script struct
UnrealEngine defines also a number of specialized traits for its container classes (e.g. TTypeTraitsBase). A comparison with c++ type_traits might be meaningful.
Many of the features available "out-of-the-box" in Unreal Engine 4 (e.g. replication, initialization, serialization, etc.) rely on information specific to each class. This allows different classes to - for example - customize how to serialize their own data.
For classes inheriting from the base UObject class, all the needed information are stored into properties or returned by overridable methods. For example, if you want to customize how your UObject-derived class manages serialization, you can simply override its virtual Serialize() method. This is enough for UE4 to be able to invoke your custom implementation when it need to serialize an instance of your class.
The problem with structs in UE4, is that they don't inherit from a common base class/interface. So UE4 doesn't have any pre-declare property or method to call. Trying to call an undeclared method will of course cause a compilation error in C++. Following the previous example on the custom serialization - UE4 can't in general invoke the Serialize() method on structs because some/most of them will not have such method and the compiler will report it as an error.
TStructOpsTypeTraitsBase2 is the solution to the above problem. You declare a specialization of it for your custom structs to inform UE4 of which methods are available. When done, using a mix of template meta-programming and auto-generated code, UE4 will be able to call such methods to provide again out-of-the-box services or allow you to customize default behaviors. For example, declaring WithSerializer = true you're informing UE4 that your struct has a custom Serialize() method and so UE4 will be able to automatically call it every time it needs to serialize an instance of your struct.
TStructOpsTypeTraitsBase2 is not limited to structs used with Blueprints, but is used also with USTRUCT() used in C++.
On when to use it, you need to declare a custom specialization of TStructOpsTypeTraitsBase2 when the default behavior of UE4 on your structure is not what you want (e.g. you want to serialize its data in a different way while the default implementation serializes all the not-transient UPROPERTY() using "standard" formats).
While the "form" is similar, the scope of TStructOpsTypeTraitsBase2 is different than C++ type_traits: type_traits is used by the compiler to inform the program/programmer about platform characteristics. TStructOpsTypeTraitsBase2 is used by the programmer to inform UE4 about available "extra" features of a custom struct.

Best practice for using same functions between classes

In swift, what is best practice for having several functions common to more than one class, where inheritance between those classes isn't feasible?
I'm new to programming so please don't condescend. Its just when I first started learning a few months ago I was told its terrible practice to repeat code, and at the time I was coding in Ruby where I could create a module in which all the functions resided, and then just include module in any class where I wanted to use those functions. As long as all variables in the module's functions were declared in the classes the code worked.
Is there a similar practice in swift, or should I be doing something else like making a bunch of global functions and passing the instance variables to those functions? Please be as specific as possible as I'm gonna follow your advice for all code I write in swift going forward, thanks!
simple answer to your question is protocol
define protocol
protocol ProtocolName {
/* common functions */
func echoTestString()
}
extension ProtocolName {
/* default implementation */
func echoTestString() {
print("default string")
}
}
class conforming to protocol with default implementation
class ClassName: ProtocolName {
}
ClassName().echoTestString() // default string
class conforming to protocol with overriden implementation
class AnotherClass: ProtocolName {
func echoTestString() {
print("my string")
}
}
AnotherClass().echoTestString() // my string
While an opinion, I think this is the right route - use a Framework target. Protocols work too. But with a Framework, you can:
Share across projects
Keep everything local in scope what you need or not
Be agnostic in many ways
If you want to use the "include" Swift verb (and all that comes with it), you pretty much need to use a Framework target. If you want complete splitting of code too. Protocols are used when you are within a single project, do not want to "repeat" code pieces, and know you will always be local.
If what you want is to (a) use protocols across projects, (b) include true separate code, (c) have global functions, while (d) passing instance variables... consider a separate target.
EDIT: Looking at your question title ("using same functions") and thinking about OOP versus functional programming, I thought I'd add something that doesn't change my solution but enhances it - functional programming means you can "pass" a function as a parameter. I don't think that's what you were saying, but it's another piece of being Swifty in your coding.

In Swift OOP design, how do I arrange a commonly-used class?

I am new to Swift and OOP. For example, I have a class that manages the system-wide configurations.
class system_conf {
init()
getValue1()
getValue2()
...
setValue1()
setValue2()
...
reloadValues()
activateX()
activeteY()
...
}
This class should have only one instance and many other classes will use it. What's the recommended way for this case?
Should I pass around this instance?
Should I consider to use Singleton?
Should I use static functions directly?
Should I create a global instance, so every other class can access it directly?
or?
It seems your class is a configuration class. If you intend to pass it to a bunch of classes, you should wonder if you need to write unit tests for them.
If so, assuming you are either using a singleton or static methods or a global var, take a moment to think about how you would mock this configuration class for each of your tests. It's not easy, is it?
If your class is a kind of mediator, a global var or static methods are fine (or any other alternative you suggested). However, in your case, it would be better to pass your object in any initializer/constructor of each class using it. Then, testing would definitely be easier. Also, passing it via an interface is even better: you can mock it super easily (mock up libraries mostly work with interfaces only).
So there is no unique answer to your question. It is just a matter of compromises and scaling. If your app is small, any of the method you listed above is perfectly fine. However, if you app tends to get bigger, a proxy solution would be better for maintainability and testability.
If you fancy reading, you should glance at this article from Misko Hevery, especially this chapter.

In Scala, plural object name for a container of public static methods?

I've written a Scala trait, named Cache[A,B], to provide a caching API. The Cache has the following methods, asyncGet(), asyncPut(), asyncPutIfAbsent(), asyncRemove().
I'm going to have a few static methods, such as getOrElseUpdate(key: A)(op: => B). I don't want methods like this as abstract defs in the Cache trait because I don't want each Cache implementation to have to provide an implementation for it, when it can be written once using the async*() methods.
In looking at Google Guava and parts of the Java library, they place public static functions in a class that is the plural of the interface name, so "Caches" would be the name I would use.
I like this naming scheme actually, even though I could use a Cache companion object. In looking at much of my code, many of my companion objects contain private val's or def's, so users of my API then need to look through the companion object to see what they can use from there, or anything for that matter.
By having a object named "Caches" is consistent with Java and also makes it clear that there's only public functions in there. I'm leaning towards using "object Caches" instead of "object Cache".
So what do people think?
Scala's traits are not just a different name for Java's interfaces. They may have concrete (implemented) members, both values (val and var) and methods. So if there's a unified / generalized / shared implementation of a method, it can be placed in a trait and need not be replicated or factored into a separate class.
I think the mistake starts with "going to have a few static methods". Why have static methods? If you explain why you need static methods, it will help figure out what the design should be.

Pseudo-multiple-inheritance with extension methods on interfaces in C#?

Similar question but not quite the same thing
I was thinking that with extension methods in the same namespace as the interface you could get a similar effect to multiple inheritance in that you don't need to have duplicate code implementing the same interface the same way in 10 different classes.
What are some of the downsides of doing this? I think the pros are pretty obvious, it's the cons that usually come back to bite you later on.
One of the cons I see is that the extension methods can't be virtual, so you need to be sure that you actually do want them implemented the same way for every instance.
The problem that I see with building interface capability via extension methods is that you are no longer actually implementing the interface and so can't use the object as the interface type.
Say I have a method that takes an object of type IBar. If I implement the IBar interface on class Foo via extension methods, then Foo doesn't derive from IBar and can't be used interchangeably with it (Liskov Substitution principle). Sure, I get the behavior that I want added to Foo, but I lose the most important aspect of creating interfaces in the first place -- being able to define an abstract contract that can be implemented in a variety of ways by various classes so that dependent classes need not know about concrete implementations.
If I needed multiple inheritance (and so far I've lived without it) badly enough, I think I'd use composition instead to minimize the amount of code duplication.
A decent way to think about this is that instance methods are something done by the object, while extension methods are something done to the object. I am fairly certain the Framework Design Guidelines say you should implement an instance method whenever possible.
An interface declares "I care about using this functionality, but not how it is accomplished." That leaves implementers the freedom to choose the how. It decouples the intent, a public API, from the mechanism, a class with concrete code.
As this is the main benefit of interfaces, implementing them entirely as extension methods seems to defeat their purpose. Even IEnumerable<T> has an instance method.
Edit: Also, objects are meant to act on the data they contain. Extension methods can only see an object's public API (as they are just static methods); you would have to expose all of an object's state to make it work (an OO no-no).