PhpStorm: annotation for inherited method return type? - annotations

Using a Behat sub-context class I need to call a method from the main context, e.g. $this->getMainContext()->fooBar(). PhpStorm quite reasonably warns me that fooBar() doesn't exist, because it expects getMainContext() to return an ExtendedContextInterface, not my concrete FeatureContext.
Is there a way to annotate my sub-class to tell PhpStorm that getMainContext() actually returns my concrete class?
One solution is to override getMainContext() just to have a method on which to add my own PHPDoc, thus specifying a different return type, but adding a method just to get nicer code sense in an IDE is horrid.
BTW, I know this is all a bit hacky and that theoretically my sub-context shouldn't depend upon my main context having a particular concrete implementation; in reality though Behat doesn't make that practical.

Using the standard #method annotation for the class works:
/**
* #method FeatureContext getMainContext()
*/
class SubContext extends BehatContext
{
public function foo()
{
$this->getMainContext()->bar();
}
}

Related

Why should we use the 'override' key word in Kotlin for abstact class members?

If the base class has an abstract method or property, than these members must be overriden in the child class. The documentation says that i must use key word 'override' every time for such members, because i must implement methods or initialize properties in the child class. For example:
abstract class Dwelling {
abstract val buildingMaterial: String
abstract fun hasRoom() : Boolean
}
class RoundHut : Dwelling() {
override val buildingMaterial = "Stone"
override fun hasRoom() : Boolean {
return true
}
}
If an abstract method and a property must be overriden and implemented in child class any way (and compiler know this), than why we should write 'override' key word every time?
When you find yourself reading and understanding the implementing class, you have the explicit information that you're currently investigating an overridden one as it's explicitly marked as such. Kotlin likes to make things explicit and the documentation states
[...] we stick to making things explicit in Kotlin. So, Kotlin requires explicit modifiers for overridable members (we call them open) and for overrides
Java has an #Override annotation that is optional and not used by everyone although it has been considered a best practice (even as per Effective Java). Kotlin goes one step further by making it a compiler-enforced requirement.

How can a Swift module/class work around the lack of language support for "protected" members?

I'm faced with a situation where I am defining a reusable base class in a module, and I want to provide certain functions that should be callable only by subclasses, not external users of that subclass.
I'm writing a framework and packaging it as a Swift module. Part of my framework includes a base class that can be subclassed to add functionality, but whereby the derived class also has a further external purpose as well. Imagine defining a new kind of view: it derives from UIView or NSView, then provides additional logic, and is then itself instantiated by another party.
In this case, I'm the one defining the UIView-like class that is intended to be subclassed, and along with it comes a lot of private UIView internal stuff, like measurement, arranging, who knows, internal stuff.
The point is, end users of this new view class don't want to see the internals of the architecture that supported the subclassing, those should be completely inside the black box of what the subclass represents.
And it strikes me that this is now impossible in Swift.
I really don't understand why Swift got rid of protected access control. According to Apple, the function that I want to expose only to subclasses "isn't really useful outside the subclass, so protection isn’t critical".
Am I missing something? Is this a whole class of design patterns that Swift simply cannot support?
One thought that occurs to me is I could perhaps split up the public-public and the private-public parts of my class into two parts, perhaps using protocols, whereby public-public users would only see the public protocol and "private" public users would see the "private" protocol as well. Alas this seems like a lot of engineering for something that used to be free.
FWIW — I've been continually asking for better access control in Swift (including protected) since before there was access control in Swift. Now, 3.5 years after we were told to give the Swift approach to access control a try, Swift has been my primary language for almost 3 of those years and I still think the access control paradigm is clumsy and unable to model concepts that are easy in almost all similar languages.
The largest mitigating factor for me is that Swift has steered me away from ever using inheritance and subclassing 95% of the time, which I think is a good thing. So this issue comes up less than it may have otherwise. But for situations exactly as you are describing, there isn't an equivalent way to accomplish what you are doing using only protocols and protocol extensions, so you are stuck either polluting a public API with possibly harmful internal details, or using some workaround (like the one that follows) which has the smallest possible public API exposure, and simulates what you want at the cost of boilerplate and awkwardness.
That said, the approach I take is somewhat inspired by Objective C, where there is also no real protected access control, but the convention is to declare a public API header (which client code will import and reference) and a special "+Subclassing" header which only subclasses will import in their implementation, giving them visibility into the not-for-public-consumption internals.
In Swift, this isn't directly possible either, but given a class like this:
open class SomeClass {
private var foo: String
private var bar: Data
public init(){
foo = "foo"
bar = Data()
}
private func doInternalThing() {
print(foo)
}
}
You can add a nested "Protected" wrapper via extension (has to be in the same file as your class declaration), which takes an instance of the class (or a subclass) and exposes the protected-level internals as a sort of proxy:
// Create a nested "Protected" type, which can accept an instance of SomeClass (or one of its subclasses) and expose the internal / protected members on it
public extension SomeClass {
public class Protected {
unowned private var someClass: SomeClass
public var foo: String {
get {
return someClass.foo
}
set {
someClass.foo = newValue
}
}
public init(_ someClass: SomeClass) {
self.someClass = someClass
}
public func doInternalThing() {
someClass.doInternalThing()
}
}
}
Outside of the framework, in the client application, the protected members are accessed in a subclass like this:
class SomeSubclass: SomeClass {
private lazy var protected: SomeClass.Protected = { SomeClass.Protected(self) }()
func doSomething() {
protected.foo = "newFoo" // Accesses the protected property foo and sets a new value "newFoo"
protected.doInternalThing() // Prints "newFoo" by calling the protected method doInternalThing which prints the foo property.
}
}
There are pros and cons for this approach. The cons are mainly the amount of boilerplate you need to write to map all your properties and functions from the Protected wrapper to the actual class instance as shown above. Also, there is no avoiding the fact that consumers will see SomeClass.Protected as a publicly visible type, but hopefully it's clear that it shouldn't be used and it's difficult enough to use it arbitrarily that it won't happen.
The pros are that there isn't a lot of boilerplate or pain for clients when creating subclasses, and its easy to declare a lazy "protected" var to get the desired API. It's pretty unlikely that non-subclass would stumble upon or use this API accidentally or unwittingly, and it's mostly hidden as desired. Instances of SomeSubclass will not show any extra protected API in code completion or to outside code at all.
I encourage anyone else who thinks access control — or really in this case, API visibility and organization — to be easier than it is in Swift today to let the Swift team know via the Swift forums, Twitter, or bugs.swift.org.
You can kinda, sorta work around it by separating out the for-subclasses stuff into a separate protocol, like this:
class Widget {
protocol SubclassStuff {
func foo()
func bar()
func baz()
}
func makeSubclassStuff() -> SubclassStuff {
// provide some kind of defaults, or throw a fatalError if this is
// an abstract superclass
}
private lazy var subclassStuff: SubclassStuff = {
return self.makeSubclassStuff()
}()
}
Then you can at least group the stuff that's not to be called in one place, to avoid it polluting the public interface any more than absolutely necessary and getting called by accident.
You can also reconsider whether you really need the subclass pattern here, and consider using a protocol instead. Unfortunately, since protocols can't nest types yet, this involves giving the subclass-specific protocol an Objective-C-style prefixed name:
protocol WidgetConcreteTypeStuff {
...
}
protocol Widget {
var concreteTypeStuff: WidgetConcreteTypeStuff { get }
}

Mark Haxe Class for forced extend?

Is there a compiler meta for Class declaration, that prevents creating Class instance before extending it? In other words - some sort of opposite of #:final meta.
Like so (last line of code):
class A {
// ...
}
class B extends A {
// ...
}
// ...
var b = new B(); // OK
var a = new A(); // induce compiler-error
Simply don't declare a constructor at all for class A
Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:
Here's an example of no constructor. Of note is that A simply doesn't have a constructor, and B simply doesn't call super(). Other than that, everything else works as you'd expect.
Here's an example of a private constructor. You still can't instantiate a new A(), but you do still need to call super() from B's constructor.
Technicalities:
Use of some features (like a default value on a member variable) will cause A to get an implicit constructor, automatically. Don't worry, this doesn't affect constructability or whether you need to call super(). But know that it is there, and if necessary an implicit super() call is prepended to B's constructor. See the JS output to verify this.
In any case, know that you can still instantiate an A at runtime with var a = Type.createInstance(A,[]); as compile-time type checks do not limit RTTI.
Related discussion:
Aside from private/no constructor, Haxe doesn't have a formal notion of abstract classes1 (base classes not expected to be instantiated) or abstract methods2 (functions on abstract base classes with no implementation that must be implemented by a derived class.) However, Andy Li wrote a macro for enforcing some of those concepts if you use them. Such a macro can detect violations of these rules and throw compile-time errors.
1. Not to be confused with Haxe abstracts types, which are an entirely different topic.
2. Not to be confused with virtual functions, which wikipedia describes as a function which can be overridden (though various docs for various languages describe this highly loaded term differently.)
One way of achieving this is to create private Class constructor:
class A {
private function new() {
// ...
}
}
// ...
var a = new A(); // Error: Cannot access private constructor

Benefits of using class func vs func vs no class declaration

Ok so I have a a bunch of helper functions in my project that I originally had in a class called Animate. I was wonder what are the benefits of declaring func vc class func.
Lets use this as an example class:
class Animate{
func moveView(...){
...
}
}
So I believe if I have a class func I don't have to instantiate the class as so.
Animate.moveView(...)
And if I just declare the function with func it would be:
Animate().moveView(...)
However if I don't declare the file as a class at all as so:
func moveView(...){
...
}
When I call the function it is just:
moveView(...)
With no indication where the code came from and it can be just used like this anywhere in the project.
What are the pros and cons of these three ways? Is not declaring a class bad practice? Or, is there some edge case that this is very useful? For example in my situation I have no need for a class since I am just creating helper functions and not an object.
Thanks in advance for any insight on this!
Ok. Instance methods vs class methods vs global methods.
(The term method and function are interchangeable. Method implies a function implemented by an object, so I tend to prefer the term method to the term function.)
An instance method is a method that is performed by instances of a class. You must have an instance of that class to talk to in order to invoke an instance method.
Instance methods have access to the instance variables of the object they belong to, so the object can save state information between calls. (In a networking class you could create multiple download objects, each of which manages an individual file download of a different file from a different URL, and each might have a different delegate it notifies when it's download is complete)
Class methods are invoked by the class itself, not by an instance. This can make it simple to invoke helper functions without having to manage an object to do that work for you. Since class methods don't talk to an instance of the class, they can't preserve different state information for each object. You might have a utilities class that performs localization functions on strings for example. The localization process is self-contained. You call a class function and pass in a string and the language you want it localized to, and it hands you back a result. No need to keep state between calls. Such a call might look like
let frenchString =
LocalizationUtils.localizeString("English String",
toLanguage: "French")
Global functions do not belong to any particular class. They are global to the entire module in which they are defined. They are similar to class functions, except that they are not specific to a particular class.
I agree with (and upvoted) #Duncan C's answer, but just thought I'd throw in a couple of other pros/cons.
I tend to like global functions over class methods because global functions don't clutter up my classes. I like to keep my classes lean and thin. The global functions can be kept in a separate file that I can copy and paste, or import, into a given project as I need them. So I might have a file in my project called AnimateHelperFunctions that is just global functions related to that class. A given project may only need a couple of them, or most of them, or those plus a couple more that I discover I need. I can delete the ones I don't use in a given project from the file so as to keep that file neat and trim.
I just think that global functions are more modular and encourage me to factor out single tasks for a single function - a good global helper function that does exactly one thing and does it perfectly can also sometimes be abstracted or made generic and used in other contexts as well. You might have a project sometime where you realize you don't need the class - you just need its helper function, and there it is.
I would prefer a hundred simple global functions that I can pick and choose from over a giant bloated class.
You can accomplish much the same thing with extensions, of course, and to some degree it is a matter of taste, as there is very little difference (any?) between class methods and global functions except that to use the class method you have to drag along the entire class.
Unlike global state, there isn't any danger in a global function. Sure, anyone can call it, but the same is true of class methods, and the global function can only operate on the arguments you pass to it.
For me, I use static or class methods to control class level properties or if I have to return customised instances of that particular class or struct. Like for example consider I have below struct.
struct Person {
let firstName: String
let lastName: String
}
Now if I am writing some test cases, where I need Person's instance initialized with a particular name John in many of my test classes, I can create a helper static method.
extension Person {
static func john() -> Person {
return Person(firstName: "John", lastName: "Appleseed")
}
}
let john = Person.john() // I could also create a static property instead, but it's a matter of personal choice and situation.
In above case, I could have made john as global function as well but for me, it will be very vague and not readable.
Another place I can think of where I prefer static method is returning count of cases for an enum.
enum Mood {
case happy
case angry
case lazy
case high
static func count() -> Int {
return 4
}
}
There are places, where I use global functions. I use global functions for logging.
func log(screenEvent name: String) {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: screenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
Internally, the method is using a sharedInstance, creating a global method makes it easily accessible everywhere in the project just like a print function which logs output in console, but this is logging in some custom service.
Some other global functions which I usually include in my projects are GCD helpers.
func delay(delay:Double, closure: dispatch_block_t) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
func backgroundTask(closure: dispatch_block_t) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), closure)
}
func mainThreadTask(closure: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), closure)
}
These function don't need any information about a class so it makes sense to make them global instead of wrapping them inside a class.
Regarding instance methods, as answered by #Duncan C, they are called on instances, when you want to maintain a state. Below example shows usage of both static and instance methods.
enum TapType {
case water
case beer
}
struct Tap {
let tapType: TapType
//static method
static func unlimitedBeer() -> Tap {
let beer = Tap(tapType: .beer)
beer.turnOn(forDuration: Float.greatestFiniteMagnitude)
return beer
}
//instance method: will do operation on a particular instance of `Tap`.
func turnOn(forDuration duration: Float) {
//implementation
}
}
let unlimitedBeer = Tap.unlimitedBeer()
You can always use convenience initializer to initialize an object with custom behaviour, but again, it's a matter of choice. In above example, I couldn't think of any convenience initializer which would give me unlimited beer.

How to Implement an Interface that Requires Duplicate Member Names?

I often have to implement some interfaces such as IEnumerable<T> in my code.
Each time, when implementing automatically, I encounter the following:
public IEnumerator<T> GetEnumerator() {
// Code here...
}
public IEnumerator GetEnumerator1() {
// Code here...
}
Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs.
When doing so, I manage to set the GetEnumerator1() accessor to private. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException within the method's body.
However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so.
What is the best approach while implementing an interface such as IEnumerable<T> that requires the implementation of two different methods with the same name?
EDIT #1
Does VB.NET reacts differently from C# while implementing interfaces, since in VB.NET it is explicitly implemented, thus forcing the GetEnumerator1(). Here's the code:
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
// Code here...
End Function
Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator
// Code here...
End Function
Both GetEnumerator() methods are explicitly implemented, and the compile will refuse them to have the same name. Why?
You can use explicit interface implementation:
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
...
}
In Visual Basic, all interface implementations are explicit.
Interface mappings are defined by the Implements statement so you can name your interface implementation methods whatever you want. (Unlike C#, where the compiler infers which methods implement interfaces by matching their names and signatures.)
Changing the method name and visibility (as appropriate) is standard practice in VB. See Implementing Interfaces in VB.NET for a good overview.
You should be able to use Explicit Interface Implementations to create the two methods that have the same signature. Depending on what you are enumerating, I would just pass these calls through to an internal IEnumerable<T> such as a List or array.
Implementing the non-generic interface explicitly allows both methods to have the same name, and allows the non-generic version to be implemented in terms of the generic one. Along the lines of:
public class TestEnumerable : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
// Type-safe implementation here.
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}