What is a "marker protocol" in Swift? - swift

I was searching through some Swift open source code and have now seen the term "marker protocol" pop up twice. From context I'm inferring it as a protocol that exists for code readability reasons, not actually to enforce rules. Can anyone explain exactly what a "marker protocol" is AND why it is used?

Marker protocol is a design pattern borrowed from other object-oriented programming languages that allow protocols or interfaces. The idea is to mark a class for use in a specific way, but without requiring the class to provide any functionality by implementing specific methods. For example, Java used this approach to mark classes serializable.
Here is an example:
protocol Marker {}
class One : Marker {
...
}
class Two { // No marker
...
}
...
if (myObj is Marker) {
... // Objects of class One will pass
... // Objects of class Two will not pass
}
This technique is becoming less relevant when the need to mark classes is addressed explicitly by language. For example, Java could have used annotations for dealing with serializability, in the same way that C# did it using attributes, but the feature had not been available at the time.
Swift is an evolving language that has attributes, but all of them are pre-defined. An addition of user-defined attributes will eliminate the need for marker protocols.

Related

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.

Typescript best practices : Interfaces versus Classes [duplicate]

In C# there's a quite huge difference between interfaces and classes. Indeed, a class represents a reference-type, so that we can actually create objects modeled on that class, while interfaces are meant to be contracts that a class sign to in order to ensure the existence of a certain behavior. In particular we can't create instances of interfaces.
The whole point with interfaces is to expose behavior. A class implements it by giving one explicit implementation of said behavior.
In that case, although interfaces may contain properties, most of the time we care about interfaces because of behavioral issues. So most of the type, interfaces are just contracts of behavior.
On TypeScript, on the other hand, I've seem something that made me quite uneasy, and in truth I've seen this more than once, which is the reason for this question.
In one tutorial I saw this:
export interface User {
name: string; // required with minimum 5 chracters
address?: {
street?: string; // required
postcode?: string;
}
}
But wait a minute. Why User is an interface? If we think like C#, User shouldn't be an interface. In truth, looking at it, it seems like we are defining the data type User, instead of a contract of behavior.
Thinking like we do in C#, the natural thing would be this:
export class User {
public name: string;
public address: Address;
}
export class Address {
public street: string;
public postcode: string;
}
But this thing of using interfaces like we do with classes, to just define a data type, rather than defining a contract of behavior, seems very common in TypeScript.
So what interfaces are meant for in TypeScript? Why do people use interfaces in TypeScript like we use clases in C#? How interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
Consider that in Javascript, data is often exchanged as plain objects, often through JSON:
let data = JSON.parse(someString);
Let's say this data is an array of User objects, and we'll pass it to a function:
data.forEach(user => foo(user))
foo would be typed like this:
function foo(user: User) { ... }
But wait, at no point did we do new User! Should we? Should we have to write a class User and map all the data to it, even though the result would be exactly the same, an Object with properties? No, that would be madness just for the sake of satisfying the type system, but not change anything about the runtime. A simple interface which describes how the specific object is expected to look like (to "behave") is perfectly sufficient here.
I also came to Typescript from a C# background and have wondered the same things. I was thinking along the lines of POCOs (is POTO a thing?)
So what interfaces are meant for in TypeScript?
The Typescript Handbook seems to say that interfaces are meant for "defining contracts within your code".
Why do people use interfaces in TypeScript like we use classes in C#?
I agree with #deceze's answer here.
John Papa expands on the subject of classes and interfaces on his blog. He suggests that classes are best suited for "creating multiple new instances, using inheritance, [and] singleton objects". So, based on the intent of Typescript interfaces as described in the Typescript Handbook and one man's opinion, it would appear that classes are not necessary to establish contracts in Typescript. Instead, you should use interfaces. (Your C# senses will still be offended.)
Interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
If I understand the question, you are asking if interfaces should establish contracts of behavior or contracts of structure. To this, I would answer: both. Typescript interfaces can still be used the same way interfaces are used in C# or Java (i.e. to describe the behavior of a class), but they also offer the ability to describe the structure of data.
Furthermore, my coworker got on me for using classes instead of interfaces because interfaces produce no code in the compiler.
Example:
This Typescript:
class Car implements ICar {
foo: string;
bar(): void {
}
}
interface ICar {
foo: string;
bar(): void;
}
produces this Javascript:
var Car = (function () {
function Car() {
}
Car.prototype.bar = function () {
};
return Car;
}());
Try it out
Interfaces in typescript are similar to interfaces in C# in that they both provide a contract. However opposed to C# interfaces which only contain methods typescript interfaces can also describe fields or properties that objects contain. Therefore they can also be used for things which are not directly possible with C# interfaces.
A major difference between interfaces and classes in typescript is that interfaces don't have a runtime representation and there won't be any code emitted for them. Interfaces are very broadly usable. For example you can use object literals to construct objects with satisfy an interface. Like:
let user: User = {
name: 'abc',
address: {
street: 'xyz',
},
};
Or you can assign any data objects (e.g. received through JSON parsing) to an interface (but your pre-checks should assert that it's really valid data). Therefore interfaces are very flexible for data.
On the other hand classes have a type associated at runtime to them and there is code generated. You can check the type at runtime with instanceof and there's a prototype chain set up. If you define User as a class it won't be a valid user unless you call the constructor function. And you can't just define any kind of suitable data to be a User. You would need to create a new instance and copy the properties over.
My personal rule of thumb:
If I'm dealing with pure data (of varying sources) I use interfaces
If I'm modelling something which has an identity and state (and probably attached methods to modify the state) I'm using a class.
How interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
Interfaces in TypeScript are shape contracts, describing the expected structure of an object. If a value has a certain interface annotation, you expect it to be an object featuring the members defined in the interface. Members can be values or functions (methods). Generally, their behavior (function bodies) is not part of the contract. But you can specify if they are readonly or not.
So what interfaces are meant for in TypeScript? Why do people use interfaces in TypeScript like we use clases in C#?
Typescript interfaces can play the same role as C# interfaces if they are expected to be implemented by TypeScript classes.
But not only a class can implement an interface; any kind of value can:
interface HelloPrinter {
printHello(): void
}
The following object is not a class but nevertheless implements the interface:
{
printHello: () => console.log("hello")
}
Thus we can do
const o: HelloPrinter = {
printHello: () => console.log("hello")
}
and the TypeScript compiler won't complain.
The object implements our interface without forcing us to write a class.
Working with interfaces is more lightweight than working with (interfaces and) classes.
But if you need to know the type name (class/interface name) during runtime then classes are the right choice, because interface names are only known at compile time.
Using only the native deserialization mechanism, you cannot deserialize an instance of a specific class. You can only deserialize into a plain-old-javascript-object. Such objects can adhere to typescript interfaces but cannot be an instance of a class. If you need to deal with data that crosses a serialization boundary such as data expected from a webservice, use interfaces. If you need to generate new instances of such values yourself, just construct them literally or create a convenience function that returns them - objects that adhere to that interface.
A class can itself implement an interface, but it might get confusing if you expect to deal with both locally constructed class instances AND deserialized, reconstituted plain objects. You'd never be able to rely on the class-basis of the object and so there'd be no benefit of also defining it as a class for that exact purpose.
I've had success in creating a ServerProxy module responsible for sending code back and forth from a webservice - the webservice call and the returned result. If you're binding to knockout models or similar, you can have a class that encapsulates the ui-bound model with a constructor that knows how to lift a returned plain-old-javascript-object that adheres to the webservice's interface-only contract into an instance of your model class.

Abstract methods in Swift?

I have few questions for Swift developers regarding the concept of abstract classes.
How do you define an abstract class in Swift? Is there any way to prevent a class from being instantiated, while providing an initializer for its subclasses to use?
How do you define abstract methods, while implementing others? When defining abstract methods, Apple generally points you to protocols (interfaces). But they only solve the first part of my question, since all of the methods they define are abstract. What do you do when you want to have both abstract and non-abstract methods in your class?
What about generics? You might have thought about using protocols together with extensions (categories). But then there is an issue with generics because protocols can't have generic types, only typealiases.
I have done my homework and I know about solving these issues using methods, such as fatalError() or preconditionFailure() in the superclass and then overriding them in a base class. But that seems like ugly object design to me.
The reason I'm posting this is to find out whether there exists more general and universal solution.
Thanks in advance,
Petr.
As of today (April 7, 2016), the proposal to introduce abstract classes and methods to Swift (SE-0026) has been deferred.
Joe Groff posted the following in swift-evolution-announce on March 7, 2016:
The proposal has been deferred from Swift 3. Discussion centered around whether abstract classes fit in the direction of Swift as a "protocol-oriented" language. Beyond any religious dogmas, Swift intends to be a pragmatic language that lets users get work done. The fact of the matter today is that one of Swift's primary target platforms is the inheritance-heavy Cocoa framework, and that Swift 2's protocols fall short of abstract classes in several respects [...].
We'd like to revisit this feature once the core goals of Swift 3 have been addressed, so we can more accurately consider its value in the context of a more complete generics implementation, and so we can address the finer points of its design.
I encourage you to read the full email, but I think the conclusion is the same as what you came up with in your question: we're currently stuck with the Objective-C way of doing things (raising exceptions).
There is no Abstract concept in Swift. But we can achieve that scenario by using Inheritance concept like the code below:
class ParentVC:UIViewController {
func loadInformation() {
}
}
class ChildVC:ParentVC {
// This is an Abstract Method
override func loadInformation() {
}
}
How do you define abstract methods, while implementing others?
The "swifty" way of achieving this is combining protocols and extensions, sometimes also typealiases. For data, you are going to define abstract properties in your protocol, then re-define them in a concrete class, then unite all that using a typealias and the & operator:
protocol BaseAbstract: class {
var data: String { get set }
func abstractMethod()
func concreteMethod()
}
extension BaseAbstract {
// Define your concrete methods that use the abstract part of the protocol, e.g.:
func concreteMethod() {
if !data.isEmpty {
abstractMethod()
}
}
}
class BaseImpl {
// This is required since we can't define properties in extensions.
// Therefore, we define a class with a concrete property and then
// unite it with the protocol above in the typealias below.
var data: String = "Hello, concrete!"
}
typealias Base = BaseAbstract & BaseImpl // et voila, `Base` is now ready to be subclassed
class Subclass: Base {
func abstractMethod() { // enforced by the compiler
}
}
(It can get tricker if you have generics in this scenario. Currently trying to figure it out.)

When the use of an extension method is a good practice? [duplicate]

This question already has answers here:
Closed 13 years ago.
Extension methods are really interesting for what they do, but I don't feel 100% confortable with the idea of creating a "class member" outside the class.
I prefer to avoid this practice as much as I can, but sometimes it looks better to use extension methods.
Which situations you think are good practices of usage for this feature?
I think that best place for extension methods is "helper" methods or "shortcuts" that make existing API easier and cleanier by providing default values to arguments of existing methods or hiding repeating chains of method calls.
Contrary to the common beliefs that you can "extend" classes for which you do not have access to the source code, you cannot. You have no access to private methods and objects, all you can do is to polish public API and bend it to your likings (not recommended).
They're great for interfaces (where you can add "composite" behaviour which only uses existing methods on the interface) - LINQ to Objects is the prime example of this.
They're also useful for creating fluent interfaces without impacting on the types that are being used. My favourite example is probably inappropriate for production code, but handy for unit tests:
DateTime birthday = 19.June(1976) + 8.Hours();
Basically anywhere that you don't want to or can't add behaviour to the type itself, but you want to make it easier to use the type, extension methods are worth considering. If you find yourself writing a bunch of static methods to do with a particular type, think about whether extension methods wouldn't make the calls to those methods look nicer.
When the class is not extensible and you don't have control over the source code. Or if it is extensible, but you prefere to be able to use the existing type instead of your own type. I would only do the latter if the extension doesn't change the character of the class, but merely supplies (IMO) missing functionality.
In my opinion, extension methods are useful to enhance the readability and thus maintainability of code. They seem to be be best on entities where either you have no access to the original class, or where the method breaks "Single Responsibility Principle" of the original class. An example of the latter we have here is DSLs. The DSL models are extended with extension methods are used to make T4 templating easier but no methods are added the model unless they are specifically related to the model.
The ideal use for them is when you have an interface that will be implemented in many places, so you don't want to put a huge burden on implementors, but you want the interface to be convenient to use from the caller's perspective as well.
So you put the "helpers" into a set of extension methods, leaving the interface itself nice and lean.
interface IZoomable
{
double ZoomLevel { get; set; }
}
public static void SetDefaultZoom(this IZoomable z)
{
z.ZoomLevel = 100;
}
Extension methods are a great way to add functionality to classes that you don't own (no source), are in the framework or that you don't want to inherit for whatever reason.
I like them, but you are right. They should be used judiciously.

What is an empty interface used for

I am looking at nServiceBus and came over this interface
namespace NServiceBus
{
public interface IMessage
{
}
}
What is the use of an empty interface?
Usually it's to signal usage of a class. You can implement IMessage to signal that your class is a message. Other code can then use reflection to see if your objects are meant to be used as messages and act accordingly.
This is something that was used in Java a lot before they had annotations. In .Net it's cleaner to use attributes for this.
#Stimpy77 Thanks! I hadn't thought of it that way.
I hope you'll allow me to rephrase your comment in a more general way.
Annotations and attributes have to be checked at runtime using reflection. Empty interfaces can be checked at compile-time using the type-system in the compiler. This brings no overhead at runtime at all so it is faster.
Also known as a Marker Interface:
http://en.wikipedia.org/wiki/Marker_interface_pattern
In java Serializable is the perfect example for this. It defines no methods but every class that "implements" it has to make sure, that it is really serializable and holds no reference to things that cannot be serialized, like database connections, open files etc.
In Java, empty interfaces were usually used for "tagging" classes - these days annotations would normally be used.
It's just a way of adding a bit of metadata to a class saying, "This class is suitable for <this> kind of use" even when no common members will be involved.
Normally it's similar to attributes. Using attributes is a preferred to empty interfaces (at least as much as FxCop is aware). However .NET itself uses some of these interfaces like IRequiresSessionState and IReadOnlySessionState. I think there is performance loss in metadata lookup when you use attributes that made them use interfaces instead.
An empty interface acts simply as a placeholder for a data type no better specified in its interface behaviour.
In Java, the mechanism of the interface extension represents a good example of use. For example, let's say that we've the following
interface one {}
interface two {}
interface three extends one, two {}
Interface three will inherit the behaviour of 'one' and 'two', and so
class four implements three { ... }
has to specify the two methods, being of type 'three'.
As you can see, from the above example, empty interface can be seen also as a point of multiple inheritance (not allowed in Java).
Hoping this helps to clarify with a further viewpoint.
They're called "Mark Interfaces" and are meant to signal instances of the marked classes.
For example... in C++ is a common practice to mark as "ICollectible" objects so they can be stored in generic non typed collections.
So like someone over says, they're to signal some object supported behavior, like ability to be collected, serialized, etc.
Been working with NServiceBus for the past year. While I wouldn't speak for Udi Dahan my understanding is that this interface is indeed used as a marker primarily.
Though I'd suggest you ask the man himself if he'd had thoughts of leaving this for future extension. My bet is no, as the mantra seems to be to keep messages very simple or at least practically platform agnostic.
Others answer well on the more general reasons for empty interfaces.
I'd say its used for "future" reference or if you want to share some objects, meaning you could have 10 classes each implementing this interface.
And have them sent to a function for work on them, but if the interface is empty, I'd say its just "pre"-work.
Empty interfaces are used to document that the classes that implement a given interface have a certain behaviour
For example in java the Cloneable interface in Java is an empty interface. When a class implements the Cloneable interface you know that you can call run the clone() on it.
Empty interfaces are used to mark the class, at run time type check can be performed using the interfaces.
For example
An application of marker interfaces from the Java programming language is the Serializable interface. A class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. The ObjectOutputStream private method writeObject() contains a series of instanceof tests to determine writeability, one of which looks for the Serializable interface. If any of these tests fails, the method throws a NotSerializableException.
An empty interface can be used to classify classes under a specific purpose. (Marker Interface)
Example : Database Entities
public interface IEntity {
}
public class Question implements IEntity {
// Implementation Goes Here
}
public class Answer implements IEntity {
// Implementation Goes Here
}
For Instance, If you will be using Generic Repository(ex. IEntityRepository), using generic constraints, you can prevent the classes that do not implement the IEntity interface from being sent by the developers.