What should the accessablity of Fields in a Abstract Class be? - language-agnostic

To put it simply as an example,
public abstract class AbstractFellow {
protected Thing buddy;
....
public class ConcreteFellow extends AbstractFellow {
public void someMethod() {
buddy.doSomething();
//OR
buddy = somethingElse;
//OR
somethingElse = buddy;
}
}
Is this bad practice?

Opinions vary. My opinion is that even in abstract classes, using private members and protected accessors (i.e. protected getBuddy()) is a better practice.
It allows for the same things encapsulation always allowed: to contain the logic of obtaining the "buddy" object in the super-class, and allowing you to change that logic without breaking all inheriting classes.
The super-class might not expect buddy to be changed, either. For example, you might want to unregister listeners or do some other cleanup when that happens - having a setter method helps achieve that.
In addition, it obviously allows you to have Buddy as a read-only member (since you can provide only a getBuddy and no setBuddy), something that is not as easy to accomplish with a member (you can always set it to be final, but then you prevent the super-class from changing it, too!)

It depends on you domain model and why you creating and abstract class. If you are defining your interface with it and want abstract class to keep some functionality it`s ok.
If you are just setting all the fields protected and then reusing them in your child classes. Well it depends, but I think a better way should be found. And it seems not very clear for your future reader to get data in the base class and all it's behavior in child classes.
If you do not need base class ability to implement methods (and you do not need to store any functionality in your base class) maybe it`s a better choice to implement an interface with every of these child classes.
If you use some of base class inner fields it seems natural to me and it's ok. Just if you are using some of them in your child classes for similar things you can implement a template method and enjoy with overriding only the parts you really need to override.

Related

dynamic class in AS3 : listening to property creation?

I'm currently working on a project that involve a re-implementation of the Array class.
This object needs to be an Array for compatibility reasons, while I also need to keep control of what is written in.
I cannot seem to find any way to check property creation inside of a dynamic object in AS3. Something that would work like the Event.ADDED_TO_STAGE but, like, ClassEvent.PROPERTY_ADDED.
I override methods like push, splice etc, but I cannot control direct assignation : MyArray[i] = ...
Is such a thing even possible ?
Of course, I could make some kind of validations elsewhere, but this would involve accessing a part of the code I cannot modify.
Thanks for your time !
I'm not sure I follow you entirely but you may be looking for the Proxy class:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Proxy.html
An example at the bottom shows you how you can override direct assignment:
override flash_proxy function setProperty(name:*, value:*):void {
_item[name] = value;
}
Using this you would be able to dispatch a custom event that would be fired any time an item was added to your ProxyArray

AS3 - Is it a good idea to make new .AS classes for ever object in a game?

I want to make new .AS files for each and every object in my game for the sake of versatility, dynamism, and organization. I mean, in the case of a shooter game, I want to make a new class file for every type of bullet with all of their unique properties all spelled out in their respective classes. I want to do the same thing for every type of enemy in the game.
This is all assuming there may be 10+ different types of enemies/bullets.
Some people have been pushing me to keep the values of each type of, for example, bullet in one class and then just change the variables depending on the type of bullet being fired. That doesn't sound too fun to me and I would rather just create a bunch of different class files and just push all of the bullets into a common array(which works so far), but I would really like to know if I have the right, or even good, idea by doing so.
In my opinion, since bullets (or enemies, for that matter) represent the same family objects, it would make sense to have a common interface, or an abstract class, which is implemented, or extended by each concrete class. Is this a good idea? Let's think about it this way:
When you are creating the classes that will be used throughout your application, you essentially building an API. Good practice suggests that you should always program to an interface rather than an implementation. What this means is that your top-level classes, should not depend on low-level ones, but rather they should use abstractions. That way, the different-level components are loosely coupled and the overall code is more flexible. This principle is known as Dependency inversion, and is one of the five principles of the SOLID design.
The links provided should give some additional information on how to structure your code.
Have a great day!
You'll want to use inheritance to make it cleaner and more flexible with changes. Then even on multiple projects you can just extend the same generic base class.
Start with a base class (or interface) - Bullet.as for example - and put all the functionality and properties that are common to ALL bullets in that class. Anytime you have groups of bullets that share the same properties, keep making sub-classes. So if you had multiple kinds of bullets that all explode on contact, you could have the following kind of setup:
public class Bullet {
public function fire():void {};
public property size:int;
public property strength:Number;
public property label:String;
public property maxDistance:Number;
}
public class ExplodingBullet extends Bullet {
public property blastRadius:Number;
public function explode():void {
trace("Kaboom");
}
}
public class BazookaBullet extends ExplodingBullet {
public function BazookaBullet():void {
blastRadius = 10;
label = "Bazooka";
size = 5;
maxDistance = 120;
}
}
This would give your bazooka bullets all the functionality of the class it extends. There are a great many benefits to doing it this way as opposed to recreating all the same properties and methods in all your bullet classes.

AS3 game element structure

I'm trying to figure out how best to setup a kind of universal game element class for my game. What I want to try and create is a structure similar too..
GameElementPositionMovement (root class)
->GameElementVisual (handles all the graphics)
->GameElementPersonality (handles game logic)
I then want to be able to set up different personalities (monster, hero, icon etc) just by creating an instance of GameElementPersonality, but in it's constructor also be able to setup the visual and positioning/movement aspects as well.
I mentioned this in another question, and the answer that came back was...
It seems that you need kind of 'data model' class to store logic and a
visual ('view') class. Visual class shouldn't inherit from data model,
it should use it. This is OOP related problem: IS vs HAS (inheritance
vs composition)
But I'm not sure if I understand that. The position/movement without any visual data, seems a good first root class, and then you add to that the visual aspects (GameElementVisual), and then finally you add in personality "traits" (GameElementPersonality) such as armour, damage, health etc
Therefore I'm keeping, the positioning/movement, visual and logic separate, and I presumed the heirachy that I've laid out would be the best way to do that, but is this not a good way to do this? should it be more flat? with the GameElementPositionMovement, creating both a visual and logic instance and storing that in itself?
You could create a structure similar to this:
(pseudocode)
ElementData
//it doesn't have to extend any particular class
//however it would be nice if it could dispatch events and register listeners
class ElementData implements IEventDispatcher
{
public function ElementData() //constructor
{
//do some stuff
}
public function setSomeProperty(value:int):void
{
//
}
public function doSomeCrazyStuff():void
{
//
}
}
ElementVisual
class ElementVisual extends MovieClip //or just Sprite or even DiplayObjectContainer
{
public function ElementVisual(elementData)
{
//constructor takes an instance of ElementData class
elementData.addEventListener(CHANGE, onDataChange)
elementData.doSomeCrazyStuff();
if (userCliked)
{
elementData.setSomeProperty(15);
}
//you can have here some interactions with user (keyboard, mouse)
//then it can communicate with elenemtData and 'listen' what it says.
}
function onDataChange
{
//react accordingly
}
}
some visual representation (you may need many of these)
class Monster extends ElementVisual
{
//do all the graphic, animations etc
}
Then you need a class to set up all the data, visuals etc… In simplest implementation it can be the 'document class'.
It's not a proper MVC model - it's a simple example to show the concept of decoupling logic from visualisation.
MVC is not the only solution, there are other so called 'design patterns' which may be useful...
Yeah the idea with MVC is to keep things decoupled, in your case you're ultimately smashing everything into one chain of inheritance where you'll end up with one type of object that inherits all the properties from another object that inherits all the properties from another object, so you'll have an instance of this thing that represents everything, which is why this isn't a great pattern to go with.
If instead you have a GameElementPositionMovement class (Your main class) create an instance of the GameElementVisual and in instance of GameElementPersonality (or multiple instances if need be). Then any time a change to a property is made in GameElementPersonality (or any in the collection if you choose to make a collection) could dispatch an event, the main class GameElementPositionMovement could listen for the dispatched event and when it gets it can set/pass the GameElementPersonality instance or array to the GameElementVisual. Then in the GameElementVisual you're just dealing with drawing based on the current model all the time, the model is separated from the view logic, you'd also probably want to handle control in a separate class or in GameElementPositionMovement. (control being the modification of the model, in this case it would probably also be where you register listeners for user events, keyboard, mouse whatever)
This way the model remains clean of control logic and view logic, it's a clear separation of what goes where and really only the view sort of depends on the model and the controller sort of depends on the view but if interfaces are established for what the model view controller each need to communicate with each other in this way you can swap out any of those parts with a new class that implements the interface (not likely an issue in a small game, but the design lends itself to this ability and therefor future scalability).

What is the data type from the source of an image

another flashbuilder brainbreaker for me...
I have a class with a contstructor that should only change the source of an image.
[Bindable]
[Embed(source='../pictures/test.jpg')]
private var _picture:Class;
public function Test(newSource:*****)
{
_picture.source = newSource;
}
(the image is not an image, but a class, I am aware of this, it is meant to be so :-) )
The problem is that when I call the constructor, let's say:
var test:Test = new Test(pictureAtStage.source);
Flashbuilder will give an error, becouse I can't tell the compiler what data type "newSource" at the constructor will have...
*edit:
When i use _picture.source, the embedded source does not seem to be changed...?
Anyone knows an answer?
Are we talking about mx.controls.Image? if so, then the source of an image can be: a Class, a Bitmap (not a BitmapData), a String (in which case it is assumed that you wanted to load it instead of using an embedded one). If you want to find a common denominator for all these, then Object is that class, however, I would rather limit it to something particular to your use case.
However, if I may advise anything... don't use mx.controls.Image, it's too bloated, even for Flex framework. If it must be a UIComponent - extend UIComponent and let the source be of type BitmapData - this way you will be able to manage resources better - you could reuse the same actual image for example. You could then use graphics property of the control to display the image.
Another advise, if you are still here :) Don't use [Bindable], especially the short version of it, especially not on a private variable - you will save yourself the frustration of countless hours of debugging it... Besides, in your case you aren't going to change the value of that variable anyway...
Are you still here? Well, don't use [Embed] on variables, use it on class definition - slightly more work for you, but this will, potentially, make your code more portable. If you embed on class the compiler will not generate a silly "something-something-Asset" class, it will use Bitmap or BitmapData - whichever your class extends. Thus, you will not introduce a dependency on Flex framework, and, in general, you will have more control over your code.
EDIT: the above was written assuming that _picture (class) variable and _picture (some variable used in a function) are not the same thing. But if they are the same thing, then Class class is dynamic, which means that you can add to it properties at runtime (don't know why, it's a design decision by Adobe...), however, the compiler will act as if it's not possible, so you would work around that by adding the property through reflection:
var _picture:Class = Sprite;
_picture["source"] = whatever;
trace(Sprite["source"]);
This is indeed slightly confusing, It will be of the type BitmapAsset which extends Bitmap. So any of those will work.
Since I'm very new to flashbuilder I didn't see the obvious solutions...
The solution for the first part of my question (before the edit):
Setting the data type to Object did the trick:
[Bindable]
[Embed(source='../pictures/test.jpg')]
private var _picture:Class;
public function Test(newSource:Object)
{
_pucture.source = newSource;
}

AS3: Interfaces & Nonpublic Methods

I know that by definition AS3 interfaces must be public, and the methods within them must be implemented as public as well.
I read this question and I suppose the answer is obvious if you want to have some classes choose whether or not to implement some methods, but have common base methods that must be implemented across all classes that implement either interface.
With that in mind, even with that 'private implementation' idea (which really isn't), is the best idea still to just explicitly define a private method for all classes, outside of the interface? The issue isn't forcing some classes to implement different methods, it's just the general visibility of those methods. I'm guessing the answer is "yes", but I figured I'd see if anyone had any insight.
Although AS3 doesn't support abstract classes , why not define a class to be used as an abstract class and have it implement that interface and define the non public methods inside that class.
interface IThing {
function thisMethodIsPublic():void;
}
public class ThingAbstract implements IThing
{
//throw an Error to avoid calling the class directly,
//this class needs to be subclassed
//and this method overridden
protected function thisMethodShouldOnlyBeVisibleToCertainClasses():void
{
throw new IllegalOperationError
('this method should be overriden in a subclass');
}
public function thisMethodIsPublic():void
{
}
}