Bi-Directional References without Database - reference

I'm trying to implement a tree structure and I would like that every node has a pointer to both its children and parent. I.e. the reference between two nodes goes both ways.
Do languages exist (e.g. python) where such a relation can be modeled nicely? What I am doing right now is:
class Node {
setParent(Node p) {
this.parent.chilren.remove(this)
p.chilren.add(this)
this.parent = p
}
// ...
}
But I would prefer an approach where I can factor out this aspect of a bidirectional reference such that I can reuse the same construct in other places. (e.g. a more declarative approach would be nice).

Look at Haskell and functional languages to simplify recursive data structures. See the article here.

Related

Difference between child entity and value object in DDD

I've found this great article where in the section on aggregates' structure, I can see a distinction being made between child entity (here: order item) and value object (here: address).
I'm not entirely sure how they differ on an architectural level. I'd like to say that both of them are value objects (aggregated within the root Order).
What am I missing in the picture?
Value Objects are much "values with methods" than they are "objects".
"Address" as a value, isn't fundamentally different from a primitive like integer. The significant difference between the two is that most generic programming languages don't come with a built in address type. So we have to roll our own -- or re-use one from a library.
In many modern languages, you can only roll your own by using the "object" idioms to create your customized data structure and the query semantics that you want.
Value objects are data with query semantics attached.
Entities, on the other hand, change over time. A way of thinking of an entity's implementation is that, under the covers, the entity is a mutable reference to a value.
void Entity::onChange(data) {
// dereference to get the current state value
val oldState = this.state;
// use a pure function to compute a new state value
val newState = stateChange(oldState, data);
// update the reference
this.state = newState;
}
The specific data structure being used to hold the state is an implementation detail of the entity of no interest to other elements in the solution.
A child entity is an entity, which is to say that it is an object with the responsibility for managing some implicit data structure. It is designed for change.
It's "just like the root", but on a smaller scale -- the root has a more complete sense of the entire context.
See also
Classes vs Data Structures -- Robert Martin
Perception and Action -- Stuart Halloway

Interview prep - How does one access nodes in binary search trees in the real world?

I'm preparing for the data structures portion of an interview. I see that there are already questions about applications of binary trees in the real world - What are the applications of binary trees?
My question is different - How does one actually access nodes in data structures based on trees?
I understand BFS, DFS and such for explicit node traversal, I get a sense this is not how the real world works. Do people write their own traversal / search algorithms, or do they rely on iterators and similar access methods provided by the database?
What is the name of a high level abstraction of accessing structured tree data, if any? I'm thinking of iterators, but am not sure if this is the right term.
I am looking for a way to intelligently converse on the subject.
What is the name of a high level abstraction of accessing structured
tree data, if any?
Iterator is something more suitable for linear data-structure like linked list or dynamic array. As tree is a hierarchical data-structure, parent(), child(), children(), ancestor(), descendent() are more suitable. For instance, if you want to implement a file system, you will have RootDirectory and to get all the sub-directories you might call like getAllSubDirectories() which are actually children of root directory. So the naming is actually domain specific.
class Directory {
private Integer someAttribute;
....
....
private Directory parentDirectory;
List<Directory> subDirectories;
}
You can abstract as iterator and can call iterator.hasNext() or iterator.next() on a hierarchical data-structure as well. So for example, for a binary search tree, you can abstract away an iterator which can iterate the tree in preorder/inorder/postorder traversal in both direction. See in-order successor.

Examples of languages that hide variable multiplicity

What are some examples of programming languages, extensions to programming languages or other solutions that hides the multiplicity of variables when operating on them, calling method etc?
Specifically I imagine a system where I have a single typed collection of objects that transparently will forward any method call on the collection of objects so that the method is applied to all of them individually including using the return value in a meaningful way. Preferably I would like to see examples of languages that does this in a good way, but it could be interesting to see also solutions where this does not work well.
I imagine something like this:
struct Foo
{
int bar();
}
void myFunction()
{
// 4 Foo objects are created in a vector
vector<Foo> vals(4);
// The bar() method is applied to each of the Foo objects and each
// return an int that is automatically inserted into a new vector
vector<int> = vals.bar();
}
Take a look at Java 8 streams. Basically, you'd "stream" the container's contents, and indicate to the stream that each thing that goes through should have the method Foo::bar applied to it.
vals.stream().forEach(Foo::bar);
A lot of these concepts come from earlier languages, including Lisp (list processing).

What haskell data structure to store mutable tree

I was thinking about writing a browser in haskell. A central data structure will be a mutable tree representing the document. Apart from using a tree composing entirely of iorefs, is there a better solution?
I am hoping to avoid something like this: data DomNode = DomNode TagName NodeProperties (IORef DomNode) [IORef DomNode] (tag, properties, parent, children)
The problem is that javascript can hold onto references of nodes in the tree, and it can mutate (add children, modify properties) any node it has a reference to, as well as traverse to it's parent.
Edit:
I realized you would need to use mutable state somehow - because you can hold onto a reference to a node that is deleted from the tree, or moved in the tree. If you referred to the element via something based on the structure of the tree, this reference will be invalid.
It is natural for javascript to operate with mutable references, so you'll have to introduce them sooner or later (not necessarily IORefs, maybe some kind of lookup table living in state monad).
If most of operations on DOM will be performed from javascript, then it is better to select data structure natural for it.
Don't try to use pure data structure only for purity itself. Otherwise you'll finish with hand-made emulation of RAM :) Your task looks imperative for me, so why not to use all the imperative features haskell provides?
I don't think zippers, as Niklas B. suggested, can help you a lot. Usually they have only one "cursor", where you can mutate. (AFAIK in theory any number of cursors are possible, but in practice it is mostly unusable)
The usual Haskell approach is to use an immutable tree, and have operations such as addChild and so forth return a new, modified tree, rather than touching the existing tree.
Without knowing what you're actually trying to do with this tree, I would suggest that this is probably the simplest and easiest approach.

In terms of OO design, can two-d and the three-d point classes be derived from single base class?

I`m currently working out the design for simple graphic editor, who support trivial operations for two-dimensional and three-d shapes.
The point is, I want to render prototype of these shapes, as MsPaint does. And at the moment it is rendering I need to store somewhere pixels from the canvas which get covered by prototype, just in case when prototype changes to restore their state on the canvas. So, I want all my shapes to support this kind of buffering (Graphic Operation is the base class for all rendering operations):
public abstract class Shape: GraphicOperation {
protected List<SomePoint> backup;
public Shape(Color c): base(c) { }
public Color FigureColor {
get { return color; }
protected set { color = value; }
}
public abstract void renderPrototype(Bitmap canvasToDrawOn);
}
The main idea is that in terms of OO design it would be great to provide the support of the buffer on base class (Shape) level, I mean for TwoDShape and ThreeDShape classes this list must be initialized in different way - for TwoDShape with TwoDPoint instances, and for ThreeDShape with ThreeDPoint instances.
But to do this, SomePoint must be base class for both two-dimensional point and three-dimensional point classes. Is it acceptable in terms of OO to derive both these classes from single base class?
May be there are too many words, but I just wanted the problem to be clear for everyone.
Edit: btw, is this the good idea to derive point classes from their king of shapes? I personally see no other options, but may be it would be better if I derive it directly from shape? Now it is:
public abstract class TwoDShape : Shape {
protected List<SomePoint> backup;
public TwoDShape(Color c) : base(c) { }
}
public class TwoDPoint: TwoDShape {
//...
}
and the same is for ThreeDPoint.
I don't see any reason not to. But if the only difference between Shapes is in the type of Points they contain, why not make the Shape class itself a template, or a "generic" in Java parlance?
What do 2d and 3d points have in common, exactly? If it is just "when drawing them onto a surface, they replace pixels which should be backed up", that sounds more like composition than inheritance to me. Both 2d and 3d shapes have a buffer of pixels they're displacing.
Anyway, can you always use both 2d and 3d shapes when the base class is expected?
If so, give them a common base class. Otherwise don't.
Base your class design on how the objects are used. If they are used in a context where they have a common base, implement it as a common base class. If it is just a matter of "I can't be bothered adding a data member to both", inheritance is probably not the right tool.
I can't think of any way to do this that doesn't violate the Liskov substitution principle in some subtle (or not-so-subtle) way. This is a classic example of why not to go crazy with inheritance, just because two classes share some fields, e.g., here or here.
In the end, even if you make it work, it'll probably have so many gotchas and restrictions on the methods you do write, I can't imagine it'll be a net win.
There's an entirely general rule of OOD that states: Favor composition over inheritance.
What this means in practice is that you shouldn't use inheritance for code reuse. It is still legal and valid to use inheritance if the motiviation for doing so is to take advantage of polymorphism.
In your case, if you can manage to write the abstract class/interface SomePoint in such a way that you can deal only with it on that level, and never need to downcast, you should definitely go for it.
If, on the other hand, you find that you need to downcast instances to, say, TwoDPoint or ThreeDPoint, then you gain nothing from inheritance, and you would be breaking the Liskov Substitution Principle. If this is the case, you should consider a design where you can implement reuse without resorting to inheritance - perhaps using a Service or a Strategy.
In games the 2d point and 3d pointtypically don't inherit from eachother, but to be honest I can't think of any fundamental reason for this. So yeah it should be fine, as for naming they are typically vector2 and vector3 so they can hold dimensions, points and colors, all in the same object.
Couldn't you make ThreeDimensionalPoint derive itself from TwoDimensionalPoint?
public class ThreeDimensionalPoint : TwoDimensionalPoint
{
}
I could see a lot of reusable code (methods/properties) in 2D that will be the same in 3D... And you might want to look at a 3D from a 2d standpoint and then all you would need to do is cast it. Just my thougts...
A simpler solution, and one that will avoid some subtle design issues is to just treat all points as 3D and simply ignore the Z coordinate if you're working within a 2D context. You can consider a 2D shape to simply be a 3D shape that happens to lie on a flat plane.

Resources