C++11 Creating an object of unknown class - class

I am developing a C++ application where I need to create X amount of classes. Let's say: class AAA, BBB and CCC. Each class corresponds to one type of object which I would need to process.
On the other hand, I have an input file of CVS type. One example of that input file looks like this one:
AAA,3432443,433434,11111,45678
AAA,8778776,786698,22222,86881
BBB,4452332,112234,34543,87734
So, I need to parse that input file, and according to the first element of the line (AAA, BBB, CCC), I need to create the corresponding object which will store the other values found in the line.
BUT, I cannot "embedded" in the application the possible classes (AAA, BBB, CCC) in order to use a chain of conditionals, like:
if (token == "AAA") then AAA aaa = new AAA (params);
Instead:
The application must remain independent of the existing classes, in such way that in the future we can add classes DDD, EEE, ... ZZZ, without modifying the module which creates the objects (in case of using conditionals, I should add, for instance: if (token == "DDD") then DDD ddd = new DDD(params). This is forbidden.
I have created a configuration file which provides the possible class types in the current execution:
AAA
BBB
CCC
...
In this way, I can loop over this class types and compare against the ones read from the first element in the input file lines. But I am stuck in the problem of how I can create an object of an unknown class. Something like this:
retrieved_type_from_input_file object = new retrieved_type_from_input_file(params);
where "retrieved_type_from_input_file" is a variable which contains the effective type of class I should create: AAA ... ZZZ
I am thinking in generic programming. Something like:
T object = new T(params);
But even though I can code this inside a class; in the implementation I need the real name of the class.
I am thinking also in the implementation of some kind of Factory pattern, creating some kind of abstract parent class ("Thing") from which everyone would be inheriting ( class AAA: public Thing). But all the models which I find, make explicit reference to the name of the class, in some place of the code, at the moment of creating the object.
Any help please?
Thanks a lot in advance!!

i am guessing, you are in need of code generator :
Step 1. Write a program that generates classes in .h, .cpp files based on your configuration file.
you can alse create/declare objects of the classes in this step
Step 2. Make use of generated classes , to build an exe file.
This is my rough idea, and looking for other possibilites from others.

Related

Scala type alias with companion object

I'm a relatively new Scala user and I wanted to get an opinion on the current design of my code.
I have a few classes that are all represented as fixed length Vector[Byte] (ultimately they are used in a learning algorithm that requires a byte string), say A, B and C.
I would like these classes to be referred to as A, B and C elsewhere in the package for readability sake and I don't need to add any extra class methods to Vector for these methods. Hence, I don't think the extend-my-library pattern is useful here.
However, I would like to include all the useful functional methods that come with Vector without having to 'drill' into a wrapper object each time. As efficiency is important here, I also didn't want the added weight of a wrapper.
Therefore I decided to define type aliases in the package object:
package object abc {
type A: Vector[Byte]
type B: Vector[Byte]
type C: Vector[Byte]
}
However, each has it's own fixed length and I would like to include factory methods for their creation. It seems like this is what companion objects are for. This is how my final design looks:
package object abc {
type A: Vector[Byte]
object A {
val LENGTH: Int = ...
def apply(...): A = {
Vector.tabulate...
}
}
...
}
Everything compiles and it allows me to do stuff like this:
val a: A = A(...)
a map {...} mkString(...)
I can't find anything specifically warning against writing companion objects for type aliases, but it seems it goes against how type aliases should be used. It also means that all three of these classes are defined in the same file, when ideally they should be separated.
Are there any hidden problems with this approach?
Is there a better design for this problem?
Thanks.
I guess it is totally ok, because you are not really implementing a companion object.
If you were, you would have access to private fields of immutable.Vector from inside object A (like e.g. private var dirty), which you do not have.
Thus, although it somewhat feels like A is a companion object, it really isn't.
If it were possible to create a companion object for any type by using type alias would make member visibility constraints moot (except maybe for private|protected[this]).
Furthermore, naming the object like the type alias clarifies context and purpose of the object, which is a plus in my book.
Having them all in one file is something that is pretty common in scala as I know it (e.g. when using the type class pattern).
Thus:
No pitfalls, I know of.
And, imho, no need for a different approach.

How can getter/setter code be generated automatically for a class in Pharo or Squeak?

I have a long list of instance variables to create for a class that I want to generate the code for, rather than do it by hand. The list comes from an existing SQL database. My intention is to do it all in a pure object-oriented way with Smalltalk first, and as I learn more, save the data back to the database and work from it directly.
Is there a way of passing the list of names to method that will generate them and add them to the class definition?
In fact is there a way of adding or modifying class definitions dynamically in Smalltalk? I suspect there must and I would like to know a best practices approach.
Update: What I have in mind is more like passing a list of the instance variables to a method that will create them automatically.
It is more like:
addVariablesAndAccessors className: MyClass variablesList: ('aaaa', 'bbbb', 'cccc')
which will then result in a call to
AddVariables className: MyClass variableList: ('aaaa' 'bbbb' cccc')
and
generateAccessors className: MyClass variableList: ('aaaa' 'bbbb' cccc')
In OmniBrowser with the refactoring tools loaded you select the class and in the context menu Refactor class > Accessors.
Alternatively, if you only want to create an accessor for a single variable, select Refactor instance/class variable > Accessor, and select the variable you want to access.
In Squeak, you have Behavior>>addInstVarName: aString, so for instance, you could do something like:
String addInstVarName: 'foo'
Squeak also has refactoring support to generate accessors automatically. You can either use it directly or have a look at AbstractInstanceVariableRefactoring>>createAccessors to get some inspiration on how to implement your own ;-)
Another quite hacky but not so uncommon solution would be to just generate the instance variables, but instead of adding accessors, you overwrite doesNotUnderstand:, which gets called when an undefined selector is sent to your objects. There, you could check if you have an instance variable named according to the message, and return / change it if it is the case. Otherwise you just do super doesNotUnderstand: aMessage.
Regarding your comment: Classes are objects, too, so you don't have to do anything special to use them as parameters. On which class you add it is totally up to you and doesn't really matter. So a method to add instance variables could look like this:
addVariablesNamed: aCollection on: aClass
aCollection do: [:each | aClass addInstVarName: each]
and you could call it like this:
yourObject addVariablesNamed: #('foo' 'bar' 'baz') on: ClassX
You can find examples on how to generate accessor methods in the class CreateAccessorsForVariableRefactoring
In Squeak, open a Browser on the class. If you "right click" (I can never remember the button colours) the class name in the class list you'll get the standard context menu - "browse full (b)", and so on. Select "more..." and you'll see "create inst var accessors". Select that, and you'll get basic getters and setters for the instance variables.

Using mixins in Coffeescript

I want to split up a large class by using mixins.
I am using this mixin code from the Little Book
#include: (obj) ->
for key, value of obj when key not in moduleKeywords
# Assign properties to the prototype
#::[key] = value
obj.included?.apply(#)
this
class FooMixin
b: => #something = 2
class Foo extends Module
#include FooMixin
a: => #something = 1
Problem is that # in FooMixin is FooMixin. I want it to be Foo instead.
I have tried adding the line _.bind(#::[key], #) at the end of #include() but it doesn't help. Any suggestions?
Okay, few things I was doing wrong.
1.
#include from the Little Book takes an object not a class. To get it to work with classes you need to write #include FooMixin::. However, I have since begun using objects instead.
2.
When using an object instead of a class, the fat arrow adds a line inside the CoffeeScript wrapper right at the top which reads _this = this. All methods are bound to the global context which is not what we want. To fix we must convert fat arrows to thin arrows, and bind each function to our Foo instance. Using Underscore I added this to the constructor of Foo:
constructor: ->
for fname in _.functions FooMixin
#[fname] = _.bind #[fname], #
super
I tried _.bindAll #, _.functions FooMixin but it gave me an error saying something like At Function.bind, could not run bind of undefined. Weird error, seeing as the code above is pretty much identical to the _.bindAll method.
So now I can split my classes up for better readability and code sharing.
UPDATE: The problem with _.bindAll is that it takes a splat not an array. Fix is to use _.bindAll #, _.functions(FooMixin)....
UPDATE: Found a better solution.
Same as original post. Use classes for mixins.
Use #include FooMixin:: or change #include to operate on a prototype instead of properties.
In the Foo constructor write FooMixin.call # which binds the methods correctly.
This works well and is nice and clean.
The only potential issue is that mixins will be overridden by existing properties. The only way to get around this that I can see is to do something like:
after = ->
_.extend Foo, FooMixin::
class Foo
# define...
after()
Or pass the extend method to _.defer but this is so hacky and probably won't work.

System.Reflection

I developed an application named as AAA in that application im referring an assembly named as BBB. At certain condition im loading that BBB assemby into my application using Assembly.LoadFromFile() function. Now i need to access certain object instances of AAA in BBB assembly at run time.Is it possible to accomplish this task?
Thanks in Advance .
Are you trying to create new instances of your objects? If so, this should work:
Assembly ass = Assembly.LoadFrom("BBB.dll");
Object myObject = ass.CreateInstance("BBB.MyObject");
Note this assumes that your object has a default constructor - if you need to pass parameters into the constructor, you can do something like this (assuming a constructor which takes a string as its argument):
Assembly ass = Assembly.LoadFrom("BBB.dll");
Type t= ass.GetType("MyObject");
ConstructorInfo c = t.GetConstructor(new Type[]{typeof(string)});
Object myObject2 = c.Invoke(new object[] { "myParam" }
Let AAA hand a reference to the object to some variable in BBB after it has loaded.
To access object ooo from BBB, you should provide BBB with a (possibly indirect) reference to ooo. AAA may use reflection to discover the appropriate entry point for BBB and then provide it with ooo.

How do you set the class of an object to something else?

I've seen this recently and now I can't find it …
How do you set the class of an object to something else?
--Update: Well, in Pharo! Like:
d:=Object new. d setClass: Dictionary.
Only that it isn't actually setClass. How can you modify the class pointer of an object?
There is #primitiveChangeClassTo:.
It requires that both original and target class have the same class layout. For some strange reason it expects an instance of the target class as parameter, which is however not used.
So you would do
d := Object new.
d primitiveChangeClassTo: Dictionary new.
however this fails, since dictionaries have two instance variables but plain objects have none.
If you are into meta-programming, you might also be interesting in using any object as a class. I used that in Protalk to realize a prototype based language that works directly on top of Smalltalk.
The method #setClass: is used in some specific contexts and with different implementations (Check it with the Method Finder).
Object has some helpers to conver the current object in other sort of, as for example #asOrderedCollection, because this last permit the operation:
asOrderedCollection
"Answer an OrderedCollection with the receiver as its only element."
^ OrderedCollection with: self
HTH.
ok, then you can try something as:
d := Object new.
e := Dictionary new.
d become: e.
But, please, try #become: with caution, because in lot of situations it break the image.
Take a look at Class ClassBuilder. It creates the a new class, when you modify a class, and then switches the instances of the former to instances of the later. Therefor it should provide some method that does, what you ask for.