Haxe: how to declare "static" methods in an Interface? - interface

This question has been asked (and probably answered) in the old Haxe forums on babble ... but it appears that that entire forum system no longer functions. Therefore, I'm asking here:
In Haxe, I need to declare an "Interface" to a class which includes a static function, "instance()." But when I do so:
You can't declare static fields in interfaces
So I remove the word "static" from public function instance() [...], and I get this:
Field instance needed by [...] is missing.
Apparently a "Catch-22." But there obviously must be some easy solution. What is it?

As you stated the language doesn't allow for static fields on interfaces. The choice is intentional. Another thing that doesn't exist is inheriting static fields.
There are several ways to structure your code to avoid such usage that in my point of view it doesn't give you many advantages. A factory pattern or DI approach (I suggest the minject library) seems the most obvious.
Given the comment below go for a typedef instead of an interface:
typedef GetInstance = Void -> Void;
You can pass that typedef around the same as an interface with the advantage that you can use both static and instance methods to satisfy that signature.

Check out the Singleton library. Any class that implements Singleton will automatically declare a static "instance" variable and corresponding getter function.
Note: as of this writing, the Haxelib version (1.0.0) is out of date. Download the Git version instead.

Related

Swift: Constant's internal implementation

In swift, how is constants implemented?
I read this article, which says
In Swift, constants are generally implemented as (inlined) function calls.
I am not clear of this statement.
Does Swift use a special approach to make constants?
Could anyone explain?
Are you familiar with "getter" and "setter" methods from other languages, such as Java? If a variable is made public in a language like Java, it's exposed to other classes to access directly. In the future, if this variable has to be changed, there's no way to do so without changing all of the other classes dependent upon. With getter/setter methods, dummy implementations can be made that don't do anything besides read/write the value. In the case that a change needs to be made, the implementation of these methods can be changed without effecting the public API of the class.
Swift implements variables with "properties", which are like a backing private variable with public getter/setter methods that are automatically generated. In the future, you can replace a property with a computer property with a special getter/setter implementation, without effecting the public API of the class, just like before. The difference here is that you don't need to write all of the default getters/setters yourself.

What's the correct way of thinking C# protected accessor in swift?

In c# we have the protected accessor which allows class members to be visible on inherited clases but not for the rest.
In Swift this doesn't exist so I wonder what's a correct approach for something like this:
I want to have a variable (internal behavior) and and a public method using this variable on a base class. This variable will be used also on inherited clases.
Options I see
Forget about base class and implement variable and methods everywhere I need it. WRONG, duplicated code
Implement inheritance by composition. I'd create a class containing common methods and this will be used by composition instead of inheritance. LESS WRONG but still repeating code that could be avoided with inheritance
Implement inheritance and make variable internal on base class. WRONG since exposes things without any justification except allowing visibility on inherited clases.
Implementation Details for Base Class
I want to have a NSOperationQueue instance and and a public method to cancel queued operations. I add new operations to this queue from inherited classes.
In Swift the correct answer is almost always protocols and extensions. It is almost never inheritance. Sometimes Cocoa stands in our way, because there are classes in Cocoa more often than protocols, but the goal is almost always protocols and extensions. Subclassing is our last choice.
Your particular case is confusing because NSOperationQueue already has a public method to cancel queued operations (cancelAllOperations). If you want to protect the queue from outside access (prevent callers from using addOperation directly for instance), then you should put the queue inside another type (i.e. composition), and forward what you want to the queue. More details on the specific problem you're solving would allow us to help suggest other Swift-like solutions.
If in the end you need something that looks like protected or friend, the correct solution is private. Put your subclass or your friend in the same file with the target, and mark the private thing private. Alternately, put the things that need to work together in a framework, and mark the attribute internal. The Swift Blog provides a good explanation of why this is an intentional choice.

Static fields/methods in e

Is there any technical reason I am missing for which e doesn't have static fields/methods?
I've looked up the LRM and there is no mention of anything like this. There are workaround (like this one: http://www.specman-verification.com/index.php?entry=entry060612-105347), but I don't find it a particularly clean approach as it's not nicely encapsulated.
Good question. There should be no such technical reasons to not have it, and it might be a good idea to add static members to e structs. Its semantics would just need to be carefully considered, because of the aspect-oriented features of e, which are irrelevant to some other languages that have static members (for example, one question that would need to be answered is whether static methods can be extended, e.g., with is also or not).
However, it doesn't seem very critical to me, because a static field is, effectively, no more than a global field (or method, or any other kind of struct member) that belongs to a given struct's namespace. So, even without having static members, an easy workaround is to add such a member to global (or to sys), and make sure that its name has a prefix that makes it clear to "belong" to a given struct.
There is an important point, though, which does make static members more than just a member of global. In e, like in C++, there are template types. A static member of a template would be something that, on the one hand, is shared by all instance objects of a given template instance type, but on the other hand, would exist separately for each template instance (each one of which being a separate struct).
Not sure if the port-based workaround suggested at the above link is any better. I see it as an overkill.
Actually, in my previous answer I am missing an important point, which does make static members more than just a member of global.
In e, like in C++, there are template types. A static member of a template would be something that, on the one hand, is shared by all instance objects of a given template instance type, but on the other hand, would exist separately for each template instance (each one of which being a separate struct).
By the way static struct members were added to the language in Specman v15.2. They are handy especially in configuration structs that are well, static:
extend packet_s {
static max_address : uint = 0x1000;
};
-- Change max_address for all instances
on xxx { packet_s::max_address = 0x2000; };
A static field can't be generated, physical(%) or used in when subtypes. Here's some comments from the teamspecman blog : Static members in e
I think the main reason why e doesn't have static struct members yet is the fact that you always have global and sys singletons as well as top unit of your specific module (which means better encapsulation), where the 'static' information can be placed. There is no special technical reason for that, besides some complexity in defining exact semantics.
As a syntactic sugar for the unit access, you can always wrap it with very basic single-word macro - it will not be completely seamless, because this magic word will always be required vs. natively visible static struct members of 'me', but still very easy to use.

Can one declare a static method within an abstract class, in Dart?

In an abstract class, I wish to define static methods, but I'm having problems.
In this simple example
abstract class Main {
static String get name;
bool use( Element el );
}
class Sub extends Main {
static String get name => 'testme';
bool use( Element el ) => (el is Element);
}
I receive the error:
function body expected for method 'get:name' static String get name;
Is there a typo in the declaration, or are static methods incompatible with abstract classes?
Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).
If you want a static method in class Main you have to fully define it there and always call it like Main.name
== EDIT ==
I'm sure I read or heard some arguments from Gilad Bracha about it but can't find it now.
This behaviour is IMHO common mostly in statically typed languages (I don't know many dynamic languages). A static method is like a top level function where the class name just acts as a namespace. A static method has nothing to do with an instantiated object so inheritance is not applicable. In languages where static methods are 'inherited' this is just syntactic sugar. Dart likes to be more explicit here and to avoid confusion between instance methods and static methods (which actually are not methods but just functions because they don't act on an instance). This is not my primary domain, but hopefully may make some sense anyways ;-)
Looks like you are trying to 'override' a static method. I'm not sure what you are trying to achieve there. I'm not aware of any OO languages that support that (and not sure how they could).
A similar question in Java might help clarify Polymorphism and Static Methods
Note also that it is considered bad practice to refer to statics from an instance of the class in Java (and other OO languages). Interestingly I noticed Dart does not let you do this so is in effect removing this bad practice entirely.
So you couldn't even fool yourself into thinking it would behave polymorphically in Dart because you can't call the static from the instance.

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.