What is the comprehension expression in AngularJS? - angularjs

I have a few questions buzzing in my head about the comprehension expression:
What is the data structure which it defines?
Was it adapted from some other language?
Where is it used in AngularJS? Does this API exist for select elements only?
From the docs:
ngOptions - comprehension_expression - in one of the following forms:
for array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array track by trackexpr
for object data sources:
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object

Comprehension expression is just a string formatted in a special way to be recognized by select directive.
There's no magic behind it, just several formats of it because there are quite a few ways to process and represent your collection (data structure of your model, item/item property selection as scope's model, some other options regarding labels, grouping etc.). When you consider all these options it is not that strange for allowing complex expressions.
Let's say you have such code:
<select
ng-model="color"
ng-options="c.name group by c.shade for c in colors"></select>
In order to ditch the comprehension expression and use attributes, you would write something like this:
<select
ng-model="color"
ng-data-type="object"
ng-data="colors"
ng-select="c"
ng-label="c.name"
ng-group-by="c.shade"></select>
The attribute approach might get ugly once you expand your API. Besides, with comprehension expression it's much easier to use filters.

While in one way it's true to say that a "comprehension_expression" is "just a string" as package says, on the other hand, source code is just a string. Programming languages are just strings.
A SQL SELECT statement
– which could very well be part of the inspiration for the syntax and features of the "comprehension_expression" (but it's not obvious that it is, because it's not mentioned in the docs– perhaps if I dug into some developer conversations I might be able to find out) –
is just a string.
Sure they're just strings, but they have structure, which relates to the problem they are trying to solve. And the question is, is the structure adequately described? Is its pattern, how it relates to the problem at hand, made clear? Is its relationship to other structures that other people have designed apparent?
While the "comprehension_expression" is just a string, on the other hand, its complexity almost comes to it being a sort of sub-language in its own right.
But the way it is portrayed in the docs (https://docs.angularjs.org/api/ng/directive/ngOptions) does reflect the attitude that it is "just a string with some formatting". It is tucked away in the documentation for ng-options as the type of the ng-options directive. To some extent, it is not an entity in its own right, it is a second-class citizen.
The way the different formats are listed can give one a strange feeling, like it's sort of ad-hoc, without any pattern relating the different possible formats (although there is a pattern if you look closely). Without a formal grammar with a regular structure, it makes you wonder if they really covered all the possible options. Compared to, say, the MySQL documentation for the SQL SELECT statement: https://dev.mysql.com/doc/refman/5.7/en/select.html
Obviously such formal syntax can be quite intimidating and is maybe not necessary for the case of the "comprehension_expression", on the other hand it can be reassuring to know it is precisely defined.
I suspect the asker of the question was somewhat unsettled by how casually the "comprehension_expression" was mentioned in the docs; it can seem like a sort of floating, ghost-like entity, just mentioned briefly but not given its own page etc.
It might be worth it having its own page, being treated as an entity in its own right, because then that invites discussion as to the design of this "sub-language". How did it come about? What are the reasons for the different features of the "sub-language"? Which features, and thus syntaxes, conflict with each other? Why can this feature be used together with that feature but not another feature? Are there inspirations from e.g. SQL, in the design of this "sub-language"?
Otherwise it seems to be an invention out of the blue, unrelated to other DSLs of its kind.
In a blog post on ng-options,
https://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
Mr. Shidhin links to a little discussion
https://groups.google.com/forum/#!topic/angular/4EDe8xIbjLU
Where just this issue is discussed. "Matt Hughes" also expresses the opinion that "Seems like a lot of additional complexity for one directive."
Perhaps this is not that big a deal. I just wanted to put it out there though.

Related

What are some GraphQL schema naming best practices?

I'm beginning development on a nontrivial application for which we're considering GraphQL. When working on the initial draft of our schema, I've become a bit paralyzed trying to establish naming conventions that will scale as the product matures. I would really appreciate some insight from anyone who has had to grow a schema and run into, or successfully avoided dead ends or inconsistencies:
Is it generally useful/idiomatic to keep the name "Interface" in the name of an interface? For example, would Profile or ProfileInterface be preferable in a large app?
interface ProfileInterface {
# fields here...
}
type UserProfile implements ProfileInterface {
# implemented fields here...
}
Is it common to specify single-enum values as "constants"?
enum GeoJSONFeatureTypeConstant {
feature
}
interface GeoJSONFeatureInterface {
id: ID
type: GeoJSONFeatureTypeConstant!
geometry: GeoJSONGeometryInterface!
properties: GeoJSONProperties
}
Is it best practice to declare all-or-nothing objects as scalar or type, and where is the line drawn between the two? Imagine a Point type that is would typically be represented as an array [x,y]; which would be more idiomadic?
scalar Point
type Point {
x: Float
y: Float
}
Any other best-practices specifically related to naming conventions or type declarations in GraphQL that would be difficult to know without experience.
Thanks in advance!
This question hasn't gained the momentum I would have liked, so I'm going to start posting useful snippets as I find them, which may evolve into an answer of sorts.
Naming input types with Input on the end is a useful convention,
because you will often want both an input type and an output type that
are slightly different for a single conceptual object.
http://graphql.org/graphql-js/mutations-and-input-types/
I pondered about these same questions and I hope this will be helpful to you.
1. I don't believe that appending Interface at the end of every interface is idiomatic. It is much better to have a descriptive name instead. Consider the example provided in the GraphQL Specification relating to Interfaces. They don't append Interface to any of their types.
2. Enums are only advantageous when there are multiple related values. I don't see how including type is helpful when there is only one possible value. Enum values are also named with all caps and underscores per the GraphQL Specification relating to Enums.
3. If you decided to implement a scalar type then it is up to you to validate the field. In this specific case, providing Point as a type makes the most sense as a Point could be 2-D or 3-D. Defining it as a type is more declarative.
Values such as Date, Email and Url are common examples for scalar types. They provide semantic value and clients will know what to expect from these fields.
Here's the relevant section for custom scalars.
Here's an example.
4. You will find this article by Lee Byron helpful.
I found this graphql API design tutorial from Shopify some time ago. I think there is no explicit chapter but best practice w.r.t. naming convention spread across the tutorial.

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

Whys is it a bad idea to have an Object[] array?

I was explaining to a friend a few days ago the concept or inheritance and containers.
He has very little programming knowledge so it was really just a friendly chat.
During the conversation he came to me with a question that i just couldn't answer.
"Why cant you just have an array of the top level class, and add anything to it"
I know this is a bad idea having being told so before by someone far smarter but for the life of me i couldn't remember why.
I mean we do it all the time with inheritance.
Say we have class animal which is parent of cat and dog. If we need a container of both of these we make the array of type animal.
So lets say we didn't have that inheritance link, couldn't we just use the base object class and have everything in the one container.
No specific programming language.
Syntactically, there is no problem with this. By declaring an array of a specific type, you are giving implicit information about the contents of that array. You could well declare a contain of Object instances, but it means you lose all the type information of the original class at compile-time.
It also means that each time you get an object out of the array at runtime, the only field instances and methods you know exist are the fields/methods of Object (which arguably is a compile time problem). To use any of the fields and methods of more specific subclasses of the object, you'd have to cast.
Alternatively, to find out the specific class at runtime you'd have to use features like reflection which are overkill for the majority of cases.
When you take elements out of the container you want to have some guarantees as to what can be done with them. If all elements of the container are returned as instances of Animal (remember here that instances of Dog are also instances of Animal) then you know that they can do all the things that Animals can do (which is more things than what all Objects can do).
Maybe, we do it in programming for the same reason as in Biology? Reptiles and Whales are animals, but they are quite different.
It depends on the situation, but without context, it's definitely okay in most (if not all) object-oriented languages to have an array of a base type (that is, as long as they follow all the substitution principles) containing various instances of different derived types.
Object arrays exist in certain cases in most languages. The problem is that whenever you want to use them, you need to remember what type they were, and stay casting them or whatever.
It also makes the code very horrible to follow and even more horrible to extend, not to mention error prone.
Plant myplant = new Plant();
listOfAnimals.Add(myplant);
would work if the list is object, but you'd get a compile time error if it was Animal.

ANTLR and arrays

I have question relating to implementation of arrays with Java+ANTLR combo. (I'm mainly talking about java/c style arrays).
So basically I'm asking how do you implement such feature, if there is such example already available or if someone could point me to anything that may point to solve it.
On other hand, I've searched a bit how would possible solution be. Main problem that I see
is that user may create arrays of various dimensions, even go crazy if he or she wants (like creating 5 dimension arrays or worse).
While grammar for something like this is fairly simple, like
new ID (INT (',' INT)* )
back end really gets involved a bit. As I said, user may input any number of dimensions, so array dimensions should be dynamically created. (at least as I see it, maybe I'm over complicating things?)
After searching I did found something that pretty much solves this problem perfectly, here is link to the question:
Is it possible to dynamically build a multi-dimensional array in Java?
Of course, my question is, is this viable example, it is a bit (to say at least), complicated? Is there more elegant solution to it?
Having that in mind, I was thinking maybe answer might be in the grounds of somehow transforming multidimensions
into more linear structure ? Could something like that be useful ? Simple search on stackoverflow pointed many solutions
to this, like:
Algorithm to convert a multi-dimensional array to a one-dimensional array
Would it be worth to search in that direction ?
Now, at the end, having in mind that arrays are really common feature in many languages, I must find it surprising that after searching ANTLR mailing list there is no similar question, which as I previously said leads me to believe that I'm maybe over complicating things ? (Unless I really suck at search?) I would really appreciate feedback.
Your syntax, if I'm not mistaken, corresponds to something like
new char 4,5,6,7
which is kind of strange. I expect that you really meant
new char[4,5,6,7]
However from a purely syntactic point of view, there's no reason not to just store the indices in an array and let the semantic analysis pass worry about it.

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