How to access object parent in D - oop

Say I have a class, Master, that starts up my program, and I have another class, TerminalIO, that has functions and data for talking to stdin and stdout. I then instantiate a Master object from main().
In code within the methods of TerminalIO, how would I access the properties and functions of Master?
The reason I'm asking about this is because my program needs to store some shared data (both enums and regular variables), and I was wanting to know of an efficient way to do that. I'm not so sure this is the best way, but it's certainly better than toying with the package keyword and trying to store "global" data at module level or whathaveyou.
I think it's worth noting that I will have many other objects that also want access to this shared data, so a simple reference may not be the best of ideas.

You will have to get a reference to Master inside your TerminalIO.
There are a couple of ways you could use:
Have Master be a singleton, so there is only one instance which you can access with Master.instance, so you'll have something like Master.instance.masterProperty.
Having a TerminalIO factory method in Master which constructs a TerminalIO and passes a Master reference to the constructor.

Related

LabVIEW: How to share a .NET object created from LabVIEW

I have a class called Camera in the .NET library and once I instantiate the object I want to create a reference of it so that this instance can be used from other VIs. How do I make a reference or how do I make it global ?
Thanks,
There are a couple ways to approach your question.
Possible answer 1: You're looking to let multiple parallel subVIs use the object at the same time. The .NET wire is already a reference wire. Forking that wire does not copy the object. Just wire it into the other VIs, however many there are, and let them all use the reference.
Possible answer 2: You're trying to obtain the existing reference in another VI without passing the reference on a wire through a subVI conpane or Call By Reference node. In this case, you would pass the .NET object refnum the same way you would pass any other bit of data in LabVIEW when avoiding wires. In general, the rule is "avoid passing data outside of dataflow." Seriously... try to pass the refnum through a conpane... if this program is going to have any significant lifetime, you'll be happier when you can take that approach. BUT... when such outside-of-dataflow passing is necessary, there are many tools -- queues, notifiers, global VIs, data value references, functional globals. Which of those tools is the right one depends greatly on what you're actually trying to achieve. The simplest is to create a global VI, but that introduces a lot of polling checks as the second VI has to keep polling the global to see if the first VI has stored the value yet or not. A notifier refnum is probably the most flexible option that I can point you toward... create a named notifier of your .NET refnum type. Both first and second VI can obtain the notifier by name. The second VI then blocks on Wait For Notificiation waiting for the first VI to write the refnum into the notifier. See http://zone.ni.com/reference/en-XX/help/371361L-01/glang/create_notifier/ for more information on notifiers. Or Google the other terms that I listed if that seems insufficient for your needs.

UDK GameReplicationInfo relating to GetPC()

I'm writing some code that uses a class to interact with a matchmaking server using TcpLink. Since I need to access a single reference to an object of this class throughout the code, I've been saving a reference to the object in the PlayerController class and accessing it throughout the program using the function GetPC. My question is, is it safe to call this function in a subclass of GameReplicationInfo? If it isn't possible, then what are my alternatives for inter-class data transfer? The class instance needs to be accessible from a variety of different places, including instances of GFxMoviePlayer, PlayerController, and, most of all, GameReplicationInfo itself.
If the object only needs to be accessible from the local player, storing a reference and accessing only the reference in a local player controller should be fine and is a far better solution than config files. Be sure to always use the local player controller, and you shouldn't expect retaining your object after level/server switching or connecting. I've done a Tcplink matchmaking server myself to know that 1) Eventually you should plan on combining tcplink with your own class pulling from an online subsystem and 2) the player controller approach will work in the mean time.
Sigh, no answers. I think I'm just going to go with saving values in a config file, because speed isn't really of the essence.

How to share/reuse a Lua script for multiple entities?

I'm in the design/skeleton coding phase of my C++ game with Lua scripting, but I have run into a design issue:
The game will have many copies of the same kind of entities, with behavior controlled by the same script. Is there a straightforward way I can share the script between entities of the same type in a single lua_state? I have only been able to find this question asked a couple of times on the Internet; I have read mixed feedback on whether or not it's a good idea to load the same script in different lua_state's, and not in-depth feedback on alternatives.
It's simple and bullet-proof, but I think loading, compiling, and storing addition copies of the same byte code with each instance of the same entity type created is a tragic waste, so I would like to figure out a smarter solution.
These are the two solutions I have thought of. I'm not new to programming or C or OO concepts but I am still learning when it comes to Lua and especially the Lua/C API. I think my ideas are sound but I am not even sure how I would go about implementing them.:
Implement OO in the Lua script and have each entity be represented by a Lua object; all the Lua logic would act on the object. This would also have the benefit (or the "benefit") of allowing the global environment to be changed by anything single entity.
Encapsulate each entity in its own environment using setfenv and copy references of all of the functions from the global space. As I understand it the env is just a different table than the default global, but I've looked into setfenv but I don't know how I would do that.
1 and 2 are just different sides of the same coin, more or less. It's simply a matter of where the object goes. In type 1, the object is an explicit part of the Lua script. Which means the script decides how it wants to set up its objects.
In type 2, the object is the environment. It is still a Lua table, but one created for it by the external code. The script cannot break free of the confines of this object, except in the ways that the external code allows.
The easiest way for me to implement type 1 would be with Luabind. I'd have an AI object as a C++ class, which Lua would be able to derive from. Running the "main script" for that AI would create an instance of that class. You would pass the script parameters, like the name of the entity it controls, maybe a reference it can use to control it, etc.
Type 2 is fairly simple. First, you create the new environment by creating an empty table and populating it with the global variables that you want the user to be able to have access to. These would be for things like talking to game-state (find other objects in the scene, etc), ways to move the entity in question around, and so forth. There are metatable tricks you can play to effectively make these values immutable and constant, so the user can't modify them later.
Then, you load the script with lua_loadstring or lua_loadfile. This puts a function on the Lua stack that represents that Lua script. Then you apply this table as that script function's environment with lua_setfenv. You can then run that script, passing whatever variables you wish (the name of the entity, etc).

When to use an object instance variable versus passing an argument to the method

How do you decide between passing arguments to a method versus simply declaring them as object instance variables that are visible to all of the object's methods?
I prefer keeping instance variables in a list at the end of the Class, but this list gets longer as my program grows. I figure if a variable is passed often enough it should just be visible to all methods that need it, but then I wonder, "if everything is public there will be no need for passing anything at all!"
Since you're referring to instance variables, I'm assuming that you're working in an object-oriented language. To some degree, when to use instance variables, how to define their scope, and when to use local variables is subjective, but there are a couple of rules of thumb you can follow whenever creating your classes.
Instance variables are typically considered to be attributes of a class. Think of these as adjectives of the object that will be created from your class. If your instance data can be used to help describe the object, then it's probably safe to bet it's a good choice for instance data.
Local variables are used within the scope of methods to help them complete their work. Usually, a method should have a purpose of getting some data, returning some data, and/or proccessing/running an algorithm on some data. Sometimes, it helps to think of local variables as ways of helping a method get from beginning to end.
Instance variable scope is not just for security, but for encapsulation, as well. Don't assume that the "goal should be to keep all variables private." In cases of inheritance, making variables as protected is usually a good alternative. Rather than marking all instance data public, you create getters/setters for those that need to be accessed to the outside world. Don't make them all available - only the ones you need. This will come throughout the development lifecycle - it's hard to guess from the get go.
When it comes to passing data around a class, it's difficult to say what you're doing is good practice without seeing some code . Sometimes, operating directly on the instance data is fine; other times, it's not. In my opinion, this is something that comes with experience - you'll develop some intuition as your object-oriented thinking skills improve.
Mainly this depends on the lifetime of the data you store in the variable. If the data is only used during a computation, pass it as a parameter.
If the data is bound to the lifetime of the object use an instance variable.
When your list of variables gets too long, maybe it's a good point to think about refactoring some parts of the class into a new class.
In my opinion, instance variables are only necessary when the data will be used across calls.
Here's an example:
myCircle = myDrawing.drawCircle(center, radius);
Now lets imaging the myDrawing class uses 15 helper functions to create the myCircle object and each of those functions will need the center and the radius. They should still not be set as instance variables of the myDrawing class. Because they will never be needed again.
On the other hand, the myCircle class will need to store both the center and radius as instance variables.
myCircle.move(newCenter);
myCircle.resize(newRadius);
In order for the myCircle object to know what it's radius and center are when these new calls are made, they need to be stored as instance variables, not just passed to the functions that need them.
So basically, instance variables are a way to save the "state" of an object. If a variable is not necessary to know the state of an object, then it shouldn't be an instance variable.
And as for making everything public. It might make your life easier in the moment. But it will come back to haunt you. Pease don't.
IMHO:
If the variable forms part of the state of the instance, then it should be an instance variable - classinstance HAS-A instancevariable.
If I found myself passing something repeatedly into an instance's methods, or I found that I had a large number of instance variables I'd probably try and look at my design in case I'd missed something or made a bad abstraction somewhere.
Hope it helps
Of course it is easy to keep one big list of public variables in the class. But even intuitively, you can tell that this is not the way to go.
Define each variable right before you are going to use it. If a variable supports the function of a specific method, use it only in the scope of the method.
Also think about security, a public class variable is susceptible to unwanted changes from "outside" code. Your main goal should be to keep all variables private, and any variable which is not, should have a very good reason to be so.
About passing parameters all they way up the stack, this can get ugly very fast. A rule of thumb is to keep your method signatures clean and elegant. If you see many methods using the same data, decide either if it's important enough to be a class member, and if it's not, refactor your code to have it make more sense.
It boils down to common sense. Think exactly where and why you are declaring each new variable, what it's function should be, and from there make a decision regarding which scope it should live in.

Dealing with "global" data structures in an object-oriented world

This is a question with many answers - I am interested in knowing what others consider to be "best practice".
Consider the following situation: you have an object-oriented program that contains one or more data structures that are needed by many different classes. How do you make these data structures accessible?
You can explicitly pass references around, for example, in the constructors. This is the "proper" solution, but it means duplicating parameters and instance variables all over the program. This makes changes or additions to the global data difficult.
You can put all of the data structures inside of a single object, and pass around references to this object. This can either be an object created just for this purpose, or it could be the "main" object of your program. This simplifies the problems of (1), but the data structures may or may not have anything to do with one another, and collecting them together in a single object is pretty arbitrary.
You can make the data structures "static". This lets you reference them directly from other classes, without having to pass around references. This entirely avoids the disadvantages of (1), but is clearly not OO. This also means that there can only ever be a single instance of the program.
When there are a lot of data structures, all required by a lot of classes, I tend to use (2). This is a compromise between OO-purity and practicality. What do other folks do? (For what it's worth, I mostly come from the Java world, but this discussion is applicable to any OO language.)
Global data isn't as bad as many OO purists claim!
After all, when implementing OO classes you've usually using an API to your OS. What the heck is this if it isn't a huge pile of global data and services!
If you use some global stuff in your program, you're merely extending this huge environment your class implementation can already see of the OS with a bit of data that is domain specific to your app.
Passing pointers/references everywhere is often taught in OO courses and books, academically it sounds nice. Pragmatically, it is often the thing to do, but it is misguided to follow this rule blindly and absolutely. For a decent sized program, you can end up with a pile of references being passed all over the place and it can result in completely unnecessary drudgery work.
Globally accessible services/data providers (abstracted away behind a nice interface obviously) are pretty much a must in a decent sized app.
I must really really discourage you from using option 3 - making the data static. I've worked on several projects where the early developers made some core data static, only to later realise they did need to run two copies of the program - and incurred a huge amount of work making the data non-static and carefully putting in references into everything.
So in my experience, if you do 3), you will eventually end up doing 1) at twice the cost.
Go for 1, and be fine-grained about what data structures you reference from each object. Don't use "context objects", just pass in precisely the data needed. Yes, it makes the code more complicated, but on the plus side, it makes it clearer - the fact that a FwurzleDigestionListener is holding a reference to both a Fwurzle and a DigestionTract immediately gives the reader an idea about its purpose.
And by definition, if the data format changes, so will the classes that operate on it, so you have to change them anyway.
You might want to think about altering the requirement that lots of objects need to know about the same data structures. One reason there does not seem to be a clean OO way of sharing data is that sharing data is not very object-oriented.
You will need to look at the specifics of your application but the general idea is to have one object responsible for the shared data which provides services to the other objects based on the data encapsulated in it. However these services should not involve giving other objects the data structures - merely giving other objects the pieces of information they need to meet their responsibilites and performing mutations on the data structures internally.
I tend to use 3) and be very careful about the synchronisation and locking across threads. I agree it is less OO, but then you confess to having global data, which is very un-OO in the first place.
Don't get too hung up on whether you are sticking purely to one programming methodology or another, find a solution which fits your problem. I think there are perfectly valid contexts for singletons (Logging for instance).
I use a combination of having one global object and passing interfaces in via constructors.
From the one main global object (usually named after what your program is called or does) you can start up other globals (maybe that have their own threads). This lets you control the setting up of program objects in the main objects constructor and tearing them down again in the right order when the application stops in this main objects destructor. Using static classes directly makes it tricky to initialize/uninitialize any resources these classes use in a controlled manner. This main global object also has properties for getting at the interfaces of different sub-systems of your application that various objects may want to get hold of to do their work.
I also pass references to relevant data-structures into constructors of some objects where I feel it is useful to isolate those objects from the rest of the world within the program when they only need to be concerned with a small part of it.
Whether an object grabs the global object and navigates its properties to get the interfaces it wants or gets passed the interfaces it uses via its constructor is a matter of taste and intuition. Any object you're implementing that you think might be reused in some other project should definately be passed data structures it should use via its constructor. Objects that grab the global object should be more to do with the infrastructure of your application.
Objects that receive interfaces they use via the constructor are probably easier to unit-test because you can feed them a mock interface, and tickle their methods to make sure they return the right arguments or interact with mock interfaces correctly. To test objects that access the main global object, you have to mock up the main global object so that when they request interfaces (I often call these services) from it they get appropriate mock objects and can be tested against them.
I prefer using the singleton pattern as described in the GoF book for these situations. A singleton is not the same as either of the three options described in the question. The constructor is private (or protected) so that it cannot be used just anywhere. You use a get() function (or whatever you prefer to call it) to obtain an instance. However, the architecture of the singleton class guarantees that each call to get() returns the same instance.
We should take care not to confuse Object Oriented Design with Object Oriented Implementation. Al too often, the term OO Design is used to judge an implementation, just as, imho, it is here.
Design
If in your design you see a lot of objects having a reference to exactly the same object, that means a lot of arrows. The designer should feel an itch here. He should verify whether this object is just commonly used, or if it is really a utility (e.g. a COM factory, a registry of some kind, ...).
From the project's requirements, he can see if it really needs to be a singleton (e.g. 'The Internet'), or if the object is shared because it's too general or too expensive or whatsoever.
Implementation
When you are asked to implement an OO Design in an OO language, you face a lot of decisions, like the one you mentioned: how should I implement all the arrows to the oft used object in the design?
That's the point where questions are addressed about 'static member', 'global variable' , 'god class' and 'a-lot-of-function-arguments'.
The Design phase should have clarified if the object needs to be a singleton or not. The implementation phase will decide on how this singleness will be represented in the program.
Option 3) while not purist OO, tends to be the most reasonable solution. But I would not make your class a singleton; and use some other object as a static 'dictionary' to manage those shared resources.
I don't like any of your proposed solutions:
You are passing around a bunch of "context" objects - the things that use them don't specify what fields or pieces of data they are really interested in
See here for a description of the God Object pattern. This is the worst of all worlds
Simply do not ever use Singleton objects for anything. You seem to have identified a few of the potential problems yourself