How to enforce derived classes to implement methods in AS3? - actionscript-3

I have a rather simple theoretical question regarding OOP (in AS3) that I don't know how to google:
I need something like an abstract class, which would require that dependant class implements some interface, like this:
Interface ISomething
{
public function somethingize(otherThing:type):void;
}
abstract public class AbstractSomething implements ISomething
{
public function AbstractSomething()
{
// ...
}
public function doSomething():void
{
//code here
// ...
this.somethingize();
// ...
}
}
Is the only way to achieve such a thing is to drop an "abstract" keyword, and move somethingize to SomethingWrapper (with an implementation of throwing an "unimplemented exception"), or is there some better way to model it?

ActionScript doesnt support Abstract classes (unfortunately).
I think there are a few techniques out there to try and mimic abstracts, but my way is too just throw errors in my abstract classes to stop them being used directly, eg:
public class AbstractSomething implements ISomething
{
public function AbstractSomething()
{
throw new Error("this is an abstract class. override constructor in subclass");
}
public function doSomething():void
{
throw new Error("this is an abstract class. override doSomething in subclass");
}
}

Without more information about the specific implementation, I would prefer composition over inheritance in this case, specifically dependency injection.
public interface ISomething {
function somethingize(thing:*):void;
}
public class SomeWorker {
private var _something:ISomething;
public function SomeWorker(something:ISomething) {
this._something = something;
}
public function doSomething():void {
// work
this._something.somethingize(obj);
// more work
}
}
Inherrited classes of SomeWorker could inject the correct implementation of ISomething for the work they need to do, or that dependency could be resolved somewhere else.

Related

Trouble creating a base ViewModel for MvvmCross 5.1.0

I'm currently diving into the world of Xamarain with the MvvmCross framework. In my current project I want to make use of a MVVM base ViewModel to be able to reuse some of my code in other ViewModels.
When trying to implement this I've ran into a problem when using the MvxViewModel which supports passing parameters between navigation.
public abstract class BaseViewModel<TParameter> : MvxViewModel, IMvxViewModel<TParameter> where TParameter : class
{
protected readonly IMvxNavigationService _navigationService;
public BaseViewModel(IMvxNavigationService navigationService)
{
_navigationService = navigationService;
}
public new abstract Task Initialize(TParameter parameter);
}
This way I'm able to use the BaseViewModel as following.
public class ExampleViewModel : BaseViewModel<ExampleParameters>
{
private ExampleParameters _parameter;
public ExampleViewModel(IMvxNavigationService navigationService) : base(navigationService)
{
}
public override Task Initialize(ExampleParameters parameter)
{
return Task.Run(() => { _parameter = parameter; });
}
}
In this situation I think this is a pretty good solution. The ExampleViewModel even tells me I need to implement the Initialize Task when I've forgotten.
Still this solution is not great in every situation. When I have ViewModel that doesn't require the passing of parameters I still need to specify a parameters object and implement the Initialize method.
public class ParameterlessViewModel : BaseViewModel<object>
{
public ParameterlessViewModel(IMvxNavigationService navigationService) : base(navigationService)
{
}
public override Task Initialize(object parameter)
{
return Task.Run(() => { });
}
}
When removing the abstract method from the BaseViewModel I wont need to implement the Initialize method but then I won't be forced to implement it when I'm creating a ViewModel that requires the passing of parameters.
The above solution is workable but I'm curious if anyone ran into this same problem and maybe has a better solution? One which is good in both situations without having to setup two BaseViewModel classes.
Kind regards,
Jop Middelkamp
The documentation for this states: https://www.mvvmcross.com/documentation/fundamentals/navigation
If you have a BaseViewModel you might not be able to inherit MvxViewModel<TParameter> or MvxViewModel<TParameter, TResult> because you already have the BaseViewModel as base class. In this case you can implement the following interface:
IMvxViewModel<TParameter>, IMvxViewModelResult<TResult> or IMvxViewModel<TParameter, TResult>
In case you use TResult you can just copy the source code into your viewmodel:
public override TaskCompletionSource<object> CloseCompletionSource { get; set; }
public override void ViewDestroy()
{
if (CloseCompletionSource != null && !CloseCompletionSource.Task.IsCompleted && !CloseCompletionSource.Task.IsFaulted)
CloseCompletionSource?.TrySetCanceled();
base.ViewDestroy();
}
Do we do the add the Interface IMvxViewModel in the base class or the device class, can you give a simple example
In this case you can implement the following interface:
IMvxViewModel<TParameter>, IMvxViewModelResult<TResult> or IMvxViewModel<TParameter, TResult>

AS3 Inheritance

When 'SubClass' extends 'SuperClass', when it inherit its methods and properties, it creates methods and properties that distinguishes from the 'SuperClass'?
Or if I create an instance of 'SubClass' and I try to modify a property, that was inherited from 'SuperClass', am I modificating the super class property also?
Thanks.
EDIT
package {
public class SubClass extends SuperClass {
public function SubClass() {
trace('superclass value n='+superClass.n+'\n');
trace('subclass changes inherited n'+'\n');
n = 3;
trace('subclass value n='+n+'\n');
trace('superclass value n='+superClass.n+'\n');
}
}
}
Returns me:
superclass value n=-1;
subclass changes inherited n;
subclass value n=3;
superclass value n=3;
I will explain it in short.
We have two classes - Subclass and SuperClass.
SuperClass have four methods:
private function methodPrivate():void;
protected function methodProtected():void;
public function methodPublic():void;
internal function methodInternal():void;
From the Subclass you:
Cannot access methodPrivate():void;
Can access methodProtected():void; but just like your private method, it means, you cannot access it from outside of Subclass.
Can access methodPublic():void; and everything can access if from outside of Subclass also.
methodInternal():void; is available for classes from the package of SuperClass.
You can however override these methods. Overriding doesn't change a methods of SuperClass but change them only in SubClass.
override public function methodPublic() : void {
// your additional code
super.methodPublic(); // eventually calling the same method of SuperClass, you can pass arguments to it also
}
As you know, your SuperClass can also have variables, that also can be public, protected, private or internal. You cannot override them, but you can do this with getters or setters however.
You can access variables that are created as public or protected by using a word "super" like this: super.someVariable .
So everything is up to you, if you want to create a different variables of the same name in SuperClass and SubClass, just declare one as private in SuperClass. If you want to have one variable that SuperClass and SubClass both can access - just declare it as protected or public.
Hope that was clear.
When you create a blank SubClass the extends SuperClass, you are creating a new class that provides the same interface (with the same implementation) to the parent class.
That is to say, if your parent class contains a method doSomething, your SubClass, without ever actually writing it, will have the doSomething method available as well. The one caveat to this is if the method is marked private, in which case the inheriting class, SubClass, will not have access.
package {
public class SuperClass {
public function SuperClass():void {
self.doSomething();
}
public function doSomething():void {
trace("doing something");
}
}
package {
import SuperClass;
public class SubClass extends SuperClass {
public function SubClass():void {}
}
}
Once you have this relationship established, you can decide whether calling doSomething on an instance of SubClass will behave differently than the default implementation, defined in SuperClass. If you want the same behavior, you leave it as is. If you want different behavior, then you override the parent class' method, using the keyword override.
package {
import SuperClass;
public class SubClass extends SuperClass {
public function SubClass():void {}
override public function doSomething():void {
trace("doing another thing instead");
}
}
}
Now something that calls doSomething on an instance of SubClass will get modified behavior. But the default implementation has not been touched. Instanced of SuperClass are not modified by this overriding of a method. Only instances of SubClass will be affected.
This is the same case for properties.
There is one exception to this, and that is static properties. A static property is a property of the class, not of an instance of the class. Static properties are not inherited. A static property looks like this:
package {
public class SuperClass {
public static var i:int = 0;
public function SuperClass():void {
}
public function doSomething():void {
trace("doing something");
}
}
The SubClass class will not have a reference to a static property i. However, a SubClass instance can change the static value of the SuperClass. As an example:
package {
import SuperClass;
public class SubClass extends SuperClass {
public function SubClass():void {}
override public function doSomething():void {
trace("changing something in SuperClass");
SuperClass.i = 1;
}
}
}
Now, the SuperClass's static variable i has a value of 1, instead of 0. In this way a SubClass has the potential (although it is the same potential any code has with the right access privileges) to change the properties of SuperClass.
I hope this helps.

Using interfaces in Actionscript 3 properly

I have made an interface called IHero i implement in my hero.as3 class.
the hero class is written so it can be inheritted in a movieclip class to handle movement etc etc. But somehow i can't figure out how to code this with a good practice.
Maybe i am in the wrong direction.
I want to have a movieclip subclass, which will be a hero for instance.
Should i just implement the IHero in the hero class with the following methods, or is this to overkill? - I guess I am looking for an answer upon what should be in an interface and what should not. Here is the interface.
package com.interfaces
{
public interface IHero
{
//movement
function MoveLeft():void;
function MoveRight():void;
function MoveUp():void;
function MoveDown():void;
//in battle
function DoDamage(isCasting:Boolean):void;
function DoHeal():void;
function Flee():void;
function TakeDamage():void;
function IsAlive():Boolean;
function CheckDeath():void;
function Die():void;
}
}
I think you are on a right track, whether its the right one or the wrong one is always subjective. But if you do want to go down this road, I suggest you read this article by Mick West. Its a few years old, but its still very applicable.
I think you really have two distinct interfaces, but probably more
public interface IMoveable {
function moveLeft(obj:DisplayObject):void;
function moveRight(obj:DisplayObject):void;
function moveUp(obj:DisplayObject):void;
function moveDown(obj:DisplayObject):void;
function Flee(obj:DisplayObject);
}
public interface IFightable {
function doDamage(withWeapon:IEquipableWeapon);
function takeDamage(fromWeapon:IEquipableWeapon);
function get isAlive():Boolean;
function checkDeath():void;
function Die():void;
function doHeal();
function get health():Number;
}
Then....
public class SimpleMover implements IMoveable {
// The movement implementation
// for example:
public funciton moveLeft(obj:DisplayObject) {
obj.x = obj.x -= 10;
}
}
public class SimpleFighter implements IFightable {
// The fighting implementation
private var _health:Number = 100;
function doDamage(withWeapon:IEquipableWeapon) {
_health -= withWeapon.damage;
}
}
Then inject those into your subclass MovieClip for your Hero.
public class Hero extends MovieClip {
private var _mover:IMoveable;
private var _fighter:IFightable;
public function Hero(mover:IMoveable, fighter:IFightable) {
_mover = move;
_fighter = fighter;
}
}
Here you are using the Hero class as both Component Manager and Render component, which goes slightly against what West is talking about in the article, but I digress. But the idea is that your Manager (the Hero) becomes more or less an orchestrator, proxying calls back through to which ever component is applicable; calling methods on _mover and fighter to do your actual work.
There are several advantages using an approach like this, and some disadvantages. First, its more complex to set up; it requires you to really like about components and what each logical chunck of code is going to do. But on the other hand, it decouples your implementations from each other, makes it more testable, and reuseable. You can also swap out components at any time (compile-time or run-time for that matter), which gives you some flexability when creating new Entities.
But anyway, its just a suggestion of a slightly different paradigm that you seem to be flirting with. Maybe you'll get some mileage out of it. But definitely give the article a read, if you haven't already.
Also look into (like check out the API) for the Unity Engine which has a similar aggregation vs inheritance model where interfaces are key to abstraction.
Usually you will want a regular class definition that extends movieclip, then set your hero movieclip to use that class in the export for actionscript options. The interface is most likely not needed at all for your game.
Just to clarify - interfaces are implemented, not inherited. Therefore it does not matter what type of class you create that implements IHero. So to make a type of library class that implements Ihero, extend a display object like Sprite or MovieClip, and then use the implements keyword to indicate the class implements Ihero.
Add the Ihero methods, and you now have a display object class that implements iHero. It might look something like this (note no constructor function supplied)
package
{
import flash.display.Sprite;
import com.interfaces.IHero;
/**
* ...
* #author Zachary Foley
*/
public class MyDisplayObkect extends Sprite implements IHero
{
public function MoveLeft():void
{
// Add Implementation here;
}
public function MoveRight():void
{
// Add Implementation here;
}
public function MoveUp():void
{
// Add Implementation here;
}
public function MoveDown():void
{
// Add Implementation here;
}
//in battle
public function DoDamage(isCasting:Boolean):void
{
// Add Implementation here;
}
public function DoHeal():void
{
// Add Implementation here;
}
public function Flee():void
{
// Add Implementation here;
}
public function TakeDamage():void
{
// Add Implementation here;
}
public function IsAlive():Boolean
{
// Add Implementation here;
}
public function CheckDeath():void
{
// Add Implementation here;
}
public function Die():void
{
// Add Implementation here;
}
}
}

ActionScript: Determine wether superclass implements a particular interface?

Is there any non-hacky way to determine wether a class' superclass implements a particular interface?
For example, assume I've got:
class A extends EventDispatcher implements StuffHolder {
protected function get myStuff():Stuff { ... };
public function getStuff():Array {
if (super is StuffHolder) // <<< this doesn't work
return super['getStuff']().concat([myStuf]);
return [myStuff];
}
class B extends A {
override protected function get myStuff():Stuff { ... };
}
How could I perform that super is StuffHolder test in a way that, well, works? In this case, it always returns true.
In this case you might have to define StuffHolder (and have it extend EventDispatcher) as a class and have getStuff as a public/protected function. You could then overload the getStuff function in class A, but not in class B.
package {
public class StuffHolder extends EventDispatcher {
function StuffHolder() {
}
protected function getStuff():Array{
return ["Default"];
}
}
}
package {
public class A extends StuffHolder {
function A {
super();
}
protected override function getStuff():Array {
return ["A"];
}
}
}
package {
public class B extends StuffHolder {
function B {
super();
}
}
}
I don't have the full picture to figure out why you'd need that kind of (weird and possibly broken) inheritance, but could you rephrase it to if (this is actually an A instance)?
If so, you could go with...
import flash.utils.getQualifiedClassName;
if (getQualifiedClassName(this) == 'A')
The thing is, the is operator should be used on object instances. And it works all the way up to object -- I mean, A is B is true for every A ancestor or interface implementation.
I think you could come up with a better structure for your classes, though.
This isn't that pretty.
I could do something involving introspection, getting the current class, finding its parent class, then checking to see if that implements the StuffHolder interface… But that seems pretty ugly :(

AS3 - Abstract Classes

How can I make an abstract class in AS3 nicely?
I've tried this:
public class AnAbstractClass
{
public function toBeImplemented():void
{
throw new NotImplementedError(); // I've created this error
}
}
public class AnConcreteClass extends AnAbstractClass
{
override public function toBeImplemented():void
{
// implementation...
}
}
But.. I don't like this way. And doesn't have compile time errors.
abstract classes are not supported by actionscript 3. see http://joshblog.net/2007/08/19/enforcing-abstract-classes-at-runtime-in-actionscript-3/
the above reference also provides a kind of hackish workaround to create abstract classes in as3.
Edit
also see http://www.kirupa.com/forum/showpost.php?s=a765fcf791afe46c5cf4c26509925cf7&p=1892533&postcount=70
Edit 2 (In response to comment)
Unfortunately, you're stuck with the runtime error. One alternative would be to have a protected constructor.... except as3 doesn't allow that either. See http://www.berniecode.com/blog/2007/11/28/proper-private-constructors-for-actionscript-30/ and http://gorillajawn.com/wordpress/2007/05/21/actionscript-3-%E2%80%93-no-private-constructor/.
You may Also find these useful: http://www.as3dp.com/category/abstract-classes/ and, in particular, http://www.as3dp.com/2009/04/07/design-pattern-principles-for-actionscript-30-the-dependency-inversion-principle/
package
{
import flash.errors.IllegalOperationError;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
public class AbstractClass
{
public function AbstractClass()
{
inspectAbstract();
}
private function inspectAbstract():void
{
var className : String = getQualifiedClassName(this);
if (getDefinitionByName(className) == AbstractClass )
{
throw new ArgumentError(
getQualifiedClassName(this) + "Class can not be instantiated.");
}
}
public function foo():void
{
throw new IllegalOperationError("Must override Concreate Class");
}
}
}
package
{
public class ConcreteClass extends AbstractClass
{
public function ConcreteClass()
{
super();
}
override public function foo() : void
{
trace("Implemented");
}
}
}
In AS3 would just use interfaces to make sure all functions are implemented at compile time.
I know it different but does the trick for an example such as the one above.
As long as they don't permit non-public constructors in actionscript, you'd have to rely on run time errors for abstract classes and singletons.