Vector holding (certain) (sub)classes (instead of instances of) - actionscript-3

So I've only somewhat recently I've started ActionScript 3.
For practice purposes I'm trying to make a simple game that should have a small number of levels. All levels are a subclass of the super class World.
So, basically I would want to do something like:
private static var levels:Vector.<Class> = new <Class>[ Level1, Level2 ];
Except in this case I only know that the classes in my vector are a subclass of Class (right?), where as I would like to know they are sub classes of World.
I know I can grab the Class from the vector, then cast to World- but if at all possible I really would prefer to be able to do this without such casting.

Related

UML relationships - dashed line vs solid line

What is the difference between these 2 relationships?
Edit: Also if you could provide a simple code example illustrating the difference, that would be really helpful!
I'm trying to give simple examples of the two types of lines.
In the first diagram, the solid line shows an association:
If the classes were declared in Java, this would be like ClassA storing a reference to ClassB as an attribute (it could be passed in to the constructor, created, etc.). So, you might see something like:
public class ClassA {
ClassB theClassB = ...
...
}
In the second diagram, it shows a dependency:
A dependency is much weaker than an association. To quote from UML Distilled:
With classes, dependencies exist for various reasons: One class sends a message to another; one class has another as part of its data; one
class mentions another as a parameter to an operation. [...] You use dependencies
whenever you want to show how changes in one element might alter other elements.
Again, using Java, a couple of examples exist: an argument of type ClassB is passed to a method, or a method declares a local variable of type ClassB:
public class ClassA {
...
public void someMethod(ClassB arg1) {...}
...
public void someOtherMethod() {
ClassB localReferenceToClassB = ...
}
...
}
Other ways ClassA could depend on ClassB without having an association (not an exhaustive list):
ClassB has a static method that ClassA calls
ClassA catches exceptions of type ClassB
Whenever ClassB is modified, ClassA must also be modified (e.g., some logic is shared)
Your question gave me a good chance to learn myself, here is what I found -
Association: Ownership of another type (e.g. 'A' owns a 'B')
//#assoc The Player(A) has some Dice(B)
class Player {
Dice myDice;
}
Dependency: Use of another type (e.g. 'C' uses a 'D')
//#dep The Player(C) uses some Dice(D) when playing a game
class Player {
rollYahtzee(Dice someDice);
}
Here's a crisp ref I found - Association vs. Dependency
This webpage says enough I think
The following text comes from it, but should be enough to understand the difference.
So basically the solid line is an association and the dashed/dotted line is a dependency.
Associations can also be unidirectional, where one class knows about
the other class and the relationship but the other class does not.
Such associations require an open arrowhead to point to the class that
is known and only the known class can have a role name and
multiplicity. In the example, the Customer class knows about any
number of products purchased but the Product class knows nothing about
any customer. The multiplicity "0..*" means zero or more.
A dependency is a weak relationship between two classes and is
represented by a dotted line. In the example, there is a dependency
between Point and LineSegment, because LineSegment's draw() operation
uses the Point class. It indicates that LineSegment has to know about
Point, even if it has no attributes of that type. This example also
illustrates how class diagrams are used to focus in on what is
important in the context, as you wouldn't normally want to show such
detailed dependencies for all your class operations.
Since my reputation is only 8 I can't place the images itself, but they can still be found on the webpage I mentioned at the start.
[EDIT]
I don't have code examples right here, but how I personally would explain it is as simple as a car and a door.
When a car has a door (or more) it's just a car
Car --- has a --> Door
But when you have a door which can be opened the door class will have a function like
public void openDoor(){
this.open();
}
To use the function above the car will have to create an instance of the door
Class Car(){
Door door1 = new Door();
door1.open();
}
In this way you have created a dependency.
So the solid line is just pointing an object(1) to another object(2), but when you start using the object(1) it becomes a dependency.
Okay, since you didn't accept the first answer; let me try.
Arrow 1: A normal association
UML has different types of lines and arrows. Above is the simple association arrow, that means that one class can have a link to the other class. Below I will explain each type WITH code examples.
In the first example, you can see that there isn't really specified who knows who (who is the owner of the relationship). An animal can know the human and the human can know the animal. It's not specified and thus not really helpful for the programmer.
In the second example, the artist can have a guitar. Because there is an arrow and there isn't one on the other side, we know that the guitar doesn't know the artist. A guitar is an object that can totally exist on its own and doesn't need anybody.
In the third example, you see a marriage. Really simple; the husband knows the wife and the wife knows her husband. In our situation, the husband has only one wife and vice versa.
How do we accomplish this usually in code?
class Husband{
Wife bestWomanInTheWorld;
public Husband(Wife theWife){
this.bestWomanInTheWorld = theWife;
}
}
Because the husband always needs a wife, we put the required relationship in the constructor. Because an artist can have a guitar, we would leave the constructor empty like this:
class Artist{
List<Guitar> guitars;
public Artist(){
}
public AddGuitarToCollection(Guitar newGuitar){
Guitars.Add(newGuitar);
}
}
So, that's how we accomplish this in code (most of the time!). You won't usually need different types of lines and arrows if you are new to programming. Keep it simple.
Arrow 2: Dependency
Okay, so we know about normal associations which we will use most of the time. But when will we use the 'dependency' arrow? Well, lets define a dependency (wikipedia):
Dependency is a weaker form of bond which indicates that one class depends on
another because it uses it at some point in time. One class depends on
another if the independent class is a parameter variable or local variable of
a method of the dependent class. This is different from an association, where
an attribute of the dependent class is an instance of the independent class.
Sometimes the relationship between two classes is very weak. They are not
implemented with member variables at all. Rather they might be implemented as
member function arguments.
If there is a connection, relation, association etc. that requires to be present, to the classA to work; it's a dependency. Example: Husband needs the Wife to exist. A car needs a wheel to be a car (and drive). A car factory needs a car class to make an object from it. Your RSSNewsItem class needs an XMLReader class to do anything.
When to use which?
Well, this is the only valid question in my eyes; since google shows alot of valid answers to your question. Try to never use a dependency in a class diagram because it usually means that you aren't specific enough. Always aim for associations, realisations etc. Only use realisations (in my opinion) if there is a required need to use an other class without maintaining a relationship. Example; Utility classes (like the XMLReader).
If you have any questions after reading this full explanation, feel free to ask. :-)
Dotted line indicates dependency to (in the direction of the arrow). Assuming you have assembled your source code neatly into separate files and headers for each class
- the give away is simply that the code includes the line #include ClassB.h.
HOWEVER The fact of the matter is that all class relationships (generalisation, realisation, composition, aggregation, association etc) all inherit the dependency relationship. For this reason I never use dotted arrows when documenting code. Where possible I would aim to document the relationship in more specific terms eg. diamonds, triangles etc. If I don't know the exact relationship my starting point is a solid line with arrows (an association, with (implicit) dependence).
Notwithstanding this the dotted arrow notation can be useful in other aspects of UML modelling eg. showing dependencies to requirements in Use Case analysis for example.
NOTE The Thought Police would have us reduce coupling & dependencies between classes by using interfaces (pure virtual classes) as far as practical.
Whilst pure virtual classes offer the prospect of multiple inheritance and tightest coupling of all between classes as is possible. Interface classes have the advantage that they are made entirely out of dark matter and so totally invisible to the police. With this in mind it is possible to write c++ code with apparently zero coupling between classes -which they love because they never really did understand all those funny looking symbols anyway.
dotted mean implements (an interface)
solid means extends (a base class)

Sharing data between model & view of an app

I'm currently trying to find a "definitive" solution (meaning : finding a solution that seems efficient a complying with OOP precepts) to a recurring problem I've been experiencing for some time : the problem of shared data in different parts of my code.
Take note that I'm not using any MVC framework anywhere here. I'm just refering to my data class as a Model and to the display class as a View (because its the proper names and have nothing to do with the MVC pattern, people made views & models way before the MVC pattern was "created").
Here's my problem :
Whenever I make an application that uses some quite expanded data (for example a game), I try to separate logic (movements, collisions, etc...) and display in two classes. But then, I stumble upon the problem : how to "bind" the data stored in my logic class with the corresponding display objects in my view class, without duplicating data, references, or other things between the different classes ?
Lets take a basic example :
I have a MyLogicClass, holding a Vector of "EntityData" objects (each with position, sizes, various states, everything to handle the logic of my items)
And I have a MyViewClass, creating and displaying Sprites for each EntityData that are in the MyLogicClass, and make them move after them being updated in the game loop.
The first thing that would come to my mind would be to store inside each data element its corresponding view, thus allowing me to loop throught my Vector to update the items logic then update the views accordingly. But that forces me to hold a MyLogicClass reference inside the MyViewClass, to be sure that I can target the entities data, forcing me to couple the two classes (things that I would prefer not to do).
On the other hand, there's the solution of each Entity having an ID, both in my data model (MyLogicClass's EntityData objects having an ID parameter) and in my View class (Sprites holding a reference to its original entity data ID). But when I want to target a specific entity that forces me to loop for it in my data model, then loop for it again to find the related Sprite in my View. This solution allows me to have loose coupling between my data and my view, but looping through hundreds of elements twice every frame (can happen !) really sounds not performance optimized for me.
I may be giving the whole problem a lot more importance that it should deserve, but I've been stumbling upon that more than one time, and I'd love to have some other views than mine about that.
Do you guys have any advice / solution for such an issue ?
Are there some other data formats / hierarchy that I may not be aware of for such case ?
What I've done is 'link' them together using events and event listeners. I have my "model parts" throw specific events that the "display parts" catch and render/update.
I've found this does let me structure some of my tests by writing testing code that would listener for certain events and error checks it that way. My code is still separated and testable on it's own: I can test my "model" by triggering and making sure the right events with the right values are being thrown. Like-wise, I can write some testing code to throw preset events that can be caught by the "display" to see if it has any issues.
Then once it is all working, I just reuse those same event listeners and link to 'each other'.
Later my "controller" (user input) would manipulate the "model" parts, which would cause events to be thrown to the "display" thus be rendered/updated.
I don't know if this is "correct" or not in terms of following the mvc pattern nor do I really have any formal knowledge on these sorts of things. I'd be interested in someone else's more knowledgeable opinion as well.
I think maybe you have over thought the problem. I do this sometimes.
Your view class has to have some type of link to the model obviously and an event is a great way to do it. Something bare bones here to give you an idea.
// Model class
package
{
class MyModel extends EventDispatcher
{
// you can make them public but that would
// be against some oop practices. so private it is
private var m_position:Vector2D;
MyModel(){}
// one way of doing getters/getters
// example: theModel.SetPosition(something);
public function GetPosition():Vector2D { return m_position; }
public function SetPosition(value:Vector2D):void
{
m_position = value;
ModelChanged();
}
// the other way
// sample: theModel.position = something;
public function get position():Vector2D {return m_position; }
public function set position(value:Vector2D):void
{
m_position = value;
ModelChanged();
}
private function ModelChanged():void
{
dispatchEvent(new Event(Event.CHANGE));
}
}
}
// now for our view.
package
{
class MyView extends Sprite // or whatever
{
private var model:MyModel;
MyView(model:MyModel)
{
this.model = model;
model.addEventListener(Event.CHANGE, handleModelChanged);
// fire off an event to set the initial position.
handleModelChanged(NULL);
}
private function handleModelChanged(evt:Event):void
{
x = model.position.x;
y = model.position.y;
// etc etc etc.
}
}
}
Anyhow you don't need the setters if your going to have the logic in the model file also obviously if nothing outside of the model needs to change it no reason for setters. But you do need the getters.
This decouples the model from the view and you can write any view any way you want and all you have to provide is a handler for when the model has changed. Just expose whatever data your views will need with getters.
You now only have to loop through the models and if one changes it will fire off an event and the views that are listening in will update.
hope I didn't miss anything and that explains what you were wanting.
Edit: I forgot to add, you don't have to have "ModelChanged()" all over the place if your using something like an update function. Just update and when your finished fire off the event.

Database for a multi-user RPG

I'm making a Flash turn-based RPG to practice OOP (who doesn't :P) I have a pretty good setup with the Weapons, Items, and all that Jazz. Though I'm currently considering how I will make my characters.
Currently I have an player and enemy class that extends the battler class.
Battler
/ \
/ \
Player Enemy
My player class has some functions that initialize the player itself, adding the graphics and all that. My party class calls on player, passing a paramater like so: player.setup(1) with 1 being the playerID.
To Clarify this is my player pseudocode:
{ setup(player_id)
player = **??????player_id??????????**
name = player.name
character_name = player.character_name
character_index = player.character_index
weapon_id = player.returnWeapon
/*---------
armor1_id = player.returnArmor //increase for other body parts
----------*/
level = player.level
}
My question, or more of a problem is how I will store the player data. I need to have many players as this is a game with many players in a party.
How will I actually use something like player.returnArmor ? Because when I do that it just calls a function, and it will not know who that player is (I guess I could use parameters, like player.returnArmor(player) but I think there is a better way to do this.
Any language is welcome, but just so you don't use assembly language as an example ;), C++, Actionscript 3, Ruby, and/or Java is fine. Please Help Me! Thank you in advance.
In AS3 you can have static and instance functions. If you call player.returnarmor(), you're calling a static function. You want to have an instance function, and call it for the instance of the player whose armor value you want.
If you have a few (<4) characters, you can just have named variables for each, but more than 3 or 4 and you should just have an array or other container for them.
var mainProtagonist:player;
var spunkySidekick:player;
var whiteMage:player;
var players:Array = new Array();
players.push(mainProtagonist);
players.push(spunkySidekick);
players.push(whiteMage);
Then to get a player's armor...we'll say you want the spunky sidekick's armor:
players[1].returnarmor();
// or
spunkySidekick.returnarmor();
You might have an array of all the players in existence, as well as another array, when used in battle, with just the players in the current party/battle. That way your enemies can target players at random, and only from those currently in the battle.
It might be worth considering using an entity system, where each item in the game is treated as a collection of unrelated properties (location, velocity, bitmap/mesh) which can be managed separately. This tends to make the hard problems easier (scalability, synchronisation, storage).
http://www.tomseysdavies.com/2011/01/23/entity-systems/
http://www.richardlord.net/blog/what-is-an-entity-framework
http://www.richardlord.net/blog/why-use-an-entity-framework

C#: Pass BusinessObject to 'BusinessLayer' Constructor or its methods?

I'm charged with the support of a C# Winforms app which uses BusinessObjects (containing no logic, just properties) and a BusinessLayer with classes ('Helpers') that manipulate those entities.
The question:
Should you pass in the BusinessObject to the Helpers constructor and then inside the constructor, instantiate the Helper's publicly accessible Entity variable
OR
Should you just pass the Entity to the methods that act on it?
Scenario 1: To the constructor
Car myCar = new Car();
CarHelper ch = new CarHelper(myCar);
ch.Wash(suds);
ch.Upgrade(upgradeKit);
ch.Save();
Scenario 2: To the methods that act on the Entity
Car myCar = new Car();
CarHelper ch = new CarHelper();
ch.Wash(myCar, suds);
ch.Upgrade(myCar, upgradeKit);
ch.Save(myCar);
Two major problems i have with Scenario 1:
A) The next developer has to dig into the CarHelper class to realise that it has a public Car accessor property which it references within methods that need it. This further obfuscates the Helper class in that each method needs to check against a 'null' Car property before performing its duties...
B) If there exists a bunch of other code in between operations, it can become unclear what ch.Wash() is actually doing...does it even act on a Car object at all...?
What does everyone think???
Is there any reason why you can't move the logic into the BusinessObject
Car myCar = new Car();
myCar.Wash(suds);
myCar.Upgrade(upgradeKit);
myCar.Save();
Do away with the helper class entirely. Makes more semantic sense to read, and there's no need to check for nulls.
Half as many classes to maintain as well
That's very true...wrapping up the logic in the BusinessObject to make it self-aware is best in my opinion too...i didn't consider that an option though because:
In 'the application' the BusinessObjects are in a namespace (....ApplicationServices) which is referenced by the DAO and so it can't actually call DAO methods (as it would cause a circular dependancy) - so it can't implement the functionality for
myCar.Wash(suds)
{
this.CleanlinessRating = suds.CleaningAbilityRating;
// persist the level of Cleanliness to the DB
CarDAO.Save(this);
}
It seems the premise behind the entire application is that the BusinessObjects do not implement any logic at all...they are just containers of information and do not have any behaviour.
Then you have BusinessLayer classes which act on the entities...
Then you have the DataLayer classes which persist the changes in the entites to the DB.
So apparently, making the Entities self aware and implement their own behaviour is a big 'no no' (in this application)... i'm sure that is the real problem here.
However, assuming i can't change that, what would you do?
Pass the entity to the methods that act on it?
OR
Wrap the entity into the constructor of the Helper class?
What about making your CarHelper class extend Car
CarHelper helper = new Car();
helper.Wash(suds);
helper.Upgrade(upgradeKit);
helper.Save();
Best of both worlds

Abstract in programming

The word abstract is when we talk about a queue class or any class. A class is abstract right? How's the word abstract used in programming. Somehing that is abstract? What does that mean?
Abstract in OO is used to indicate that the class cannot be instantiated directly and must be inherited from before instantiation. Wiki explains this nicely.
Abstract means that you are discussing an idea one or more levels away from any specific example that you can actually point to or create.
As far as classes are concerned, an abstract class is abstract because it can't be instantiated. A specific class that can be instantiated is concrete, and it may be an example of a certain abstract class.
Similarly, if your data structures class discusses an 'abstract' data type such as a Queue, the teacher means Queue as 'a FIFO data structure'. Slightly less absract is Java's AbstractQueue. A concrete queue that you can "point to" (not in the sense of pointers and memory, but in the sense "THERE is a queue!") could be Java's LinkedBlockingQueue
`Abstract` ... ... ... ... ... ... ... ... ... `Concrete`
a queue AbstractQueue LinkedBlockingQueue
a group an infinite group positive integers
a car a Ford 1995 Ford Taurus My 1995 Ford Taurus VIN# 3489230148230
The term "abstract" can mean a whole bunch of different things, depending on the context.
The two most common uses of "abstract" pertain to object-oriented programming. A method is called "abstract" (or, in C++-speak, "pure virtual") if the method does not have an implementation. The purpose of an abstract method is to indicate that classes that inherit from the given class will all have a method with the given signature, but there is no reasonable default behavior for that method. A common example is, in a class hierarchy of shapes, that the base class for shapes might have an abstract method that draws the shape on the screen. There is no good default behavior for drawing "a shape" - what shape it it? - but any individual shape will have a concrete implementation of this function.
A related term is an "abstract class," which is a class that contains an abstract method. Because the class contains this abstract method, you can't have a concrete object of that class type. Otherwise, if you tried calling the abstract method, you'd find out that there was no implementation associated with it.
In an entire different context, the word "abstract" sometimes shows up in the term "abstract data type," which is a term used to describe an object supporting some set of mathematical operations without necessarily explaining how those operations are implemented. For example, "stack," "queue," and "list" are all abstract data types, since they describe what behaviors are expected of a given type of object without giving implementation (e.g. dynamic array? linked list? hash table?)
The term "abstract" also comes up in "abstraction," which is some simplification of a complex system into something more managable. For example, network routing is usually broken down into a different number of "layers," each of which are responsible for handling some part of the end-to-end communication. Each layer is tasked with a specific job, and must take in input and produce output in a predetermined fashion. This lets programmers work on one layer treat all the other layers as "black boxes" that magically get the job done, since provided that you give input to the layer in the right form or read the output of some layer in a specific manner, you don't need to worry about the details of how that layer works.
Hope this helps!
Well a good example in OO is an Animal, you'd have an abstract class like so:
abstract class Animal
{
public AnimalType Type { get; set; }
}
Now you can't declare an animal outright, you must have a class that inherits from an animal, like a cat:
class Cat : Animal
{
public Cat()
{
Type = AnimalType.Feline;
}
}
So this wouldn't work:
Animal a = new Animal();
But this would:
Animal a = new Cat();
So in essence, what you're saying, is this is a base class, you can't make one on it's own, you need more information, say a class that inherits from it. Kind of hard to explain, so hope the example helps!
Abstract classes cannot be instantiated and instead are inherited from by other classes, generally concrete ones. They usually contain code that is common to inheriting classes to minimize code duplication.
I think it can mean a couple of things related to programming. But, for me, I think of it related to virtual methods, which may perform different tasks depending on the underlying object type. That would be in contrast to a method that always does the same, fixed set of operations.
In fact there are "abstract classes", where one or more methods are pure virtual, which means they are not implemented by that class. Such a class cannot be instantiated. Instead, you must derive a new class from it that implements the pure virtual methods, and then you can instantiate the second class.
Abstraction is a way of building compound objects from simpler ones. A function for example can be seen a form of black box abstraction ..where the inner workings of the function are hidden from the user.
Data abstraction in general is a methodology that enables programmers to isolate how a compound data object is used from the details of how it is constructed from more primitive data objects.