Visitor Pattern: Traversing tree elements in client or visitor - visitor-pattern

Good morning stackoverflow,
I'm currently implemeting a visitor pattern on something like an AST.
Now my question is, how do I iterate through the elements ?
I think its somewhat more logical to just return the object to the visitor and let the visitor traverse from there on. Because you're keeping up flexibility , when you would like to traverse the object in different ways.
On the other side one could say, the visitor shouldn't concern about the structure of the object. So in case the object changes, you don't have to change the visitor too.
Are there any general recommadations how to solve this? I've got two books about Visitor Patterns but both are not dealing with the question how to deal with more complex nodes.
Regads
toebs

It seems pretty straightforward for a tree structure. The accept method in a node could look like this:
void accept(Visitor visitor) {
visitor.visitMyTypeOfNode(this);
for each child {
child.accept(visitor);
}
}
Obviously you need to consider if this makes sense in the overall architecture of your application.

Related

Ruby: Hash, Arrays and Objects for storage information

I am learning Ruby, reading few books, tutorials, foruns and so one... so, I am brand new to this.
I am trying to develop a stock system so I can learn doing.
My questions are the following:
I created the following to store transactions: (just few parts of the code)
transactions.push type: "BUY", date: Date.strptime(date.to_s, '%d/%m/%Y'), quantity: quantity, price: price.to_money(:BRL), fees: fees.to_money(:BRL)
And one colleague here suggested to create a Transaction class to store this.
So, for the next storage information that I had, I did:
#dividends_from_stock << DividendsFromStock.new(row["Approved"], row["Value"], row["Type"], row["Last Day With"], row["Payment Day"])
Now, FIRST question: which way is better? Hash in Array or Object in Array? And why?
This #dividends_from_stock is returned by the method 'dividends'.
I want to find all the dividends that were paid above a specific date:
puts ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('12/05/2014')}
I get the following:
#<DividendsFromStock:0x2785e60>
#<DividendsFromStock:0x2785410>
#<DividendsFromStock:0x2784a68>
#<DividendsFromStock:0x27840c0>
#<DividendsFromStock:0x1ec91f8>
#<DividendsFromStock:0x2797ce0>
#<DividendsFromStock:0x2797338>
#<DividendsFromStock:0x2796990>
Ok with this I am able to spot (I think) all the objects that has date higher than the 12/05/2014. But (SECOND question) how can I get the information regarding the 'value' (or other information) stored inside the objects?
Generally it is always better to define classes. Classes have names. They will help you understand what is going on when your program gets big. You can always see the class of each variable like this: var.class. If you use hashes everywhere, you will be confused because these calls will always return Hash. But if you define classes for things, you will see your class names.
Define methods in your classes that return the information you need. If you define a method called to_s, Ruby will call it behind the scenes on the object when you print it or use it in an interpolation (puts "Some #{var} here").
You probably want a first-class model of some kind to represent the concept of a trade/transaction and a list of transactions that serves as a ledger.
I'd advise steering closer to a database for this instead of manipulating toy objects in memory. Sequel can be a pretty simple ORM if used minimally, but ActiveRecord is often a lot more beginner friendly and has fewer sharp edges.
Using naked hashes or arrays is good for prototyping and seeing if something works in principle. Beyond that it's important to give things proper classes so you can relate them properly and start to refine how these things fit together.
I'd even start with TransactionHistory being a class derived from Array where you get all that functionality for free, then can go and add on custom things as necessary.
For example, you have a pretty gnarly interface to DividendsFromStock which could be cleaned up by having that format of row be accepted to the initialize function as-is.
Don't forget to write a to_s or inspect method for any custom classes you want to be able to print or have a look at. These are usually super simple to write and come in very handy when debugging.
thank you!
I will answer my question, based on the information provided by tadman and Ilya Vassilevsky (and also B. Seven).
1- It is better to create a class, and the objects. It will help me organize my code, and debug. Localize who is who and doing what. Also seems better to use with DB.
2- I am a little bit shamed with my question after figure out the solution. It is far simpler than I was thinking. Just needed two steps:
willpay = ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('10/09/2015')}
willpay.each do |dividend|
puts "#{ciel3.code} has approved #{dividend.type} on #{dividend.approved} and will pay by #{dividend.payment_day} the value of #{dividend.value.format} per share, for those that had the asset on #{dividend.last_day_with}"
puts
end

Is it bad programming practice to store objects of type Foo into a static array of type Foo belonging to Foo in their construction?

Say I wanted to store objects statically inside their own class. Like this:
public class Foo
{
private static int instance_id = 0;
public static List<Foo> instances = new List<Foo>();
public Foo()
{
instances[instance_id++] = this;
}
}
Why?
I don't need to create unique array structures outside the class (one will do).
I want to map each object to a unique id according to their time of birth.
I will only have one thread with the class in use. Foo will only exist as one set in the program.
I did searching, but could find no mention of this data structure. Is this bad practice? If so, why? Thank you.
{please note, this question is not specific to any language}
There are a couple of potential problems I can see with this setup.
First, since you only have a single array of objects, if you need to update the code so that you have lots of different groups of objects in different contexts, you'll need to do a significant rewrite so that each object ends up getting associated with a different context. Depending on your setup this may not be a problem, but I suspect that in the long term this decision may come back to haunt you.
Second, this approach assumes that you never need to dispose of any objects. Imagine that you want to update your code so that you do a number of different simulations and aggregate the results. If you do this, then you'll end up having your giant array storing pointers to objects you're not using. This means that you'll (1) have a memory leak and (2) have to update all your looping code to skip over objects you no longer care about.
Third, this approach makes it the responsibility of the class, rather than the client, to keep track of all the instances. In some sense, if the purpose of what you're doing is to make it easier for clients to have access to a global list of all the objects that exist, you may want to consider just putting a different list somewhere else that's globally accessible so that the objects themselves aren't the ones responsible for keeping track of themselves.
I would recommend using one of a number of alternate approaches:
Just have the client do this. If the client needs to keep track of all the instances, just have them always create the array they need and populate it. That way, if multiple clients need different arrays, they can do so. You also avoid the memory leak issues if you do this properly.
Have each object take, as part of its constructor, a context in which to be constructed. For example, if all of these objects are nodes in a quadtree, have them take a pointer to the quadtree in which they'll live as a constructor parameter, then have the quadtree object store the list of the nodes in it. After all, it seems like it's really the quadtree's responsibility to keep track of everything.
Keep doing what you're doing, but using something with weak references. For example, you might consider using some variation on a WeakHashMap so that you do store everything, but if the objects are no longer needed, you at least don't have a memory leak.

How to randomly access a point in a CvSeq?

Can we randomly access a point in a CvSeq object? We can traverse it, so I imagine it's possible in a simple manner. How is this accomplished?
I have found it. There is a method called cvGetSeqElem, which takes in the sequence and the index. Thanks for the help though. This might just follow the linked list linearly, but it's simpler than manually coding the search.
Looking at the OpenCV API (http://opencv.willowgarage.com/documentation/dynamic_structures.html) it doesn't sound possible. Looks to be some form of linked list implementation, which means that the only way to access an element part way though is to follow the links.
cvSeq is a linked list - you have to follow the chain of links, you have no idea where the next entry is stored in memory.

is it wasteful/bad design to use a vector/list where in most instances it will only have one element?

is it wasteful/bad design to use a vector/list where in most instances it will only have one element?
example:
class dragon
{
ArrayList<head> = new ArrayList<head> Heads;
tail Tail = new tail();
body Body = new body();
dragon()
{
theHead=new head();
Heads.add(theHead);
}
void nod()
{
for (int i=0;i<Heads.size();i++)
{
heads.get(i).GoUpAndDown();
}
}
}
class firedragon extends dragon
{
}
class icedragon extends dragon
{
}
class lightningdragon extends dragon
{
}
// 10 other one-headed dragon declarations here
class hydra extends dragon
{
hydra()
{
anotherHead=new head();
for (int i=0;i<2;i++)
{
Heads.add(anotherHead);
}
}
}
class superhydra extends dragon
{
superhydra()
{
anotherHead=new head();
for (int i=0;i<4;i++)
{
Heads.add(anotherHead);
}
}
}
EDIT:(part 2 of the question)
Thanks for the replies. They have been very helpful.
I've actually run into this situation more than once, and I'd like to give a second example that is unrelated to inheritance. This is actually a real-world example, and though I've decided my current project is small scale enough to be safe with using vectors based on your answers, it's a concept that I imagine I'll use on a much larger scale at some point.
In creating an engine for my current Android game project, I found it necessary to create an Imagepoint object that is basically a set of XY coordinates that are used to track significant parts of a sprite image. Say you have a bone character made up of several bitmaps, it's useful to know where the neck attaches to the torso, the forearm to the bicep, etc. This xy offset data is used later to calculate the position for various purposes, such as where to position other sprites by using trigonometric functions to find the xy offset given the current angle.
Most sprite objects will need only one image point. The bicep needs one for the forearm, the forearm needs one for the hand, the neck needs one for the head, etc. The torsos in my current character models are the exception, and they need several for the shoulders, the legs, the neck, and any removable decorative sprites.
The sprite is the object that contains the imagepoint vectors, there will be no inherited classes, because each : torso, leg, etc is simply an instance of the sprite class, which is strictly a graphical object, containing a pointer to the bitmap, these imagepoints, and assorted position/orientation data, and will not be used for any specialized purposes. If I were to use this concept on a large scale game with massive numbers of instances, where most would require only a single imagepoint, with a few objects requiring several or none, and where there would be no special cases meriting the use of inheritance. What would your thoughts be?
Yes and no.
I mean your question really depends on how are you going to use these objects.. personally I like to split behaviours and attributes as much as possible to "clusterize" them according to the kind of object they represent without caring about reusing some code a little bit less compared to a really inheritance approach like the one you proposed. Something like:
interface BigLizard
{
void nod();
}
class Dragon implements BigLizard
{
Head head;
void nod() { head.upAndDown(); }
}
class ReallyScaryDragon extends Dragon { ... }
class Hydra implements BigLizard
{
ArrayList<Head> heads;
void nod() { for (Head h : heads) h.upAndDown(); }
}
And so on. This approach is like "having just exactly what you need for your objects without force anything to be a specific case". Of course this means that it will have two different implementations of nod() but when you don't need to optimize (and you should care about it only at the end) just stick with your personal preference, assuming that it doesn't go against any standard, widely accepted convention.
You don't have to make anything inherit from a single object, just customize the hierarchy as you like.. also a composite solution (like already suggested) would be a solution also if the concept of "head part" is not the same for your Dragon and for your Hydra..
A third solution for your specific case could be to use a LinkedList instead that an ArrayList. In this case whenever you have just one head you won't waste space (except for instantiation of the list) and you'll have just the next pointer of the head (of the list :D ) pointing nowhere.
If the head is publicly accessible, it'll need to be available as an array/list/collection so that consumers can deal with it.
Another way of dealing with this may be to switch to a more behavioral design rather than a stateful design. In other words, instead of having code telling the dragon to nod, have the dragon respond to an event that would cause him to nod, if that makes sense.
say("Dragon, would you like a yummy princess?");
if(dragon.Stomach.Contents.IsEmpty)
{
dragon.Nod();
}
compared with:
say("Dragon, would you like a yummy princess?");
dragon.offerFood(princess);
// in dragon class
void offerFood(Food yummyFood)
{
if(Stomach.Contents.Empty)
{
head.Nod(); // can be overridden by subclasses.
}
}
In the second example, the consumer of the dragon class isn't asserting authority to make the dragon do things... all the consumer is doing is things (saying things, offering a princess) that he has the authority to do - the dragon gets to decide whether it wants to nod its head or not (which makes sense. I doubt that I'd be able to get a dragon to nod its head if it didn't want to!)
I call this 'behavioral' because the interfaces focus on the interactions between the objects (the dragon and whatever is offering the yummy princess) rather than the state of the dragon (its heads).
I don't think there is a single answer to this question. It seems to me like it would be application dependent. If the application is a relatively lightweight dragon simulation that will never deal with more than a few thousand dragons at any one time, then it probably isn't a big deal to use a vector. If, though, it is a game involving millions of dragons, then it might make sense to optimize it slightly differently and maybe save a bit of memory and possibly shorten access time. But even that probably depends on the underlying class implementation. It is quite possible that the vector class you use could be optimized to handle a single element without extra overhead.
In this particular case, it'd probably be better to override nod() for your multi-headed dragons. Whether they have 1 head or 5 is a detail that really shouldn't be worried about in the base class (which should be as simple as you can reasonably make it).
You don't want to have to account for every possibility that every one of your code's users (even you) will ever need at every point in time. Otherwise, you'd need to account for 2-headed dogs (which are a lot more real than even 1-headed dragons). People extending your classes and such will be developers, too; let them do the work to account for the more exotic/bizarre cases, if they need to.
You could change the Head implementation to be a Composite type. That way, each extension of Dragon needs only one instance of Head and the Head takes care of GoUpAndDown().
I would implement such features in deriving classes. To make this behaviour work, you have to be able to override methods (in your case, the nod() method). The baseclass shouldn't cater for all possibilities, it should present the base case, which can be extended. Just make the appropiate methods overrideable, so the deriving classes can implement the specific behaviour, and everything will work out fine.

OOP Best Practices When One Object Needs to Modify Another

(this is a C-like environment) Say I have two instance objects, a car and a bodyShop. The car has a color iVar and corresponding accesors. The bodyShop has a method named "paintCar" that will take in a car object and change its color.
As far as implementation, in order to get the bodyShop to actually be able to change a car object's color, I see two ways to go about it.
Use the "&" operator to pass in a pointer to the car. Then the bodyShop can either tell the car to perform some method that it has to change color, or it can use the car's accessors directly.
Pass in the car object by value, do the same sort of thing to get the color changed, then have the method return a car object with a new color. Then assign the original car object to the new car object.
Option 1 seems more straightforward to me, but I'm wondering if it is in-line with OOP best practices. In general for "maximum OOP", is the "&" operator good or bad? Or, maybe I'm completely missing a better option that would make this super OOPer. Please advise :)
Option 1 is prefered:
The bodyShop can either tell the car
to perform some method that it has to
change color, or it can use the car's
accessors directly.
Even better still...create an IPaintable interface. Have Car implement IPaintable. Have BodyShop depend on IPaintable instead of Car. The benefits of this are:
Now BodyShop can paint anything that implements IPaintable (Cars, Boats, Planes, Scooters)
BodyShop is no longer tightly coupled to Car.
BodyShop has a more testable design.
I would assume that the responsibility of the bodyShop is to modify car objects, so #1 seems like the right way to go to me. I've never used a language where the "&" operator is necessary. Normally, my bodyShop object would call car.setColor(newColor) and that would be that. This way you don't have to worry about the rest of the original car's attributes, including persistence issues - you just leave them alone.
Since you're interested in the best OOP practice, you should ignore the performance hit you get with option 2. The only things you should be interested in is do either option unnecessarily increase coupling between the two classes, is encapsulation violated and is identity preserved.
Given this, option 2 is less desirable since you can't determine which other objects are holding references to the original car or worse, contain the car. In short you violate the identity constraint since two objects in the system may have different ideas of the state of the car. You run the risk of making the overall system inconsistent.
Of-course your particular environment may avoid this but it certainly would be best practice to avoid it.
Last point, does your bodyShop object have state; behaviour and identity? I realise that you have explained only the minimum necessary but possibly the bodyShop isn't really an object.
Functional v OO approaches
As an interesting aside, option 2 would close to the approach in a functional programming environment - since state changes are not allowed, your only approach would be to create a new car if it's colour changed. That's not quite what you're suggesting but it's close.
That may sound like complete overkill but it does have some interesting implications for proving the correctness of the code and parallelism.
Option 1 wins for me. The & operator is implicit in many OO languages (like Java, Python etc). You don't use "passing by value" in that languages often - only primitive types are passed in that way.
Option 2 comes with multiple problems: You might have a collection of cars, and some function unaware of it might send a car to bodyShop for painting, receive new car in return and don't update your collection of cars. See? And from more ideologic point of view - you don't create new object each time you want to modify it in real world - why should you do so in virtual one? This will lead to confusion, because it's just counterintuitive. :-)
I am not sure what this "C-like environment" mean. In C, you need this:
int paintCar(const bodyShop_t *bs, car_t *car);
where you modify the contents pointed by car. For big struct in C, you should always pass the pointer, rather than the value to a function. So, use solution 1 (if by "&" you mean the C operator).
I too agree with the first 1. I can't say it's best practice because i'm never really sure what best practice is in other peoples minds... I can tell you that best practice in my mind is the most simple method that works for the job. I've also seen this aproach taken in the hunspell win api and other c-ish api's that i've had to use. So yea i agree with scott.
http://hunspell.sourceforge.net/
//just in-case your interested in looking at other peoples code
It depends on whether the body shop's method can fail and leave the car in an indeterminate state. In that case, you're better off operating on a copy of the car, or a copy of all relevant attributes of the car. Then, only when the operation succeeds, you copy those values to the car. So you end up assigning the new car to the old car within the body shop method. Doing this correctly is necessary for exception safety in C++, and can get nasty.
It's also possible and sometimes desirable to use the other pattern - returning a new object on modification. This is useful for interactive systems which require Undo/Redo, backtracking search, and for anything involving modelling how a system of objects evolves over time.
In addition to other optinions, option 1 lets paintCar method return a completion code that indicates if the car has changed the color successfully or there were problems with it

Resources