Except for obvious reasons, such as if by design I do not want certain method, or property, or whatever to be overridden down the inheritance tree, are there other reasons to mark things final in Swift?
For example, are there performance considerations? I recall reading somewhere on SO answers that suggest something along the line.
From Apple's Swift blog: Increasing Performance by Reducing Dynamic Dispatch
Swift allows a class to override methods and properties declared in its superclasses. This means that the program has to determine at runtime which method or property is being referred to and then perform an indirect call or indirect access. This technique, called dynamic dispatch, increases language expressivity at the cost of a constant amount of runtime overhead for each indirect usage.
Using final is one of several ways to improve performance by eliminating such dynamism:
The "final" keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection.
Related
The main goal of defining enumerators is to assign a variable to some numbers and their equal strings as I understand.
We can define var a as an enum everywhere in the initializing section of our Program or Function Block like this:
a:(start,stop,operate);
tough I don't know why we can't see that in tabular view but there there is a big question that:
What is the benefit of defining enumerators as a DUT?
There are 3 main benefits for me:
You can use the same enum in multiples function blocks
You can use TO_STRING on enums declared as DUTs (After enabling it with {attribute 'to_string'} Infosys
You can use refactoring on names of each component, which is impossible with local enums
When defining an enum as a DUT it is available everywhere in your code (global scope).
This is helpful in many cases, but in general it is not good programming practice to have a lot of stuff available in the global scope.
Here is a bit elaboration on the topic.
In addition to the above, one benefit is that if you are using an enumeration for something like FB states, you will be able to see the descriptive status name when the program is running (READING, WRITING, WAITING, ERROR, etc.).
You can see it in the variable declarations section, in-line with your code, or in the watch window. You don’t have to remember what status number was defined in your state machine.
This benefit comes with local enumerations or DUT (global) enumerations.
In addition to other good points already made, there is another big advantage to enumerations : you can use the enumeration as the type of a variable, and when you do that, the compiler will (if {attribute 'strict'} is used in the enumeration declaration, which it probably should) refuse an assignment to that variable of a value that is not allowed by the enumeration.
In other words, you get rid of a whole class of failure modes where the variable ends up having an invalid value due to some coding mistake the compiler cannot catch.
It takes a trivial amount of time to create an enumeration, and it has benefits on many levels. I would say the real question is why not use them whenever a fixed list of meaningful values needs to be expressed.
I have to implement an algorithm which fits perfectly to the procedural design approach. It has no relations with some data structure, it just takes couple of objects, bunch of control parameters and performs complicated operations on them, including creating and modifying intermediate temporal data, subroutines calls, many cpu-intensive data transformations. The algorithm is too specific to include in either parameter object as method.
What is idiomatic way to wrap such algorithms in an OOP language? Define static object with static method that performs calculation? Define class that takes all algorithm parameters as constructor arguments and have result method to return result? Any other way?
If you need more specifics, I'm writing in scala. But any general OOP approach is also applicable.
A static method (or a method on a singleton object in the case of Scala -- which I'm just gonna call a static method because that's the most common terminology) can work perfectly fine and is probably the most common approach to this.
There's some reasons to use other approaches, but they aren't strictly necessary and I'd avoid them unless you actually need an advantage that they give. The reason for this is because static methods are the simplest (if least versatile) approach.
Using a non-static method can be useful because you can then utilize design patterns like the factory pattern. For example, you might have an Operator class with a method evaluate. Now you could have different factories create different Operators so that you can swap your algorithm on the fly. Perhaps a calculator might have an AddOperatorFactory, MultiplyOperatorFactory and so on. Obviously this requires that you are able to instantiate an object that represents the algorithm. Of course, you could just pass a function around directly, as Scala and many other languages allow. Classes allow for inheritance, though, which opens the doors for some design patterns and, well, you're asking about OOP, not Scala specifically.
Also useful is the ability to have state with an object. With static methods, your only options for retaining state are either having global state (ew) or making the user of the static methods keep track of this state (more work for the users). With an instance of an object, you can keep that state inside the instance. For example, if your algorithm is a graph search, perhaps you'd want to allow resuming a search after you find the first match (which obviously requires storing state).
It's not much harder to have to do new MyAlgorithm().doStuff() instead of MyAlgorithm.doStuff(), so if in doubt, I would err on the side of avoiding static methods if you think you'll need the functionality that having an instance offers.
Except for obvious reasons, such as if by design I do not want certain method, or property, or whatever to be overridden down the inheritance tree, are there other reasons to mark things final in Swift?
For example, are there performance considerations? I recall reading somewhere on SO answers that suggest something along the line.
From Apple's Swift blog: Increasing Performance by Reducing Dynamic Dispatch
Swift allows a class to override methods and properties declared in its superclasses. This means that the program has to determine at runtime which method or property is being referred to and then perform an indirect call or indirect access. This technique, called dynamic dispatch, increases language expressivity at the cost of a constant amount of runtime overhead for each indirect usage.
Using final is one of several ways to improve performance by eliminating such dynamism:
The "final" keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection.
I'm sure my terminology is off, so here's an example:
C/C++ has methods and virtual methods. Both have the opportunity to be inlined at compile time.
C#'s CIL has call and callvirt instructions (which closely resemble C++ methods and virtual methods). Although almost all method calls in C# become callvirt (due to langauge snafu) the JIT compiler is able to optimize most back to call instructions and then (if worthwhile) also inline them.
Objective-C method calls are done very differently (and inefficiently); a message object is passed via objc_msgsend every time you call a method, it's a form of dynamic dispatch, and can never be inlined.
Reading up on the language specification for functions for Swift, I don't know if Swift is using the same messaging system as Objective-C or something different.
Sometimes yes, sometimes no. If you have pure swift code, and do not expose your classes/protocols to Objective-C with the #objc decoration, it appears that pure-swift method calls are not dispatched via objc_msgSend, however in other cases they are. If the protocol your swift object adopts is declared in Objective-C, or if the swift protocol is decorated with #objc, then method calls to protocol methods, even from swift objects to other swift objects, are dispatched via objc_msgSend.
The documentation is currently a little thin; I'm sure there are other nuances... but empirically speaking (i.e. I've tried it out) some swift method calls go through objc_msgSend and others don't. I think getting the best performance will be dependent on keeping your code as much pure-swift as possible and crossing the Obj-C/swift boundary as little as possible, and through bottleneck interfaces/protocols, so as to limit the number of swift calls that have to be dispatched dynamically.
I'm sure more detailed docs will emerge sooner or later.
Unlike C++, it is not necessary to designate that a method is virtual in Swift. The compiler will work out which of the following to use:
The performance metrics of course depend on hardware.
Inline the method : 0 ns
Static dispatch: < 1.1ns
Virtual dispatch 1.1ns (like Java, C# or C++ when designated).
Dynamic Dispatch 4.9ns (like Objective-C).
Objective-C of course always uses the latter. The 4.9ns overhead is not usually a problem as this would represent a small fraction of the overall method execution time. However, where necessary developers could seamlessly fall-back to C or C++ where required. This is still somewhat of an option in Swift, however the compiler will analyze which of the fastest can be used and try to decide on your behalf.
One side-effect of this, is that some of the powerful features afforded by dynamic dispatch may not be available, where as this could previously have been assumed to be the case for any Objective-C method. Dynamic dispatch is used for method interception, which is in turn used by:
Cocoa-style property observers.
CoreData model object instrumentation.
Aspect Oriented Programming
With the latest release of Swift, even if an Object is marked as '#objc' or extends NSObject the compiler may still not necessarily use dynamic dispatch. There's a dynamic attribute that can be added to the method to opt-in.
In this video from Google IO 2009, the presenter very quickly says that signatures of methods should return concrete types instead of interfaces.
From what I heard in the video, this has something to do with the GWT Java-to-Javascript compiler.
What's the reason behind this choice ?
What does the interface in the method signature do to the compiler ?
What methods can return interfaces instead of concrete types, and which are better off returning concrete instances ?
This has to do with the gwt-compiler, as you say correctly. EDIT: However, as Daniel noted in a comment below, this does not apply to the gwt-compiler in general but only when using GWT-RPC.
If you declare List instead of ArrayList as the return type, the gwt-compiler will include the complete List-hierarchy (i.e. all types implementing List) in your compiled code. If you use ArrayList, the compiler will only need to include the ArrayList hierarchy (i.e. all types implementing ArrayList -- which usually is just ArrayList itself). Using an interface instead of a concrete class you will pay a penalty in terms of compile time and in the size of your generated code (and thus the amount of code each user has to download when running your app).
You were also asking for the reason: If you use the interface (instead of a concrete class) the compiler does not know at compile time which implementations of these interfaces are going to be used. Thus, it includes all possible implementations.
Regarding your last question: all methods CAN be declared to return interface (that is what you ment, right?). However, the above penalty applies.
And by the way: As I understand it, this problem is not restricted to methods. It applies to all type declarations: variables, parameters. Whenever you use an interface to declare something, the compiler will include the complete hierarchy of sub-interfaces and implementing classes. (So obviously if you declare your own interface with only one or two implementing classes then you are not incurring a big penalty. That is how I use interfaces in GWT.)
In short: use concrete classes whenever possible.
(Small suggestion: it would help if you gave the time stamp when you refer to a video.)
This and other performance tips were presented at Google IO 2011 - High-performance GWT.
At about the 7 min point the speak addresses 'RPC Type Explosion':
For some reason I thought the GWT compiler would optimize it away again but it appears I was mistaken.