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;
}
*/
}
Related
After going back to an older project and getting around to update its dependencies I had to realize that logback does not anymore propagate MDCs to children since version 1.1.5: https://github.com/qos-ch/logback/commit/aa7d584ecdb1638bfc4c7223f4a5ff92d5ee6273
This change makes most of the logs nigh useless.
While I can understand the arguments given in the linked issues, I can not understand why this change could not have been made in a more backwards compatible manner (as is generally usual in java..).
Q: What is the now correct way to achieve the same behaviour other than having to subclass everything from Runnables to Threads?
I see no straightforward way to change this back. Two alternatives that come to mind are:
Way #1: Wrap all Runnables
Introduce an abstract class that will copy MDC from the original Thread to a new Thread and use it instead of Runnable
public abstract class MdcAwareRunnable implements Runnable
{
private Map<String, String> originalMdc;
public MdcAwareRunnable()
{
this.originalMdc = MDC.getCopyOfContextMap();
}
#Override
public void run()
{
MDC.setContextMap(originalMdc);
runImpl();
}
protected abstract void runImpl();
/**
* In case some Runnable comes from external API and we can't change that code we can wrap it anyway.
*/
public static MdcAwareRunnable wrap(Runnable runnable)
{
return new MdcAwareRunnable()
{
#Override
protected void runImpl()
{
runnable.run();
}
};
}
}
If some Runnable comes from an external API that you can't change that code, use wrap helper method.
Drawback: need to analyze and change whole code.
Way #2: Mess with slf4j internals
Resurrect the original LogbackMDCAdapter implementation that uses InheritableThreadLocal from before that commit and put it somewhere in your code under some other name. Then somewhere around startup use reflection to override MDC.mdcAdapter property with and instance of that custom implementation. This is obviously a dirty hack but it saves a lot of troubles comparing to #1.
Note: for performance reasons it makes to inherit your resurrected version from existing LogbackMDCAdapter and just override all the methods with old implementation. See LoggingEvent.java and LogbackMDCAdapter.getPropertyMap internal method for some details.
Way #3: Mess with logback jar (even stranger alternative)
This sounds to me as a quite bad plan but for completness here it is.
Again resurrect the original LogbackMDCAdapter but this time don't rename, compile it and override that .class file inside logback.jar.
Or resurrect the original LogbackMDCAdapter with renaming, remove .class file for org.slf4j.impl.StaticMDCBinder from logback.jar and add your own class that will return resurrected version of LogbackMDCAdapter either to logback.jar or to your code. MDC seems to be bound to that class by name to create an implementation of MDCAdapter to use.
Or you can achieve similar result by using custom ClassLoader that would map org.slf4j.impl.StaticMDCBinder to your class instead of the one inside logback.jar. Note: this is probably impossible to achieve inside a Web-container that will add its own custom ClassLoaders.
Way 4: Misuse TurboFilter
ch.qos.logback.classic.Logger passes the logging event to a filter before passing it along to the appenders.
Way 5: Modify log Encoder / provider
Although this would mean the logging event is not updated, but the log output will be.
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?
I have a TitleWindow component. It allows me to save some data provided through 3 TextInput.
That data "fills" a DropDownList which is in another TitleWindow component, not inside the original one.
How can I call the remoteObject method that fills (or refresh) my DropDownList?
Any ideas will be appreciated!
You can simply use a Singleton as a model if you'd like, this will allow you to share data, but beware keep data only that needs to be shared in here or it will just become a global nightmare.
Using a singleton means you'll have a class that you can only ever have one instance of. If you put properties in that class any time you reference it it will be the same memory throughout the application execution.
http://blog.pixelbreaker.com/actionscript-3-0/as30-better-singletons
Marking the singleton class or individual properties as Bindable will make it so you can watch for the changes and call a function.
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_8.html
Putting this together you have something like this:
[Singleton.as]
package
{
[Bindable]
public class Singleton
{
public var myListData:Array;
public static var instance:Singleton;
public static function getInstance():Singleton
{
if( instance == null ) instance = new Singleton( new SingletonEnforcer() );
return instance;
}
public function Singleton( pvt:SingletonEnforcer )
{
// init class
}
}
}
internal class SingletonEnforcer{}
Somewhere else you want to get a handle on this
[MyTitleWindow.as]
var instance:Singleton = Singleton.getInstance();
instance.myListData = [1,2,3];
[MyTitleWindowWithAList]
var instance:Singleton = Singleton.getInstance();
BindingUtils.bindSetter(funcUpdateList, instance, "myListData");
private function funcUpdateList(data:Object)
{
myList.dataProvider = data as Array;
}
Another option is to create an event that carries your data payload, dispatch that event from the first title window, and capture it, the problem with this is you have to register the listeners on the PopUpManager or SystemManager I believe because the TitleWindow's aren't direct children of the Application I believe.
Singletons are a bad idea and you should not get in the habit of using them. Instead, just dispatch an event from the View and catch it from something else that has access to your Service object.
Note that your Service should not be part and parcel of any View--the responsibility of a View is displaying data and capturing requests from the user to change the data, not communicating with a server.
For examples of an application written with this pattern in mind, check out
[Refactoring with Mate] (http://www.developria.com/2010/05/refactoring-with-mate.html) - The example has View source enabled
The same application done with RobotLegs - again, View Source is enabled.
Note that these are written against some popular frameworks, but they are written in such a way that you can easily replace that framework code with something else, even your own code.
For reference, here is the naiive implementation, where the service layer is being called directly in the Views. You couldn't call a different service without changing the Views, though the use of the static service means you could use it from elsewhere.
That static usage survived into the later examples, though today I would never write something depending on a globally accessible object. In part this is because I discovered Test Driven Development, and it is impossible to replace the "real" static object with an object that lets you isolate what you are testing. However, the fact that most of the code in the 2 "better" examples is insulated from that static object means that it is trivial to replace it with one that is provided some other way.
The lesson here is if you're going to use static, global objects, lock them away behind as much abstraction as you can. But avoid them if you're at all interested in best practice. Note that a Singleton is a static global object of the worst kind.
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.
As we all know, when we derive a class and use polymorphism, someone, somewhere needs to know what class to instanciate. We can use factories, a big switch statement, if-else-if, etc. I just learnt from Bill K this is called Dependency Injection.
My Question: Is it good practice to use reflection and attributes as the dependency injection mechanism? That way, the list gets populated dynamically as we add new types.
Here is an example. Please no comment about how loading images can be done other ways, we know.
Suppose we have the following IImageFileFormat interface:
public interface IImageFileFormat
{
string[] SupportedFormats { get; };
Image Load(string fileName);
void Save(Image image, string fileName);
}
Different classes will implement this interface:
[FileFormat]
public class BmpFileFormat : IImageFileFormat { ... }
[FileFormat]
public class JpegFileFormat : IImageFileFormat { ... }
When a file needs to be loaded or saved, a manager needs to iterate through all known loader and call the Load()/Save() from the appropriate instance depending on their SupportedExtensions.
class ImageLoader
{
public Image Load(string fileName)
{
return FindFormat(fileName).Load(fileName);
}
public void Save(Image image, string fileName)
{
FindFormat(fileName).Save(image, fileName);
}
IImageFileFormat FindFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
return formats.First(f => f.SupportedExtensions.Contains(extension));
}
private List<IImageFileFormat> formats;
}
I guess the important point here is whether the list of available loader (formats) should be populated by hand or using reflection.
By hand:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
formats.Add(new BmpFileFormat());
formats.Add(new JpegFileFormat());
}
By reflection:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if(type.GetCustomAttributes(typeof(FileFormatAttribute), false).Length > 0)
{
formats.Add(Activator.CreateInstance(type))
}
}
}
I sometimes use the later and it never occured to me that it could be a very bad idea. Yes, adding new classes is easy, but the mechanic registering those same classes is harder to grasp and therefore maintain than a simple coded-by-hand list.
Please discuss.
My personal preference is neither - when there is a mapping of classes to some arbitrary string, a configuration file is the place to do it IMHO. This way, you never need to modify the code - especially if you use a dynamic loading mechanism to add new dynamic libraries.
In general, I always prefer some method that allows me to write code once as much as possible - both your methods require altering already-written/built/deployed code (since your reflection route makes no provision for adding file format loaders in new DLLs).
Edit by Coincoin:
Reflection approach could be effectively combined with configuration files to locate the implmentations to be injected.
The type could be declared explicitely in the config file using canonical names, similar to MSBuild <UsingTask>
The config could locate the assemblies, but then we have to inject all matching types, ala Microsoft Visual Studio Packages.
Any other mechanism to match a value or set of condition to the needed type.
My vote is that the reflection method is nicer. With that method, adding a new file format only modifies one part of the code - the place where you define the class to handle the file format. Without reflection, you'll have to remember to modify the other class, the ImageLoader, as well
Isn't this pretty much what the Dependency Injection pattern is all about?
If you can isolate the dependencies then the mechanics will almost certainly be reflection based, but it will be configuration file driven so the messiness of the reflection can be pretty well encapsulated and isolated.
I believe with DI you simply say I need an object of type <interface> with some other parameters, and the DI system returns an object to you that satisfies your conditions.
This goes together with IoC (Inversion of Control) where the object being supplied may need something else, so that other thing is automatically created and installed into your object (being created by DI) before it's returned to the user.
I know this borders on the "no comment about loading images other ways", but why not just flip your dependencies -- rather than have ImageLoader depend on ImageFileFormats, have each IImageFileFormat depend on an ImageLoader? You'll gain a few things out of this:
Each time you add a new IImageFileFormat, you won't need to make any changes anywhere else (and you won't have to use reflection, either)
If you take it one step further and abstract ImageLoader, you can mock it in Unit Tests, making testing the concrete implementations of each IImageFileFormat that much easier
In vb.net, if all the image loaders will be in the same assembly, one could use partial classes and events to achieve the desired effect (have a class whose purpose is to fire an event when the image loaders should register themselves; each file containing image loaders can have use a "partial class" to add another event handler to that class); C# doesn't have a direct equivalent to vb.net's WithEvents syntax, but I suspect partial classes are a limited mechanism for achieving the same thing.