AS3 targeting controller class variable using string - class

I'm looking for a way of condensing some of my AS3 code to avoid almost duplicate commands.
The issue is that I have multiple variables with almost the same name e.g. frenchLanguage, englishLanguage, germanLanguage, spanishLanguage
My Controller class contains public static variables (these are accessed across multiple classes) and I need a way to be able to call a few of these variables dynamically. If the variables are in the class you are calling them from you can do this to access them dynamically:
this["spanish"+"Language"]
In AS3 it's not possible to write something like:
Controller.this["spanish"+"Language"]
Is there any way to achieve this? Although everything is working I want to be able to keep my code as minimal as possible.

It is possible to access public static properties of a class this way (assuming the class name is Controller as in your example:
Controller['propertyName']
I'm not sure how this helps to have "minimal code", but this would be a different topic/question, which might need some more details on what you want to achive.
Having said that, I like the approach DodgerThud suggests in the comments of grouping similar values in a (dynamic) Object or Dictonary and give it a proper name.
Keep in mind, that if the string you pass in as the key to the class or dynamic object is created from (textual) user input you should have some checks for the validity of that data, otherwise your programm might crash or expose other fields to the user.

It would make sense to utilize a Dictionary object for a set of variables inherited: it provides a solid logic and it happens to work...
I do not think this is what you are trying to accomplish. I may be wrong.
Classes in AS3 are always wrapped within a package - this is true whether you have compiled from Flash, Flex, Air, or any other...
Don't let Adobe confuse you. This was only done in AS3 to use Java-Based conventions. Regardless, a loosely typed language is often misunderstood, unfortunately. So:
this["SuperObject"]["SubObject"]["ObjectsMethod"][ObjectsMethodsVariable"](args..);
... is technically reliable because the compiler avoids dot notation but at runtime it will collect a lot of unnecessary data to maintain those types of calls.
If efficiency becomes an issue..
Use:
package packages {
import flash.*.*:
class This implements ISpecialInterface {
// Data Objects and Function Model
// for This Class
}
package packages {
import...
class ISpecialInterface extends IEventDispatcher

Related

Any way to trigger creation of a list of all classes in a hierarchy in Swift 4?

Edit: So far it looks like the answer to my question is, "You can't do that in Swift." I currently have a solution whereby the subclass names are listed in an array and I loop around and instantiate them to trigger the process I'm describing below. If this is the best that can be done, I'll switch it to a plist so that least it's externally defined. Another option would be to scan a directory and load all files found, then I would just need to make sure the compiler output for certain classes is put into that directory...
I'm looking for a way to do something that I've done in C++ a few times. Essentially, I want to build a series of concrete classes that implement a particular protocol, and I want to those classes to automatically register themselves such that I can obtain a list of all such classes. It's a classic Prototype pattern (see GoF book) with a twist.
Here's my approach in C++; perhaps you can give me some ideas for how to do this in Swift 4? (This code is grossly simplified, but it should demonstrate the technique.)
class Base {
private:
static set<Base*> allClasses;
Base(Base &); // never defined
protected:
Base() {
allClasses.put(this);
}
public:
static set<Base*> getAllClasses();
virtual Base* clone() = 0;
};
As you can see, every time a subclass is instantiated, a pointer to the object will be added to the static Base::allClasses by the base class constructor.
This means every class inherited from Base can follow a simple pattern and it will be registered in Base::allClasses. My application can then retrieve the list of registered objects and manipulate them as required (clone new ones, call getter/setter methods, etc).
class Derived: public Base {
private:
static Derived global; // force default constructor call
Derived() {
// initialize the properties...
}
Derived(Derived &d) {
// whatever is needed for cloning...
}
public:
virtual Derived* clone() {
return new Derived(this);
}
};
My main application can retrieve the list of objects and use it to create new objects of classes that it knows nothing about. The base class could have a getName() method that the application uses to populate a menu; now the menu automatically updates when new subclasses are created with no code changes anywhere else in the application. This is a very powerful pattern in terms of producing extensible, loosely coupled code...
I want to do something similar in Swift. However, it looks like Swift is similar to Java, in that it has some kind of runtime loader and the subclasses in this scheme (such as Derived) are not loaded because they're never referenced. And if they're not loaded, then the global variable never triggers the constructor call and the object isn't registered with the base class. Breakpoints in the subclass constructor shows that it's not being invoked.
Is there a way to do the above? My goal is to be able to add a new subclass and have the application automatically pick up the fact that the class exists without me having to edit a plist file or doing anything other than writing the code and building the app.
Thanks for reading this far — I'm sure this is a bit of a tricky question to comprehend (I've had difficulty in the past explaining it!).
I'm answering my own question; maybe it'll help someone else.
My goal is to auto initialize subclasses such that they can register with a central authority and allow the application to retrieve a list of all such classes. As I put in my edited question, above, there doesn't appear to be a way to do this in Swift. I have confirmed this now.
I've tried a bunch of different techniques and nothing seems to work. My goal was to be able to add a .swift file with a class in it and rebuild, and have everything automagically know about the new class. I will be doing this a little differently, though.
I now plan to put all subclasses that need to be initialized this way into a particular directory in my application bundle, then my AppDelegate (or similar class) will be responsible for invoking a method that scans the directory using the filenames as the class names, and instantiating each one, thus building the list of "registered" subclasses.
When I have this working, I'll come back and post the code here (or in a GitHub project and link to it).
Same boat. So far the solution I've found is to list classes manually, but not as an array of strings (which is error-prone). An a array of classes such as this does the job:
class AClass {
class var subclasses: [AClass.Type] {
return [BClass.self, CClass.self, DClass.self]
}
}
As a bonus, this approach allows me to handle trees of classes, simply by overriding subclasses in each subclass.

Are UE4 Blueprints the same with a C++ class? If so, how will I implement a class design?

Good day! I am new to using Unreal Engine 4 and I have a few questions about how exactly blueprints work. From my understanding of it, every blueprint works like a class. By that I mean one blueprint is much like one class in an OOP programming language.
Please educate me as to - if my assumption is correct or wrong. If wrong, then maybe you could help me achieve what I want in a different method/perspective. I am willing to learn and accept suggestions.
If at some point my understanding is correct - that blueprints are actually individual classes - I would really appreciate it if you could (please) guide as to where to go and how to implement a design that I want to create. This is from a programmers perspective (PHP OOP Programming). Forgive the approach, I'm just using PHP to logically express how I want the class to work. Plus, it is the only OOP programming I know atm.
I want to create a class named: Items. class Item {}
This class is going to handle everything item related, thus we will have to give it a lot of properties/variable. (Below is just an example; Again I'm using PHP as an example.)
class Item {
var $id;
var $name;
var $description;
var $type;
var $subType;
var $mesh;
var $materials;
}
3.) I would like to initiate this class by having two variables as its construct arguments. (We will require itemID and itemType). This is because I will use these two variables to retrieve the item's data which is already available in a data table. I will use those data in the table to populate the class properties/variables. (I'm not sure if I said that right. I hope you understood my point anyway.)
class Item {
var $id;
var $name;
var $description;
var $type;
var $subType;
var $mesh;
var $materials;
function _construct($cons_itemID, $cons_itemType) {
/*-- Start getting the item Data here based on what item and type provided. Then, push that data into the class properties/variables. We will use individual methods/functions to fill other properties/variables later. --*/
}
}
4.) Basically with that design I could easily pass on an item ID to the class and then get the item's name, description, mesh, materials and etc using pointers.
Example:
$weapon = new Item('10001','Weapon');
$weaponMesh = $weapon->getMesh();
$armor = new Item('12345','Armor');
$armorName = $armor->getName();
I'm just having a lot of trouble working with blueprint and achieve this method or even something similar to it. I'm not trying to avoid C++, I would love to learn it but I just don't have the time freedom right now.
Few things I have tried to make it work:
Casting / Casting to class (But I couldn't figure out what the target object will be and how was I going to add input arguments into the class that way? There isn't any input there that I could use.)
Spawn Actor (This one is very promising, I need to dig in deeper into this)
Blueprint Macros? Blueprint Interfaces? (I'm just lost.)
For all those who will help or answer. Thank you!
~ Chris
So far as I know, yes, we can assume that each blueprint can be viewed as class. (Moreover, since UE 4.12 (in UE 4.11 that functionality is marked as experimental I think) you can check Compile blueprints under Project settings -> Packaging. That will create native class for each blueprint.)
You can create either Blueprint or C++ class based on Object (UObject in C++). Then you can specify all properties (or variables in UE editor terminology). In BP you have small advantage: you can mark some properties as Visible at spawn (they must be Public and Visible). So when you are creating new instance of that class, you can explicitly pass values to that properties.
And in BP Construct event, that properties are correctly filled, thus you can set another properties values based on given ID and Type.
In C++ class having different arguments than FObjectInitializer is not possible, thus you don't have that values in time when constructor is executed. But it is not so hard to achieve same functionality, you can find example here: https://answers.unrealengine.com/questions/156055/passing-arguments-to-constructors-in-ue4.html.
Something about list of what you had tried:
Spawn actor - derive from actor only if you intend to have that BP in scene. Actors are subjects to game updates and rendering, so having actor only as data container is very wrong.
BP Macro is same as BP Function except function will be called just like function (so executing necesary actions by function call conventions) and macro will replace it's implementation in place, where you are calling that macro. More exhausting explanation here.
If I would implement your code, I'd do it like I said and then I'll have that class as property in some component and that component would be attached to some actor, which would be placed in scene.

Dependency injection and when to use static classes

Are static classes pretty much always frowned upon, or is there ever a good time to use them?
For example, would it make sense to implement something ubiquitous in your application like security in a static class? You could still use property injection on the static class to change out the implementation, and if you were to use something like MEF to inject the implementation then I would think it wouldn't get in the way of your tests.
I use static classes mainly for stateless helper classes and when I want to create extension methods. I try to avoid static classes that have state because as you mention it can get in the way of the tests.
Let's say you decide to add state to a static class. To test the methods of this class that depend on its state you will have to find a way to change this state during the tests. This means that you have to:
Prepare the state before each test.
Clear the state after each test.
This means that the class will need to offer a way (by means of internal methods or internal property setters) to alter its state which can be dangerous. If you want to create immutable classes or classes that encapsulate completely their implementation details then you will not be able to test them easily (if not at all) and your test might break more often from changes to the implementation. Even with MEF it will not be easy to do this.
Of course static class sometimes offer attractive solutions for problems like logging and,as mentioned in your question, security. In these cases I would go for a static class that delegates all calls to a private readonly field. This way the class of this field can be unit tested normally. You can then test the static class in your integration tests.
By the way have a look at .NET's design guidelines for static classes. It doesn't include anything relevant to your question but it includes valuable advice.

Need suggestions regarding Interface refactoring

I have inherited a project that has an awkwardly big interface declared (lets call it IDataProvider). There are methods for all aspects of the application bunched up inside the file. Not that it's a huge problem but i'd rather have them split into smaller files with descriptive name. To refactor the interface and break it up in multiple interfaces (let's say IVehicleProvider, IDriverProvider etc...) will require massive code refactoring, because there are a lot of classes that implement the interface. I'm thinking of two other ways of sorting things out: 1) Create multiple files for each individual aspect of the application and make the interface partial or 2) Create multiple interfaces like IVehicleProvider, IDriverProvider and have IDataProvider interface inhertit from them.
Which of the above would you rather do and why? Or if you can think of better way, please tell.
Thanks
This book suggests that interfaces belong, not to the provider, but rather to the client of the interface. That is, that you should define them based on their users rather than the classes that implement them. Applied to your situation, users of IDataProvider each use (probably) only a small subset of the functionality of that big interface. Pick one of those clients. Extract the subset of functionality that it uses into a new interface, and remove that functionality from IDataProvider (but if you want to let IDataProvider extend your new interface to preserve existing behavior, feel free). Repeat until done - and then get rid of IDataProvider.
This is difficult to answer without any tags or information telling us the technology or technologies in which you are working.
Assuming .NET, the initial refactoring should be very minimal.
The classes that implement the original interface already implement it in its entirety.
Once you create the smaller interfaces, you just change:
public class SomeProvider : IAmAHugeInterface { … }
with:
public class SomeProvider : IProvideA, IProvideB, IProvideC, IProvideD { … }
…and your code runs exactly the way it did before, as long as you haven't added or removed any members from what was there to begin with.
From there, you can whittle down the classes on an as-needed or as-encountered basis and remove the extra methods and interfaces from the declaration.
Is it correct that most if not all of the classes which implement this single big interface have lots of methods which either don't do anything or throw exceptions?
If that isn't the case, and you have great big classes with lots of different concerns bundled into it then you will be in for a painful refactoring, but I think handling this refactoring now is the best approach - the alternatives you suggest simply push you into different bad situations, deferring the pain for little gain.
One thing to can do is apply multiple interfaces to a single class (in most languages) so you can just create your new interfaces and replace the single big interface with the multiple smaller ones:
public class BigNastyClass : IBigNastyInterface
{
}
Goes to:
public class BigNastyClass : ISmallerInferface1, ISmallerInterface2 ...
{
}
If you don't have huge classes which implement the entire interface, I would tackle the problem on a class by class basis. For each class which implements this big interface introduce a new specific interface for just that class.
This way you only need to refactor your code base one class at a time.
DriverProvider for example will go from:
public class DriverProvider : IBigNastyInterface
{
}
To:
public class DriverProvider : IDriverProvider
{
}
Now you simply remove all the unused methods that weren't doing anything beyond simply satisfying the big interface, and fix up any methods where DriverProvider's need to be passed in.
I would do the latter. Make the individual, smaller interfaces, and then make the 'big' interface an aggregation of them.
After that, you can refactor the big interface away in the consumers of it as applicable.

Single Responsibility Principle: do all public methods in a class have to use all class dependencies?

Say I have a class that looks like the following:
internal class SomeClass
{
IDependency _someDependency;
...
internal string SomeFunctionality_MakesUseofIDependency()
{
...
}
}
And then I want to add functionality that is related but makes use of a different dependency to achieve its purpose. Perhaps something like the following:
internal class SomeClass
{
IDependency _someDependency;
IDependency2 _someDependency2;
...
internal string SomeFunctionality_MakesUseofIDependency()
{
...
}
internal string OtherFunctionality_MakesUseOfIDependency2()
{
...
}
}
When I write unit tests for this new functionality (or update the unit tests that I have for the existing functionality), I find myself creating a new instance of SomeClass (the SUT) whilst passing in null for the dependency that I don't need for the particular bit of functionality that I'm looking to test.
This seems like a bad smell to me but the very reason why I find myself going down this path is because I found myself creating new classes for each piece of new functionality that I was introducing. This seemed like a bad thing as well and so I started attempting to group similar functionality together.
My question: should all dependencies of a class be consumed by all its functionality i.e. if different bits of functionality use different dependencies, it is a clue that these should probably live in separate classes?
When every instance method touches every instance variable then the class is maximally cohesive. When no instance method shares an instance variable with any other, the class is minimally cohesive. While it is true that we like cohesion to be high, it's also true that the 80-20 rule applies. Getting that last little increase in cohesion may require a mamoth effort.
In general if you have methods that don't use some variables, it is a smell. But a small odor is not sufficient to completely refactor the class. It's something to be concerned about, and to keep an eye on, but I don't recommend immediate action.
Does SomeClass maintain an internal state, or is it just "assembling" various pieces of functionality? Can you rewrite it that way:
internal class SomeClass
{
...
internal string SomeFunctionality(IDependency _someDependency)
{
...
}
internal string OtherFunctionality(IDependency2 _someDependency2)
{
...
}
}
In this case, you may not break SRP if SomeFunctionality and OtherFunctionality are somehow (functionally) related which is not apparent using placeholders.
And you have the added value of being able to select the dependency to use from the client, not at creation/DI time. Maybe some tests defining use cases for those methods would help clarifying the situation: If you can write a meaningful test case where both methods are called on same object, then you don't break SRP.
As for the Facade pattern, I have seen it too many times gone wild to like it, you know, when you end up with a 50+ methods class... The question is: Why do you need it? For efficiency reasons à la old-timer EJB?
I usually group methods into classes if they use a shared piece of state that can be encapsulated in the class. Having dependencies that aren't used by all methods in a class can be a code smell but not a very strong one. I usually only split up methods from classes when the class gets too big, the class has too many dependencies or the methods don't have shared state.
My question: should all dependencies of a class be consumed by all its functionality i.e. if different bits of functionality use different dependencies, it is a clue that these should probably live in separate classes?
It is a hint, indicating that your class may be a little incoherent ("doing more than just one thing"), but like you say, if you take this too far, you end up with a new class for every piece of new functionality. So you would want to introduce facade objects to pull them together again (it seems that a facade object is exactly the opposite of this particular design rule).
You have to find a good balance that works for you (and the rest of your team).
Looks like overloading to me.
You're trying to do something and there's two ways to do it, one way or another. At the SomeClass level, I'd have one dependency to do the work, then have that single dependent class support the two (or more) ways to do the same thing, most likely with mutually exclusive input parameters.
In other words, I'd have the same code you have for SomeClass, but define it as SomeWork instead, and not include any other unrelated code.
HTH
A Facade is used when you want to hide complexity (like an interface to a legacy system) or you want to consolidate functionality while being backwards compatible from an interface perspective.
The key in your case is why you have the two different methods in the same class. Is the intent to have a class which groups together similar types of behavior even if it is implemented through unrelated code, as in aggregation. Or, are you attempting to support the same behavior but have alternative implementations depending on the specifics, which would be a hint for a inheritance/overloading type of solution.
The problem will be whether this class will continue to grow and in what direction. Two methods won't make a difference but if this repeats with more than 3, you will need to decide whether you want to declare it as a facade/adapter or that you need to create child classes for the variations.
Your suspicions are correct but the smell is just the wisp of smoke from a burning ember. You need to keep an eye on it in case it flares up and then you need to make a decision as how you want to quench the fire before it burns out of control.