Storing Factory Pattern Products - actionscript-3

Right now, I've got a switch statement which is being used to create objects based on a string. There are three types of objects which extend an abstract generic object. I should really be using a factory pattern, which I'm figuring out right now. My issue is thus: I appreciate the flexibility of the factory pattern, but right now I'm storing the would-be products in special dictionaries dedicated to their type.
_type1[location] = ArrayOfType1s
_type2[location] = ArrayOfType2s
_type3[location] = ArrayOfType3s
That works if I only have three types, but if I decide to add more with the flexibility of the factory pattern, then that presents the problem of how to store them, as I'd have to make a special dictionary each time I add one...
The only answer that I can think of is to nest my dictionaries, which sounds pretty slow.
_factoryOutput[type] = type[location] = ArrayOfTypes
That's probably a workable solution, but can anyone suggest a cleaner one? I'm working in AS3, but feel free to provide a more generic solution.

One possible solution is to have your products implement a getType() method. This could just return a string, or int that is unique to that product type. You could dynamically create unique arrays for product types as they come up (ie: check if array exists for type, create if needed before storing) or alternatively, you could just store all product types in one array, and have filter functions for retrieving them. An example of this would be:
function getProductsByType(type:String):Array {
var matched:Array = [];
for(//loop over all products) {
//if type is what your looking for, push into matched array
}
return matched;
}

Related

What is a good way to retrieve the associated value from a struct's enum property when the associated value might have multiple possible types?

I have an array of structs that has been decoded from a JSON file. Each struct has a stored property that is a variable-dimension array stored in an enum associated value.
Some of the structs have property Enum.array2D([[Float]]) and others have Enum.array3D([[[Float]]])
Is there a simple or elegant way to extract a variable-type associated value from the struct's enum property - maybe with a getter function? Currently, the only way I know how to do this is with an external switch anytime I want to access the underlaying value. For example, somewhere in external code I have to use this anytime I want to get these values and manipulate them:
switch structArray[index].enumProperty {
case .array2D(let array2Val):
// Do stuff with the 2D array
case .array3D(let array3Val):
// Do stuff with the 3D array
}
I have considered adding each of the two possible types as optionals and setting the correct one in the init function with a switch, but that seems inefficient as I’ll have the arrays stored in two places.

TypeScript types serialisation/deserialization in localstorage

I have a Typescript app. I use the localstorage for development purpose to store my objects and I have the problem at the deserialization.
I have an object meeting of type MeetingModel:
export interface MeetingModel {
date: moment.Moment; // from the library momentjs
}
I store this object in the localStorage using JSON.stringify(meeting).
I suppose that stringify call moment.toJson(), that returns an iso string, hence the value stored is: {"date":"2016-12-26T15:03:54.586Z"}.
When I retrieve this object, I do:
const stored = window.localStorage.getItem("meeting");
const meeting: MeetingModel = JSON.parse(stored);
The problem is: meeting.date contains a string instead of a moment !
So, first I'm wondering why TypeScript let this happen ? Why can I assign a string value instead of a Moment and the compiler agree ?
Second, how can I restore my objects from plain JSON objects (aka strings) into Typescript types ?
I can create a factory of course, but when my object database will grow up it will be a pain in the *** to do all this work.
Maybe there is a solution for better storing in the local storage in the first place?
Thank you
1) TypeScript is optionally typed. That means there are ways around the strictness of the type system. The any type allows you to do dynamic typing. This can come in very handy if you know what you are doing, but of course you can also shoot yourself in the foot.
This code will compile:
var x: string = <any> 1;
What is happening here is that the number 1 is casted to any, which to TypeScript means it will just assume you as a developer know what it is and how you to use it. Since the any type is then assigned to a string TypeScript is absolutely fine with it, even though you are likely to get errors during run-time, just like when you make a mistake when coding JavaScript.
Of course this is by design. TypeScript types only exist during compile time. What kind of string you put in JSON.parse is unknowable to TypeScript, because the input string only exists during run-time and can be anything. Hence the any type. TypeScript does offer so-called type guards. Type guards are bits of code that are understood during compile-time as well as run-time, but that is beyond the scope of your question (Google it if you're interested).
2) Serializing and deserializing data is usually not as simple as calling JSON.stringify and JSON.parse. Most type information is lost to JSON and typically the way you want to store objects (in memory) during run-time is very different from the way you want to store them for transfer or storage (in memory, on disk, or any other medium). For instance, during run-time you might need lookup tables, user/session state, private fields, library specific properties, while in storage you might want version numbers, timestamps, metadata, different types of normalization, etc. You can JSON.stringify anything you want in JavaScript land, but that does necessarily mean it is a good idea. You might want to design how you actually store data. For example, an iso string looks pretty, but takes a lot of bytes. If you have just a few that does not matter, but when you are transferring millions a second you might want to consider another format.
My advise to you would be to define interfaces for the objects you want to save and like moment create a .toJson method on your model object, which will return the DTO (Data Transfer Object) that you can simply serialize with JSON.stringify. Then on the way back you cast the any output of JSON.parse to your DTO and then convert it back to your model with a factory function or constructor of your creation. That might seem like a lot of boilerplate, but in my experience it is totally worth it, because now you are in control of what gets stored and that gives you a lot of flexility to change your model without getting deserialization problems.
Good luck!
You could use the reviver feature of JSON.parse to convert the string back to a moment:
JSON.parse(input, (key, value) => {
if (key == "date") {
return parseStringAsMoment(value);
} else {
return value;
});
Check browser support for reviver, though, as it's not the same as basic JSON.parse

Best way to map Object ID References?

I'm writing an application where I have many objects (data models) that are identified by a unique String ID that every such object possesses and these objects can refer to each other by their IDs.
So far so good but now I need to keep track of which object keeps a reference to another object and of course there are cases where an object references (or is referenced by) more than one other object and I was wondering what would be the best method to store these references? In a simple map data structure I could just map one object's ID to another but as mentioned there are cases where an object can hold a ref to an arbitrary amount of other objects. Or I could map another map or an Array that hold more than one reference but I'd like to prevent iteration and maybe somebody knows a much better solution for this.
I guess it depends a lot in the particular use, but I think a Dictionary is the way to go, unless you need the order of the references, in which case I think an Array (or Vector) should work...
//Array:
object1.references.push(object2);
for each(var o in object1.references) trace(o);
object1.references.pop();
//Dictionary:
object1.references[object2] = 1;
for (var o in object1.references) trace(o);
delete object1.references[object2];
Whenever you have a dynamic arbitrary set of objects, I think you will necessarily need to iterate through them, whether its an array, object or dictionary.

Casting objects created in LINQ to SQL to a single master object

I have an interesting problem to solve that would be helped by successfully casting objects created by LINQ to SQL into a single master object that I could pass around. Here is the scenario at a high level.
I have a number of stored procedures that fetch data and then all return the exact same columns. The params into the procs and the logic vary greatly, so a single proc will not work. Then Linq creates a strongly typed object which is used throughout my application as parameter and return values.
I am using these strongly typed objects as noted above as parameters and return values in a series of filters used to analyze stocks. My client would like to change the order the order of the filters. The issue is that each succeeding filter will only work on what passed the last filter.
Currently I am hard coding my parameters, and if I could create a master object that I could cast any of these Linq objects to, I could then always pass and return the master object.
I have read the materials available on the internet about casting between different types such as static to anonymous types or a list of integers and an array list containing objects representing integers, but I need to actually cast one object into another.
What general direction would I take to solve this problem of converting strongly typed objects generated by linq that are exactly the same into a single master object?
Thank you for any of your thoughts.
If all your linq objects have the same fields, you could have them implement an interface defined with those common fields. Then the calls to your filter methods can depend on an interface rather than a specific implementation. In other words, the parameters in the filter methods will be of the interface type rather than a linq class type.
e.g.: Where ICommonFields is an interface you define with all the common fields in each l2s class -
public class Filterer
{
public ICommonFields filterStuff(ICommonFields x)
{
//do stuff
}
}
or -
public class Filterer
{
public T filterStuff<T>(T x)
where T: class, ICommonFields, new()
{
//do stuff
}
}
I'd prefer the generic version, as T becomes the actual type rather than a reference through an interface - linq-to-sql has issues when using a type through an interface with query expressions.
Edit: sorry, it was late when i first wrote this response (likely excuse! :). Fixed my obvious mistake with the example code :)
Although there might be a way to do this with casting, I'm going to offer you a quick and dirty solution - and I'm assuming that your resultant objects are collection-based:
Given that all of your child objects
all share the same columns, go ahead
and pick one of them to act as your
master object - then simply iterate
through the rows of your other LINQ
objects and add them to the collection
of your master object. If your
resultant object is a strongly typed
data table, then all you'd do is Add
to the .Rows collection.
Additionally, you might be able to just add the elements retrieved some subsequent LINQ queries directly to your master object depending upon how you write your SELECT causes in LINQ.

Where Do I Store Hash Table or Dictionary Key Names

When I'm working with Hash Tables/Dictionaries I sometimes struggle with how to specify keys.
For example: if I create a simple Dictionary (using Python for this example),
foo = {'bar': 'baz', 'foobar': 'foobaz' }
I can access values (in other modules) with the key values: (foo['bar']) and get baz back.
In the words of Dr. Evil, "pretty standard, really."
Unfortunately, using static strings for keys tightly couples any modules using this Dictionary to its implementation. Of course, this can also apply when using other key types (e.g. Enums, Objects, etc.); anyway you slice it, all modules which access the Dictionary need to know the values for the keys.
To resolve this, I typically use static constant string values (or Enums if available in the language) for keys, and either store them publicly in the local class/module, or in a separate module/class. Therefore any changes to the dictionary keys themselves are kept in a single location.
This usually looks like this:
BAR_KEY = 'bar'
foo[BAR_KEY] = 'foobar'
Are there better ways of specifying keys such that the use of the Dictionary doesn't necessarily couple a module/class to its implementation?
Note: I've seen a few responses in SO which address this (e.g. property-to-reference-a-key-value-pair-in-a-dictionary), but the topics didn't seem to address this issue specifically. The answers were helpful, but I'd like a wider range of experience.
Why not make a class for this, which only contains properties? This is done nicely with Python (from what I know), and works well with other languages, too. Refactoring the names is trivial with today's tools, too.
In cases where I'm passing the object around and I've got known keys, I'd always prefer adding an attribute to an object. IMO, the use case of dictionaries is when you don't know what the keys are.
Python is trivial:
foo.bar=baz
Java is pretty much the same:
class Foo { public String bar="baz"; }
The Python performance would be pretty much identical, since a property lookup is just a dictionary lookup and the Java performance would be better.
I sometimes create a separate class to hold the dictionary keys. That gives them their own namespace, as well as the regular benefits of having the keys be in const strings, namely that you don't have the risk of typos, you get code completion, and the string value is easy to change. If you don't want to create a separate class, you get all of the benefits except a namespace just from have const strings.
That said, I think you're getting close to soft coding territory. If the keys in the dictionary change, it's OK for code using the dictionary to change.
Personally, I use your method. It's pretty sensible, simple, and solves the actual problem.
I usually do the same thing; if the key is always going to be the same, make a 'constant static' in whatever language to hold the key.