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?

trakos
  • 841
  • 8
  • 25
  • My opinion on this topic keeps swaying from "just use what the language gives you" (interfaces), and doing things like you/and answers below have suggested. Frankly, I don't like methods that throw exceptions by default. In the end, I think it's up to you. I've been perfectly happy w/interfaces alone. Perhaps ignorance really is bliss. – Sunil D. Feb 28 '13 at 03:21
  • Also, w/MVC frameworks that do dependency injection, you can declare the dependency as an interface and inject anything that implements it, which is very handy. Would the same be true of an "abstract" class? This might be why I prefer interfaces over abstract classes. – Sunil D. Feb 28 '13 at 03:30

2 Answers2

3

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");
    }
}
0

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.

J. Holmes
  • 18,466
  • 5
  • 47
  • 52