Interfacing and Game Architecture in Actionscript 3 - actionscript-3

I am in the midst of creating the architecture for my new Point and Click game in the Starling framework. It is set to be big in size, so I am trying to make sure to use best Object Oriented practises to ensure I do not A) Repeat the same methods. B) Keep it sustainable and clean.
I was unaware of Interfacing as a way to contract all classes. To keep everything consistent and to ensure that sub classes have the methods to function correctly. Let us look at an example of a player class i have created.
public interface IPlayer {
function changeDirection():void;
function walkToPosition():void;
function pickUpItem():void;
}
class AbstractPlayer extends Sprite implements IPlayer {
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
class Player extends AbstractPlayer {
override protected function walkToPosition():void {}
override protected function pickUpItem():void {}
}
I am aware that AS3 Does not support Abstract Classes natively. But I choose to have it in this form as it makes sense to. What I do not understand is why the interfaces only support public methods. Doesn't that defeat the whole purpose of having an interface; so you know what methods are needed for a player. Declaring only the public functions of the player class seems like a half job.
A verbose explanation of this concept and perhaps a more advanced solution to how this could be structured would be of great benefit.
Many Thanks,
Shaun

An interface is a collection of method declarations that allows unrelated objects to communicate with one another.Hence public access control identifiers for implemented methods.In a typical interactive context often a need arises to modify or control behavior of an object in question externally.In such a case, behavior-control may ideally be accomplished through an interface.Obliviously only methods put into a public namespace are accessible externally.Bearing in mind that attributes of an object should not be be directly modified by external code but only through an interface is good practice of Object Oriented Design. Assuming that a need arises of an object to have more than one point of access control(behavior control); one for external purposes and the other for internal purposes respectively, then putting all behavior in one interface defeats the objective.The following may help to achieve the objective(because you said it's big in size).
Put behavior in an interface you think should be accessible externally.
Define Mediator to encapsulate view-code-mediation:-listen for user triggered events, update view send notifications to other tiers of the application.
Define Model for data purposes.
Define executable commands to be called within your application.
See if you can promote as much lose coupling as possible among the tiers.The goal is to write as much less code as possible and not boiler-plate in nature.I recommend that you use a framework such as robotlegs if really your project is that big.The framework will take care of dependency injection and along the way lift off the burden of writing boiler-plate code.
I Hope the foregoing helps. Thanks.

The interface is acting as an outline of required members to be implemented in the classes using said interface. Therefore the interface methods never being called directly and only being used in the classes implementing them require no access modifiers.
Now you're correct AS3 does not support abstract classes, BUT there is a way to implement an "abstract" class AS3 as per the design. So here is what that might look like with your code:
public interface IPlayer
{
function init():void;
function changeDirection():void;
function walkToPosition():void;
function pickUpItem():void;
}
public class AbstractPlayer extends Sprite implements IPlayer
{
public function AbstractPlayer() {
init();
}
protected function init():void {
throw new IllegalOperationError( "Abstract method, must be overridden in subclass" );
}
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
public class Player extends AbstractPlayer
{
public function Player() {
super();
}
override protected function init():void {
//implementation
}
}
Abstract classes having method implementation by default will require subclasses to override these methods ( see init() and error thrown ) keeping strict usage of the parent class method and members.
This is the basic abstract class design for AS3. This is also the begining to a Factory Method pattern which you can read more on here: http://www.adobe.com/devnet/actionscript/articles/ora_as3_design_patterns.html
Now the more reusable design for this might be to generalize your class names a bit more, perhaps something more like this:
public interface IEntity
{
function init():void;
function changeDirection():void;
function walkToPosition():void;
}
This would be assuming that more game objects other than your Player class will have use of the methods in the IEntity interface.
Now your Player class can become a new object of type Entity:
public class Entity extends Sprite implements IEntity
{
public function Entity() {
init();
}
protected function init():void {
throw new IllegalOperationError( "Abstract method, must be overridden in subclass" );
}
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
Now in regards to the design, since abstract classes are just a tool like any other there are many different designs to take using it and it really depends on your project. I would recommend sifting through the aforementioned link to the "Factory Method" pattern and some of the other designs to see what fits your needs.

An interface defines the way other classes interact with a specific implementation of that interface. Other classes cannot call implementation's private methods directly - there's no need for the interface to define them.
Let's say we have two subclasses of AbstractPlayer: Player and AIPlayer. The Player class would probably include methods to listen for specific input events and to respond to them accordingly, like onKeyUp or onMouseClick, which should be private: there's no need to external classes to know how the player is controlled. The AIPlayer on the other hand is controlled by some strategies you define in your code, therefore instead of listening to user's input, it should keep track of Player's actions and react accordingly. This class does not need onKeyUp or onMouseClick methods, so why put them in interface?

Related

How could not using "final" be a security issue?

From page 113 of O'Reilly's Essential ActionScript 3.0 (2007):
Methods that are final help hide a class’s internal details. Making a class or a
method final prevents other programmers from extending the class or overriding
the method for the purpose of examining the class’s internal structure. Such prevention
is considered one of the ways to safeguard an application from being
maliciously exploited.
Does this refer to users of the API of a compiled, closed-source package, and "maliciously exploited" to learning things about the class design? Is this really a problem?
For some more context, it's the second of two reasons to use final. In the 2007 edition, it's on page 113 in the chapter Inheritance under subtitle Preventing Classes from Being Extended and Methods from Being Overridden.
The final attribute is used for two reasons in ActionScript:
In some situations, final methods execute faster than non-final methods. If you
are looking to improve your application’s performance in every possible way, try
making its methods final. Note, however, that in future Flash runtimes, Adobe
expects non-final methods to execute as quickly as final methods.
Methods that are final help hide a class’s internal details. Making a class or a
method final prevents other programmers from extending the class or overriding
the method for the purpose of examining the class’s internal structure. Such prevention
is considered one of the ways to safeguard an application from being
maliciously exploited.
In many languages, overriding methods is opt-in from the base class. Often, it is the virtual keyword that allows base class authors to opt-in for the possibility of overriding.
In AS3, however, the ability to have methods overridden is opt-out. That is what the final keyword does. It allows the base class author to say "this method may not be overridden".
There are some old-school thoughts about encapsulation that would suggest that it is a security problem for AS3 to do it this way. But this is mostly in cases of public APIs in which you want to hide your content but expose the functionality.
But, in more modern times, we have learned that disassembly and reflection will allow a malicious developer to do anything he/she wants anyways, so this is less of an issue today. Relying on final for security is a crutch, in my opinion, and any suggestions of it should be dismissed. Security needs to be thought of more carefully than that. APIs need to be architected such that the implementation lets developers do what then need to do, but security-critical information should not be included in public APIs.
That is not to say that final is not useful. final tells developers that derive from your class that you never intended them to override the function. It lets you say "please just call this function. Don't override." It is more of an interface or a communications mechanism than anything else, IMO.
final keyword is not used for this kind of security. It is not a substitute for what would normally require a cryptographic solution.
What is usually meant by "security" in these kinds of discussions is the concept of a secure object model - that is to say an object model that cannot be manipulated by consumers for purposes unintended by the original author of the class.
It's Sort of, a well-constructed class will encapsulate its state and a class that only has final methods will not allow consumers to override the behavior of the class and change how the state is encapsulated. A class could expose its state (through public fields for example) and no final keyword would be able to protect the integrity of that state.
It is more about "changing" the stuff rather than "securing". The final keywords simply puts away the ability to change/modify/extend any method.
It doesn't make your code more secure, it is more for thread safety than anything else. If a variable is marked final, a value must be assigned to it when the object is created. After object creation, that variable cannot be made to refer to another value.
This behavior allows you to reason about the state of an object and make certain assumptions when multiple threads are accessing it concurrently.
I don't think that making a field final would add security against malicious attacks (more likely against mistakes and of course threading issues). The only "real form" of security is that if you have a final constant field it might get inlined at compilation so changing its value at runtime would have no impact.
I've heard of final and security more in the context of inheritance. By making a class final you can prevent someone from subclassing it and touching or overriding its protected members, but again I would use that more to avoid mistake than to prevent threats.
Assume you release some fancy SWC Library to the public. In this case you can prevent a method from beeing overridden.
package
{
import flash.display.Sprite;
public class FinalDemo extends Sprite
{
public function FinalDemo()
{
super();
var someClientInstance:ExtendedAPIClient = new ExtendedAPIClient();
// doSomething is overridden by ExtendedAPIClient
someClientInstance.doSomething();
// activate cannot be overridden
someClientInstance.activate("mySecretAPIKey");
var myApp:MySupaDupaApplication = new MySupaDupaApplication(someClientInstance);
}
}
}
/**
* Assume this class is within a swc that you release to the public.
* You want every developer to get some APIKey
* */
internal class MySupaDupaApplication{
public function MySupaDupaApplication($apiClient:APIClient):void{
if($apiClient.activated)trace("It's a valid user, do something very cool");
}
}
/**
* In order to activate a Client the developer needs to pass a
* instance of the API Client to the Application.
* The application checks the activated getter in order to determine
* if the api key is valid.
* */
internal class APIClient{
private var __activated:Boolean = false;
public function APIClient(){
trace("APIClient Constructor");
}
/**
* override possible
* */
public function doSomething():void{
trace("doing something");
}
/**
* override not possible
* */
public final function activate($key:String):void{
trace("activate "+$key);
if($key == "mySecretAPIKey"){
__activated = true;
}else{
__activated = false;
throw new Error("Illegal Key");
}
}
/**
* override not possible
* */
public final function get activated():Boolean{
return __activated;
}
}
/**
* Class within some developers library using MySupaDupaApplication
* Changes the Client behaviour
* Exploit of activation not possible
* */
internal class ExtendedAPIClient extends APIClient{
public function ExtendedAPIClient(){
trace("ExtendedAPIClient Constructor");
super();
}
override public function doSomething():void{
trace("doing something else");
}
/* this will throw a compiler error */
/*
override public function activate($key:String):void{
// do nothing
}
override public function get isActivated($key:String):Boolean{
return true;
}
*/
}

AS3 How do you access an instance of a class from anywhere?

I currently pass a reference to my model through the constructor to any class that needs it in my simple mvc pattern, this can get annoying at times when it starts to go deeper.
How do Classes such as LoadMax allow you from anywhere to simple import the class, and do something like addChild(LoaderMax.getContent("bg"));? Replicating this should surely be a good way to have my model work, without the complexity of big frameworks?
Statics are your friend
As previous answers have noted, TweenLite/Max etc. makes heavy use of static members to get work done. This is exactly like the Math class, for example, and can be a very convenient design pattern. You have global access to the class, and that can definitely alleviate the issue of getting access to variables through deeply nested classes.
Statics are the enemy
Statics, however, bring certain problems to the table. Most importantly, they tend to reduce flexibility and modularity of classes through the often unnecessary addition of tightly coupled relationships. It's a bit like pouring concrete over your application. It does work, but changing behavior becomes difficult as project features change.
Static members != instance members
Note, very clearly, that a static member "belongs" to the class itself, and not an instance of that class. Static members have no access to instance members. This causes troubles when you want to mix these members up in logic. You tend to have to make everything static (the so-called "static-cling" effect). Static patterns are often argued to be argued to be "anti" object-oriented, for precisely this reason. Once you build a structure on a static pattern you tend to lose many of the principles that makes OOD powerful.
In small does, they're pretty nice
That all being said - TweenLite is a great example of a static pattern that is totally appropriate - its a utility package, one that logic is not dependent on. And that should probably be how you leverage statics, too.
To reduce reliance on statics, or even global vars, it does often mean writing more code, but the flexibility in app structure gained is often quite worth it. #Marty_Wallace has a pretty good solution imo.
Demeter and the Paperboy
Finally, I'll just mention the Law of Demeter, or the Principle of Least Knowledge, and the related Paperboy and the Wallet example, which is often pointed to in discussions of statics:
Each unit should have only limited knowledge about other units: only
units "closely" related to the current
unit.
Each unit should only talk to its friends; don't talk to strangers.
Only talk to your immediate friends.
Hopefully that sheds a little bit of light on a fairly complicated and not-often obvious issue.
This is done using the static namespace, however I discourage the use of this.
package
{
public class Main
{
public static function sayHell():void
{
trace("hello!");
}
}
}
You can now call sayHello() like this from anywhere in the application (assuming you've imported the class).
Main.sayHello();
Another thing you can do (to make the entire class accessible from within the application) is create a static property that refers to the class itself:
package
{
public class Something
{
public static var instance:Something;
public function Something()
{
instance = this;
}
public function someFunction():void
{
trace('hello!');
}
}
}
Which you can now use like so:
Something.instance.someFunction();
The only thing to note here is that you need to create an instance of Something for this to work to call the constructor and define instance.
What I would do
Create a base class for all objects in your application
Create a manager class that takes care of these objects
Create a setter within your base class to define the manager
Here's an example:
Base
package
{
public class Base extends Object
{
private var _manager:Manager;
public function set manager(m:Manager):void
{
_manager = m;
init();
}
protected function init():void
{
manager.someFunction();
}
public function get manager():Manager{ return _manager; }
}
}
Manager
package
{
public class Manager extends Object
{
public function someFunction():void
{
trace('hello!');
}
}
}
Now anything that extends Base will have access to anything held in Manager via the manager getter property. All you need to do is make sure you define the manager, which is easily achieved from within anything that extends Base like so:
var something:SomeExtendingClass = new SomeExtendingClass();
something.manager = manager;
The example you gave is just a static method, but to answer your question about a global instance of a class:
package myPackage
{
public var globalVariable:MyClass = new MyClass();
}
You can access it with:
import myPackage.globalVariable;
trace(globalVariable);
I think you have to rethink in which way you want to name your classes.
You can instantiate whatever class you want, at run-time, but to access a instance by name, you have to make changes in your structure. For example, the getContent() function you mentioned in LoaderMax, all it does is to search in an array for the given loader that matchs the name, among other things. You can read the name variable comment for a description.
A name that you use to identify the loader instance. This name can be fed to the getLoader() or getContent() methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".
So in this system, you have to name every single member (loaders in this case) if you want to be able to search them. Because if I call getClassInstance("myinstance"), what is "myinstance" representing? Where should I name it?
That said, if you want to do it for DisplayObjects only, you can use getChildByName. But again, you have to name every DisplayObject (just set the name variable).
Hope this helps.

When should I use/examples of nested classes?

Please retag this question to include languages to which it is relevant
So my java book had a whole chapter on nested classes, but ended on the note that you should only really use them when it comes to "modeling composition relationships and implementing internals of a class you want to hide". So lets discuss when you would want to use nested classes and some examples.
A nested/inner class is just a class that's only ever used specifically in the context of another class, which doesn't have it's own class file. If it's linked to an instance, it can only be instantiated in the context of a parent class instance; it can see private data, or only private static data if it's a static class.
The java developer site has a nested classes tutorial with one example:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
A couple examples of usage:
Hide a concrete implementation of an
interface:
(Thinking of a database session for a tool like Hibernate): Suppose you have a Session interface, and a SessionFactory which returns an instance of a Session. The SessionImpl concrete class that implements the Session interface could be an innner class of the factory that knows how to construct and initialize it.
Supply information by implementing an
interface:
In the Wicket web framework, each GUI component has an associated "model", whose job is to wire data to the component. The interface looks something like:
public interface IModel extends IDetachable {
public Object getObject();
public Object setObject();
}
Suppose you have some special logic to retrieve data for a custom GUI component that you've written. Since no other component retrieves data the same way, you could use an anonymous class at the point where the IModel is supplied to take care of the data retrieval. If you have another point in the same class where you need to reuse your IModel implementation, you could make it an inner class. Later, if you need the model elsewhere, you could convert it to a top-level class.
Generally you use an inner class in a situation where you need a class definition, but that class is only usable or only makes sense in the context of the parent class.
A real life usage i had with nested classes, was in a global settings object.
The parent class was a Singleton, with nested classes as settings categories.
Settings
File settings
Print settings
Etc.
There was no real point in making the inner object as separate classes, as their would be no use for them outside the settings class scope.
I use nested classes for encapsulating algorithms that would be usually done as a method with lots of arguments. I use class that has raw data and I put algorithms into separate file in nested class (using partial keyword). That way I can put properties for that algorithm and its (working) data lives after algorithm is done.
I know that can be easily done without nested classes but this feels right because algorithm is purposely built for parent class.
public partial class Network
{
partial void initFDLF()
{
fdlf=new FDLF(this);
}
public FDLF fdlf;
public class FDLF
{
internal bool changed=true;
internal bool pvchange=true;
public double epsilon = 0.001;
public bool fdlfOk=false;
public void init(){...}
public void run(){...}
...

extending a class and implementing an interface

I am creating objects for a game, they are all sprites. but I also want them to implement an interface. Is it possible to do both ? If not, how can i have an object have the capabilities of a sprite and also have it implement an interface. I am wanting to create another class that checks all my objects to see what datatype they are and evaluate them accordingly
It is possible for all ActionScript objects to both implement an interface and extend a class. Here's an example:
public class RedZoid extends Sprite implements IColoredZoid
Furthermore, the is keyword works with interface implementations:
var z1:RedZoid = new RedZoid();
if (z1 is IColoredZoid) {
// This branch will be hit, since the interface is implemented
}

What is a class interface?

I'm currently working my way through Code Complete and the word "interface" keeps popping up! I'm trying to get my head round what an interface is. Can you define the term? Also what actually makes up a "class interface"?
In general, an interface is simply "what the class looks like to the rest of the world".
For example, this class in Java:
class MyClass {
private string data;
private string Foo() {...}
public void Bar(string s){...}
}
could be said to have just the Bar function in its interface. Internally it has a few other members, but they're private, so they're not visible to the outside world.
More commonly, interfaces are also specific types in the language, for example in the following, MyClass implements the interface IMyClass:
interface IMyClass {
public void Bar(string s);
}
class MyClass implements IMyClass {
private string data;
private string Foo() {...}
public void Bar(string s){...}
}
The interface is now expressed in code, so that any time a variable of type IMyClass is expected, an object of type MyClass can be used, because it implements the correct interface.
I think a good way to define an interface is as follows
An interface is a contract specifying a set of methods, fields and properties which will be available on any implementing object
The actual implementation from language to language may have funny little differences but the principle holds.
I considered adding implemented interfaces to the list above but left it off because it seemed to be a bit too language specific. I think it's OK though because the end effect is almost the same. Tacking on more interfaces is just adding more methods, fields and properties to the contract.
The interface to a class is its "public face" that other classes can see. It separates the the class's implementation from the way it interacts with other classes. That way different implementations can be swapped out and other classes don't need to know anything about what's behind the interface.
An interface can include both data and function members.
It's external face to the world. Usually the set of public methods (members) it exposes.
Technically however they would be 2 different things
An interface would be a public contract. e.g.
interface ILogger
{
void Log(String str);
}
A class would then 'implement' this interface - in a way saying that it provides this functionality
class ConsoleLogger : ILogger
{
public ConsoleLogger() { ... }
public void Log(String str)
{
Console.WriteLine("Console Logger " + str);
}
// private stuff
}
Users of this service / interface do not have to concern themselves with how it is implemented or who is implementing it? By depending on an interface, the actual implementation can be switched at will.
Interface is definition of set of methods that class can impelement. It's mostly used for interface polymorphism.
A interface is like a class but not quite. It has similar traits like a class but it is not an interface. An interface has a variables and methods, "just like the class but the methods declared in interface are by default abstract (only method signature, no body)".
http://beginnersbook.com/2013/05/java-interface/
Interfaces have two definitions. It depends in what context the term Interface is used.
A Classes Interface refers to all the implemented public methods of a class.
An Interface as a Type. i.e using the keyword interface to declare an Interface.
interface Movable{
moveStraight();
moveLeft();
moveRight();
stop();
}
So now a class, lets say, Car can implement the interface Movable. This is what is know as the contract. If class Car implements interface Movable, Car guarantees to provide implementations for all the methods declared in Movables
declaration.
To conclude, generally an Interface is addressed as a type (definition 2) in a language specific programming context. You will find the first definition on fewer occasions usually in a theoretical or design context.
The classical real life example of an interface is the controls a car.
The break, gas, and wheel would be the interface.
The engine and other mechenical aspects would be the implementation.
These mechanical aspects can change, we wouldn't know because our interface remains the same.
This is the power of an interface, it hides implementation details so we can work on a higher level of abstraction. We can directly use the functionality of the interface usually without worrying about how the code underneath it is implemented.