I have a class with a large number of properties that map to some JSON data I've parsed into a Map object elsewhere. I'd like to be able to instantiate a class by passing in this map:
class Card {
String name, layout, mana_cost, cmc, type, rarity, text, flavor, artist,
number, power, toughness, loyalty, watermark, border,
timeshifted, hand, life, release_date, starter, original_text, original_type,
source, image_url, set, set_name, id;
int multiverse_id;
List<String> colors, names, supertypes, subtypes, types, printings, variations, legalities;
List<Map> foreign_names, rulings;
// This doesn't work
Card.fromMap(Map card) {
for (var key in card.keys) {
this[key] = card[key];
}
}
}
I'd prefer to not have to assign everything manually. Is there a way to do what I'm trying to do?
I don't think there is a good way to do it in the language itself.
Reflection would be one approach but it's good practice to avoid it in the browser because it can cause code bloat.
There is the reflectable package that limits the negative size impact of reflection and provides almost the same capabilities.
I'd use the code generation approach, where you use tools like build, source_gen to generate the code that assigns the values.
built_value is a package that uses that approach. This might even work directly for your use case.
Related
I have this method
#override
Response<BodyType> convertResponse<BodyType, SingleItemType>(
Response response) {
final Response dynamicResponse = super.convertResponse(response);
final BodyType customBody =
_convertToCustomObject<SingleItemType>(dynamicResponse.body);
return dynamicResponse.replace<BodyType>(body: customBody);
}
What does it mean <BodyType> and <BodyType, SingleItemType> in this method?
These are called generics in Dart (in fact, they are called the same in other similar programming languages).
The main idea behind generics is that you could reuse the same code without relying on a specific data/return type. Imagine List in Dart. You could have a list of integers (List<int>), a list of strings (List<String>), a list of your custom objects (List<CustomType>) - the type is not hardcoded and it could be adjusted based on your needs.
Also, you could say that it would be easier just to use dynamic or Object types that would cover most of these cases. However, generics brings you type safety, and the method type itself becomes a parameter.
Here is the official documentation about generics.
I would like to represent a kind of class table (CT) as a singleton in Rascal, so that some transformations might refer to the same CT. Since not all transformations need to refer to the CT (and I prefer not to change the signature of the existing transformations), I was wondering if it is possible to implement a kind of singleton object in Rascal.
Is there any recommendation for representing this kind of situation?
Edited: found a solution, though still not sure if this is the idiomatic Rascal approach.
module lang::java::analysis::ClassTable
import Map;
import lang::java::m3::M3Util;
// the class table considered in the source
// code analysis and transformations.
map[str, str] classTable = ();
/**
* Load a class table from a list of JAR files.
* It uses a simple cache mechanism to avoid loading the
* class table each time it is necessary.
*/
map[str, str] loadClassTable(list[loc] jars) {
if(size(classTable) == 0) {
classTable = classesHierarchy(jars);
}
return classTable;
}
Two answers to the question: "what to do if you want to share data acros functions and modules, but not pass the data around as an additional parameter, or as an additional return value?":
a public global variable can hold a reference to a shared data-object like so: public int myGlobalInt = 666; This works for all kinds of (complex) data, including class tables. Use this only if you need shared state of the public variable.
a #memo function is a way to provide fast access to shared data in case you need to share data which will not be modified (i.e. you do not need shared state): #memo int mySharedDataProvider(MyType myArgs) = hardToGetData();. The function's behavior must not have side-effects, i.e. be "functional", and then it will never recompute the return value for earlier provided arguments (instead it will use an internal table to cache previous results).
For example, I'd like to just be able to write:
class Dog {
final String name;
Dog(this.name);
bark() => 'Woof woof said $name';
}
But have #Dog.bark's type definition be () => String.
This previously wasn't possible in Dart 1.x, but I'm hoping type inference can save the day and avoid having to type trivial functions where the return type is inferable (the same as it does for closures today?)
The language team doesn't currently have any plans to do inference on member return types based on their bodies. There are definitely cases like this where it would be nice, but there are other cases (like recursive methods) where it doesn't work.
With inference, we have to balance a few opposing forces:
Having smart inference that handles lots of different cases to alleviate as much typing pain as we can.
Having some explicit type annotations so that things like API boundaries are well-defined. If you change a method body and that changes the inferred return type, now you've made a potentially breaking change to your API.
Having a simple boundary between code that is inferred and code that is not so that users can easily reason about which parts of their code are type safe and which need more attention.
The case you bring up is right at the intersection of those. Personally, I lean towards not inferring. I like my class APIs to be pretty explicitly typed anyway, since I find it makes them easier to read and maintain.
Keep in mind that there are similar cases where inference does come into play:
Dart will infer the return type of an anonymous function based on its body. That makes things like lambdas passed to map() do what you want.
It will infer the return type of a method override from the method it is overriding. You don't need to annotate the return type in Beagle.bark() here:
class Dog {
String bark() => "Bark!";
}
class Beagle extends Dog {
final String name;
Dog(this.name);
bark() => 'Woof woof said $name';
}
What's the preferred way of getting a value in swift?
Using a read-only variable
var getString: String? {
return "Value"
}
or using a function?
func getString() -> String? {
return "Value"
}
Also, is there a performance difference between the two?
First, neither of these would be appropriate names. They should not begin with get. (There are historical Cocoa meanings for a get prefix that you don't mean, and so even if you mean "go out to the internet and retrieve this information" you'd want to use something like fetch, but certainly not in the case you've given.)
These issues are addressed in various sections of the Swift API Design Guidelines. First, a property is a property, whether it is stored or computed. So there is no difference in design between:
let someProperty: String?
and
var someProperty: String? { return "string" }
You should not change the naming just because it's computed. We can then see in the guidelines:
The names of other types, properties, variables, and constants should read as nouns.
Furthermore, as discussed in The Swift Programming Language:
Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value.
So if this is best thought of as a value associated with the type (one of its "attributes"), then it should be a property (computed or stored). If it is something that is not really "associated" with the type (something that the caller expects this type to retrieve from elsewhere for instance), then it should be a method. Again from the Design Guidelines:
Document the complexity of any computed property that is not O(1). People often assume that property access involves no significant computation, because they have stored properties as a mental model. Be sure to alert them when that assumption may be violated.
If "stored properties as a mental model" doesn't match what you mean to express, then it probably shouldn't be a property in the first place (and you need to document the discrepancies if you make it a property anyway). So, for instance, accessing a property should generally have no visible side effects. And if you read from a property immediately after writing to it, you should get back the value you wrote (again, as a general mental model without getting into the weeds of multi-threaded programming).
If you use a method, it can often result in a different appropriate name. See the "Strive for Fluent Usage" section of the Design Guidelines for more on that. There are several rules for selecting good method names. As a good example of when to use properties vs methods, consider the x.makeIterator(), i.successor() and x.sorted() examples and think about why these are methods and why they're named as they are. This is not to say there is exactly one answer in all cases, but the Design Guidelines will give you examples of what the Swift team intends.
With no discernible difference in performance, make the choice for readability:
When an attribute behaves like a variable, use a property. Your example falls into this category.
When reading an attribute changes object state, use a function. This includes
Attributes that behave like a factory, i.e. returns new objects when you access them
Attributes that produce new values, such as random number generators
Peripheral readers
Input iterators
Of course, if the attribute is computed based on one or more argument, you have no other choice but to use a function.
Just as a note: If you want to use both getters and setters in Swift you can do as follows:
var myString: String {
get {
return "My string"
}
set {
self.myPrivateString = newValue
}
}
This way you can access your value as if it was a regular variable, but you can do some "under-the-hood magic" in your getters and setters
I found this method in one of examples for dependency Injecting a Controller. What is the reason of using an interface type IList<> instead of List<>?
public IList<string> GetGenreNames()
{
var genres = from genre in storeDB.Genres
select genre.Name;
return genres.ToList();
}
The actual reason, you're going to go ask the original programmer of that method that.
We can come up with a plausible reason however.
Input parameters should be as open and general as possible. Don't take an array if you can use any collection type that can be enumerated over. (ie. prefer IEnumerable<int> over List<int> if all you're going to do is do a foreach)
Output parameters and return types should be as specific as possible, but try to return the most usable and flexible data type possible without sacrificing performance or security. Don't return a collection that can only be enumerated over (like IEnumerable<int>) if you can return an array or a list you created specifically for the results (like int[] or List<int>).
These guidelines are listed many places on the internet (in different words though) and are there to help people write good APIs.
The reason why IList<T> is better than List<T> is that you're returning a collection that can be:
Enumerated over (streaming access)
Accessed by index (random access)
Modified (Add, Delete, etc.)
If you were to return List<T> you wouldn't actually add any value, except to return a concrete type instead of just any type that happens to implement that interface. As such, it is better to return the interface and not the concrete type. You don't lose any useful features on the outside and you still retain the possibility of replacing the actual object returned with something different in the future.
targeting interface is always better than targeting concrete type.
So if returning IList, that means anything implementing IList could be returned, give better separation.
check this out for more info
Why is it considered bad to expose List<T>?
It's somewhat basic rule in OOP. It's good to have an interface so your clients (the caller of GetGenreNames ) knows only how to call (function signature, only thing to remember, rather than implementation details etc) to get serviced.
Programming to interface supports all goodies of OOP. its more generalized, maintains separation of concerns, more reusable.