This is as much a question about learning object-oriented methodology, for me, as it is about VBA syntax. Suppose I create several classes, like Car, Truck, Bus, etc. And I create another class SpeedCalculator, which instances of my vehicles will instantiate and contain. (As a newbie, let me note that this strikes me as a good time to declare a class as static and not instantiate it--which vba can't do I don't think... .) Now this speed calculator will be no simple speedometer. Rather it will calculate speed from temperature, windspeed, RPMs, etc, etc--go along with this please, just for the sake of the example.
Now the question is how for the contained object to collect its inputs, which are only available in the container objects (the vehicle objects might implement an interface (if VBA can even do that...)). "Parent." is wrong, I figured out eventually, b/c parent-child is an inheritance relation (which VBA doesn't have, again), not a containment relation, and the parent of the contained object is an Excel Application (not my object). So it seems it would be nice if there were another keyword to refer to container properties. I hope I haven't just missed something simple. Or is it more the case that that sort of reference would break object-oriented encapsultaion principles?
I guess a second approach would be to pass the container to the contained, via "Me" as an argument. But then you have to multiply all of the contained's methods, either to overload them (if VBA can even do that...), or with variously named versions--due to the different types of the containers (can we be more idealist and avoid declaring as variant or "Object"?).
And then door #3 would be the last door standing, I guess? Which would be to pass an (annoying) litany of arguments. The definition of all of which would tend to defeat the purpose of having my tidy little calculator class?
It's not clear to me from your question whether or not you already know VBA and/or OO, and are just asking how to use the object-oriented features of VBA. If you are new to both VBA and OO, see below for some thoughts on why VBA isn't a very good vehicle for learning OOD/OOP.
To address the general part of your question, VBA classes can implement interfaces. This is how you express inheritance of interface (an "is-a" relationship) in VBA. There is no direct way to express inheritance of implementation in VBA. Instead, to make one class inherit the implementation of another, you have the first implement the interface of the second, contain an instance of the second, and then delegate calls to that instance. See this answer for more:
VBA inheritance, analog of super
There is a link there, that I will repeat here, to the Visual Studio 6.0 Programmer's Guide:
http://msdn.microsoft.com/en-us/library/aa240846(v=VS.60).aspx
It's as good a short introduction as any on the "VBA way" of OOP (although it's written for VB6, not VBA).
Now, for your specific question about design: "how for the contained object to collect its inputs, which are only available in the container objects".
You need to think about what you are actually modeling here. Regardless of how you implement it, a "speed calculator" should only get to know about a very specific set of inputs, not the entire internal state of whatever vehicle is using it. In VBA, as you note, there are no static classes. Instead, use a regular code module and have a function that you call from inside your vehicle class(es):
Public Function calcSpeed(temp, windspeed, rpm)
'do calc based only on parms passed in...
End Function
If it needs to take a zillion parameters because that's how the calculation works, so be it. Don't try to hide it. Of course, you can wrap them up in a Type or in a class if there are too many.
Now, does every different kind of vehicle calculate speed in the exact same way from the exact same set of state parameters? If so, then have a speed property or method that is implemented by your "base vehicle" class and call calcSpeed from there.
But maybe it's the case that different kinds of vehicles have different state parameters, or use different calculation methods, or the calculation is the same but not every vechicle type supplies every parameter. In that case, put the speed method in the base vehicle interface, but "override" it as needed in the implementation of each subclass. (Maybe then calcSpeed is too simplistic, and you'd end up with a library of speed calculation helper functions.)
One thing I would not do, is have a generic SpeedCalculator class that takes a Vehicle argument and then interrogates it for its state in order to do the calc. The reason why not is expressed very well in these classic articles:
http://media.pragprog.com/articles/may_04_oo1.pdf
http://pragprog.com/articles/tell-dont-ask
http://www.cmcrossroads.com/bradapp/docs/demeter-intro.html
There's also this:
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
which has a quote I like:
So, what's so bad about this code
(besides being a horribly contrived
example)? Well, lets translate what
the code is actually doing into
real-language:
Apparently, when the
paperboy stops by and demands payment,
the customer is just going to turn
around, let the paperboy take the
wallet out of his back pocket, and
take out two bucks.
I don't know about
you, but I rarely let someone handle
my wallet. There are a number of
'realworld' problems with this, not to
mention we are trusting the paperboy
to be honest and just take out what
he's owed. If our future Wallet object
holds credit cards, the paperboy has
access to those too... but the basic
problem is that “the paperboy is being
exposed to more information than he
needs to be”.
Thats an important
concept... The 'Paperboy' class now
'knows' that the customer has a
wallet, and can manipulate it. When we
compile the Paperboy class, it will
need the Customer class and the Wallet
class. These three classes are now
'tightly coupled'. If we change the
Wallet class, we may have to make
changes to both of the other classes.
ADDED AS PROMISED IN COMMENTS:
It's not that you couldn't readily have an instance of a class Speedometer contained within your Vehicles. (My example of a simple function might be too simplistic. Maybe you need a class to model the other things about speedometers - they have mass, take up space, etc.) It's how the two classes depend on each other. In this example, Vehicle needs to know about Speedometer. But why should the reverse be true? If Speedometer takes a Vehicle as a parameter, and then asks it for the particular things it needs to know to calculate speed, the code will certainly work. However, you've coupled Speedometer to Vehicle more tightly than necessary.
One of the reasons to use an OO approach in the first place is because it lets you be more exact about how concepts relate to each other. It's better to have Vehicle tell Speedometer, "Here are some facts about the world. Give me back a speed.", rather than, "Here I am, Me, the Vehicle that contians you. Ask me whatever you need to about anything related to me, and then give me back a speed." (Note that whether the "facts about the world" are raw temp, windspeed, etc., or an instance of some SpeedometerInput Type/Class isn't the issue. It's that speedometers don't need to know all about vehicles.)
Using the most exact interface you can get away with doesn't make that big of a deal in a simple example. But it becomes huge when added up over many design decisions.
Finally, If you have a choice, I wouldn't use VBA as a vehicle for learning object-oriented design or programming. You can do "OOP" in VBA, but in a Microsoft-/COM-specific way that is literally a relic from the mid-1990s. You can browse around stackoverflow for plenty of examples of things that are normally done in OO programming languages (and with their much better libraries) that are cumbersome and tricky in VBA. Here are a few off the top of my head that I've either asked or answered:
Is there a way to overload the constructor / initialize procedure for a class in VBA?
Is there a way to write an equality test for a VBA class with private members without exposing knowledge of the existence of those private members?
Restrict type in a Collection inside a class module
Excel-VBA - Is there anything like Javas Set container in VBA?
So, unless you're either constrained to learn with VBA because you can't install anything but MS Office on your machine, or you plan to be doing a lot of VBA work becuase you're using Excel, Access, etc. and have some problems where OOP can help, I'd look elsewhere. Python, .NET, or Java are all available for free on Windows and have tons of resources available for the beginner.
I'm not sure if this is what you're looking for, but I'll give it a shot. If Car class contains one Speedometer class, Car contains Windspeed and Acceleration properties, Speedometer contains a Mass property, and speed is defined as Windspeed times Acceleration divided by Mass, then here's how I would set it up.
In class CCar
Private mlCarID As Long
Private mdWindSpeed As Double
Private mdAcceleration As Double
Private mclsSpeedometer As CSpeedometer
'Getters and setters
Public Property Get CarID() As Long: CarID = mlCarID: End Property
Public Property Let CarID(ByVal lCarID As Long): mlCarID = lCarID: End Property
Public Property Get Acceleration() As Double: Acceleration = mdAcceleration: End Property
Public Property Let Acceleration(ByVal dAcceleration As Double): mdAcceleration = dAcceleration: End Property
Public Property Get WindSpeed() As Double: WindSpeed = mdWindSpeed: End Property
Public Property Let WindSpeed(ByVal dWindSpeed As Double): mdWindSpeed = dWindSpeed: End Property
'read only property to the speedometer class
Public Property Get Speedometer() As CSpeedometer
Set Speedometer = mclsSpeedometer
End Property
'create the child and set the parent property
Private Sub Class_Initialize()
Set mclsSpeedometer = New CSpeedometer
Set mclsSpeedometer.Parent = Me
End Sub
Private Sub Class_Terminate()
Set mclsSpeedometer.Parent = Nothing
Set mclsSpeedometer = Nothing
End Sub
'pass through property
Public Property Get Speed() As Double
Speed = Me.Speedometer.Speed
End Property
In class CSpeedometer
Private mdMass As Double
Private mclsParent As CCar
Public Property Get Mass() As Double: Mass = mdMass: End Property
Public Property Let Mass(ByVal dMass As Double): mdMass = dMass: End Property
Public Property Get Parent() As CCar
Set Parent = mclsParent
End Property
Public Property Set Parent(clsCar As CCar)
Set mclsParent = clsCar
End Property
Public Property Get Speed() As Double
'references to parent properties
Speed = Me.Parent.WindSpeed * Me.Parent.Acceleration / Me.Mass
End Property
In a standard module
Sub GetSpeed()
Dim clsCar As CCar
Set clsCar = New CCar
clsCar.CarID = 1
clsCar.WindSpeed = 10
clsCar.Acceleration = 5
clsCar.Speedometer.Mass = 100
Debug.Print clsCar.Speed
End Sub
You have to make sure you destroy your parent/child relationship properly or you'll get a memory leak. I use CopyMemory to set up parent properties to avoid that particular problem. It's described here http://www.dailydoseofexcel.com/archives/2007/12/28/terminating-dependent-classes/#comment-29661
Related
So, I have bound the CombatController to an object called "godObject". In the Start() method, I call init() functions on other classes. I did this so I can control the order in which objects are initialized since, for example, the character controller relies on the grid controller being initialized.
Quick diagram:
-------------------- calls
| CombatController | ----------> CameraController.init();
-------------------- |
| ---> GridController.init();
|
| ---> CharacterController.init();
So, now I have a slight problem. I have multiple properties that I need in every controller. At the moment, I have bound everything to the combat controller itself. That means that, in every controller, I have to get an instance of the CombatController via GameObject.Find("godObject).GetComponent<CombatController>(). To be honest, I don't think this is good design.
My idea now was to create a BaseCombatController that extends MonoBehavior, and then have all other classes like GridController, CharacterController etc. extend the BaseCombatController. It might look like this:
public class BaseCombatController : MonoBehaviour
{
public GameObject activePlayer;
public void setActivePlayer(GameObject player) {
this.activePlayer = player;
}
... more stuff to come ...
}
This way, I could access activePlayer everywhere without the need to create a new instance of the CombatController. However, I'm not sure if this doesn't have possible side effects.
So, lots of text for a simple question, is that safe to do?
I use inheritance in Unity all the time. The trick, like you have in the question, is to allow your base class to inherit from monobehavior. For Example:
public class Base Item : Monobehavior
{
public string ItemName;
public int Price;
public virtual void PickUp(){//pickup logic}
//Additional functions. Update etc. Make them virtual.
}
This class sets up what an item should do. Then in a derived class you can change and extend this behavior.
public class Coin : BaseItem
{
//properties set in the inspector
public override void PickUp(){//override pickup logic}
}
I have used this design pattern a lot over the past year, and am currently using it in a retail product. I would say go for it! Unity seems to favor components over inheritance, but you could easily use them in conjunction with each other.
Hope this helps!
As far as I can see this should be safe. If you look into Unity intern or even Microsoft scripts they all extend/inhert (from) each other.
Another thing you could try would be the use of interfaces, here is the Unity Documentation to them: https://unity3d.com/learn/tutorials/topics/scripting/interfaces if you want to check it out.
You are right that GameObject.Find is pure code smell.
You can do it via the inheritance tree (as discussed earlier) or even better via interfaces (as mentioned by Assasin Bot), or (I am surprised no one mentioned it earlier) via static fields (aka the Singleton pattern).
One thing to add from experience - having to have Inits() called in a specific order is a yellow flag for your design - I've been there myself and found myself drowned by init order management.
As a general advice: Unity gives you two usefull callbacks - Awake() and Start(). If you find yourself needing Init() you are probably not using those two as they were designed.
All the Awakes() are guaranteed (for acvie objects) to run before first Start(), so do all the internal object initialisation in Awake(), and binding to external objects on Start(). If you find yourself needing finer control - you should probably simplify the design a bit.
As a rule of thumb: all objects should have their internal state (getcomponents<>, list inits etc) in order by the end of Awake(), but they shold not make any calls depending on other objects being ready before Start(). Splitting it this way usually helps a lot
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.
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
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.
What is the best way of adding a new object in the entity framework. The designer adds all these create methods, but to me it makes more sense to call new on an object. The generated CreateCustomer method e.g. could be called like this:
Customer c = context.CreateCustomer(System.Guid.NewGuid(), "Name"));
context.AddToCustomer(c);
where to me it would make more sense to do:
Customer c = new Customer {
Id = System.Guid.NewGuid(),
Name = "Name"
};
context.AddToCustomer(c);
The latter is much more explicit since the properties that are being set at construction are named. I assume that the designer adds the create methods on purpose. Why should I use those?
As Andrew says (up-voted), it's quite acceptable to use regular constructors. As for why the "Create" methods exist, I believe the intention is to make explicit which properties are required. If you use such methods, you can be assured that you have not forgotten to set any property which will throw an exception when you SaveChanges. However, the code generator for the Entity Framework doesn't quite get this right; it includes server-generated auto increment properties, as well. These are technically "required", but you don't need to specify them.
You can absolutely use the second, more natural way. I'm not even sure of why the first way exists at all.
I guess it has to do with many things. It looks like factory method to me, therefore allowing one point of extension. 2ndly having all this in your constructor is not really best practice, especially when doing a lot of stuff at initialisation. Yes, your question seems reasonable, i even agree with it, however, in terms of object design, it is more practical as they did it.
Regards,
Marius C. (c_marius#msn.com)