c++ class with an iterator but no container - stl

I'm trying to implement a class that would allow me to iterate over objects STL-style without explicitly storing them in a container.
A simplified example of this would be, say, a <Paragraph>::iterator in a class that doesn't actually have a container of Paragraphs, but instead has a <string> text variable. It's easy to create a member function that actually goes through text line by line and assemble paragraphs but it seems silly to me to store all this text again in some container just so that I could inherit from it's iterators.
Also, the reason I called it a <Paragraph>::iterator as opposed to a <string>::iterator is because I may want to have an iterator of some different type. For example, I could count the number of chars in each of the paragraphs and have an <int>::iterator.
I guess my question is this: is it appropriate to think in terms of iterators when there's no container?
Thanks

is it appropriate to think in terms of iterators when there's no container?
It’s not only appropriate, it’s the superior way of thinking: classes should have lean interfaces – that is, they should only expose what they need to expose, nothing more. How you handle paragraphs internally (whether you store them in a container, and if so, in which container) is an implementation detail and doesn’t belong in the class’ interface.
The class should in any case only expose an iterator range of the paragraphs. And once you’ve thus got rid of the container on the interface level there might not be a reason to have one inside the class, as you’ve noticed yourself.

Yes, the iterator concept is completely independent of the concept of a container.
The standard library has a set of stream iterators, for example. Anything that can be iterated over should be represented by iterators in C++, whether or not there is an underlying in-memory container.

Boost.Range is geared around this concept.
http://www.boost.org/doc/libs/release/libs/range/index.html

Sounds to me like you are treating a Paragraph object as a container of paragrahs. But wouldn't a Paragraph be part of a container of Paragraphs? and each Paragraph be a container of words (or a string, depending on your needs)? so you could use the std::string iterator in the Paragraph object, and a std container to hold the Paragraph?
You can still create a custom iterator to iterate over what ever you want, however you want, the answer to this question gives a good overview of how to structure your iterator class.

Related

Bind html to multiple .ts file in angular

I'm currently working on an Angular app, specifically a quite complex table, in terms of styling and features.
My component file currently has 2k lines of code, and it comprehends functions for styling text, styling the table, functions for check if data treated are correct, data formatting and so on...
Many of theese funtions are called directly from the HTML fiel thorugh interpolation.
Is there any way to break up this quite large file into smaller ones?
You can break up your component into smaller ones and nest them.
Typical example:
<app-list>
<app-list-item></app-list-item>
</app-list>
The parent component can then pass its properties down to the child components:
<app-list>
<app-list-item [name]="valueFromParent"></app-list-item>
</app-list>
It is further possible to emit values back up from the child to the parent:
<app-list>
<app-list-item (onChildEvent)="updateParent($event)"></app-list-item>
</app-list>
I tried to keep it simple here, but there is more to it.
I suggest going through the official Angular tutorials, because they explain these concepts pretty well.
You should further try to put as much functionality into Services as possible. This also helps to make your components smaller, easier to reason about and helps testing.
E.g. a functions for check if data treated are correct would be a good example for a service method.

Aren't DOM searches for elements with classes depth first?

I was under the impression that when a browser (generally) searches for an element that has a class it is a depth first search.
Recently I was asked to put some code together for a colleague, and asked to identify forms on a page with the substring of 'webform' in the class. I knew there was a form on a page I tested and used the following JS:
document.querySelector("[class*=webform]")
However, this returned the body element of the page whose class attribute had the substring of 'webform' in it. Generally (this question being browser dependant) is the searching in the DOM for elements containing a certain class depth first? Is it totally implementation or browser dependant (as in querySelector will use one method and another function will use a different method)?
Many thanks.
#hungerstar is right. Apologies for the brain fart, seems I need to brush up on my trees a little!
So in conclusion, it proved that it is depth-first. Great!

How to extend multiple elements with Polymer

I know there is this question on multiple inheritance/composition. However, it seems like this question is more about how to reuse functionality from multiple existing elements in other elements. And obviously, the solution for that are mixins.
I would like to know, how I can actually "decorate" existing elements without really borrow functionality from them. We know there is this extends property one can use to extend an existing element with Polymer.
So making a normal <button> behave like a mega-button is as simple as attaching <button is="mega-button"> and write a component for it. But it turns out, that it's not possible to extend multiple elements. So something like extends="foo bar" doesn't work. What if I want to build a web component, that can actually be applied to different elements?
For example, I don't want to only extend <button> elements with mega-button but probably also an <a> element so that it looks like and behaves like a mega-button too?
The mixin approach doesn't really help here (as far as I get it), because they do nothing more then providing shared logic for different web components. That means, you create multiple components, and reuse logic (packed in a mixin) from a mixin.
What I need is a way to create one web component that can be applied to multiple elements.
Any idea how to solve that?
UPDATE
Addy answered with some approaches to handle that use case. Here's a follow up question based on one approach
How to find out what element is going to be extended, while registering my own in Polymer
And another one on Is it possible to share mixins across web components (and imports) in Polymer?
UPDATE 2
I've written an article and concludes my experiences and learnings about inheritance and composition with polymer: http://pascalprecht.github.io/2014/07/14/inheritance-and-composition-with-polymer/
If you need to have just a single import that has support for being applied to multiple elements, your element could include multiple element definitions which may or may not take advantage of Polymer.mixin in order to share functionality between your decorating elements.
So pascal-decorator.html could contain Polymer element definitions for <pascal-span> and <pascal-button>, both of which mixin logic from some object defined within pascal-decorator.html. You can then do <button is="pascal-button"> and <button is="pascal-span"> whilst the logic for doing so remains inside the same import.
The alternative (if you strictly want to do this all in one custom element, which imo, makes this less clean) is to do something like checking against the type of element being extended, which could either be done in the manner you linked to or by checking as part of your element registration process.
In general, I personally prefer to figure out what logic I may need to share between elements that could be decorated, isolate that functionality into an element and then just import them into dedicated elements that have knowledge about the tag (e.g <addy-button>, <addy-video> etc).

Class vs. ID - Readability [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What is the preferred method when dealing with choosing a class vs. an ID?
For instance, you can have a bunch of elements that might be styled identically and could all use the same class. However, for readability purposes, it's sometimes nice to have a unique ID for each element instead.
Obviously you don't want to go ridiculously overboard where every element has an ID. However, where do you guys draw the line and does using all IDs where you could be using classes slow things down noticeably? If so... when?
How to stop obliterating semantic HTML.
Most people learn HTML from looking at source code and of HTML and tinkering with it, learning how <tag>foo</tag> looks and running along with it. They don't really gain a deep understand of it, but they go on to do things that require a deep understanding, the side effect is the problem you and thousands of others have every day -- they're doing things and they don't know fully how these tools work, because it looks so simple on the surface and the powerful uses are are "hidden" in the funny manual that nobody feels the need to read. Everything is plainly explained and been written down for a long time.
What IDs are for (directly from the HTML4 spec, with my notes)
The id attribute assigns a unique identifier to an element (it only happens ONCE, never TWICE or more, I'm tired of seeing people come on this site and dropping in their code with the same ID in twenty elements)
The id attribute has several roles in HTML:
As a style sheet selector. (This means, you can use it to describe CSS styles)
As a target anchor for hypertext links.(When you can jump to a section of a page)
As a means to reference a particular element from a script.(document.getElementById("whatever"))
As the name of a declared OBJECT element.
For general purpose processing by user agents (e.g. for identifying fields when extracting data from HTML pages into a database, translating HTML documents into other formats, etc.).
What Classes are for (directly from the HTML4 spec, with my notes)
The class attribute [...] assigns one or more class names to an element (this one gets to be re-used to your heart's content) ; the element may be said to belong to these classes. A class name may be shared by several element instances. The class attribute has several roles in HTML:
As a style sheet selector (when an author wishes to assign style information to a set of elements).
For general purpose processing by user agents. (Basically, it's just another part of an element)
What? I don't get it.
IDs: It's the fingerprint of something, there's only one, you only use each fingerprint once in the entire document. You only use it when you need to give something an ID. You probably don't want to have hundreds of these, or even tens of these. You rarely if ever need to start making these. The specific uses are for target anchors, improving selector speed in rare edge-cases. Generally you never describe your CSS based on IDs, you might have some edge-cases such as #HEADER .body h1, which may be different from your #BODY, I'd still advise against making them IDs for no real reason.
Classes: Nothing to do with unique fingerprints or linking to sections of a page, classes don't uniquely identify something. Classes describe a group of things that belong together or should behave the same way. If you're part of the class called coffee you should exhibit classes as one might expect from coffee, if you're a class of cellphone, then look like a cellphone (don't provide coffee).
But how the heck am I supposed to access the 4th cell in the 6th column of some table, or group of divs or that 20th list item?
This is where people who don't know what HTML is throw their hands up in the air and decide to assign IDs to all the elements. This is a total side-effect of nobody properly explaining to you how HTML works. That's a nice way of saying you didn't RFTM or ask questions early on (user1066982 in this case, did, which is amazing and makes me happy, I'm writing this to point other people to in the future who fail at HTML).
You need to start learning right now. Stop pretending you understand this stuff.
HTML is not a string of text such as <foo><bar>baz</bar>blah<ding/></foo>, sure that's how you write HTML but if that's what you believe it is you do not understand HTML in the browser.
HTML is a document that is structured like XML. HTML documents have a model, that means they aren't flat text. The text-representation of that document is a way your browser can take flat text and turn it into a tree structure. Trees are like arrays, except they aren't just flat elements in an array one-after-another, but rather they nest so one element may point to several other elements.
This below isn't a diagram (stolen from the w3c's spec on the Document Object Model) of how to write HTML text, this is a diagram of how your browser stores it in memory:
Since it's in memory like that, it doesn't mean "Oh crap! I have no way to access the first TD in the second TR of the table body in the table!", it means you simply and plainly explain to your code that there is a child element inside of the table.
JavaScript provides a full DOM API that allows you to access every single node in that DOM tree.
PHP provides a full DOM API that allows you to access every single node in that DOM tree.
C++ has a full DOM API that allows you to access every single node in that DOM tree.
ASP provides a full DOM API that allows you to access every single node in that DOM tree.
EVERYTHING that touches the DOM provides a full DOM API that allows you to access every single node in that DOM tree, with the exception of sub-standard software that throws regular expressions around in a futile attempt at parsing HTML.
Use the API for the DOM to access those nodes based on semantic HTML. Semantic HTML means you have a structure to your HTML that makes sense. Paragraphs go in <p> tags, headings go into heading tags, and so on.
You never, under any circumstances, what-so-ever need to reproduce the DOM API through hacking in values with ID tags because you didn't know you could just say getAllEmentsByTagName("td")[4] to get the fourth element.
If you can grab getAllEmentsByName("td")[4] you don't need to do <td id="id4"> and then later getElementById("id4") because you didn't want learn just one other API call. I dread the day I ever have to maintain a pile of code left behind by someone who felt the need to stick an ID into every element "just to be sure", especially when I need to go back and insert a new element between the fifth and sixth element in a table of thousands (can you imagine replacing EVERY id? Especially when this feature was accounted for over 10 years ago?! Insanity!)
Tl;dr
HTML isn't actually just a pile of text with one way to access it
rtfm, stop pretending you understand it because you can do a handful of things, you're holding yourself back.
Don't shove IDs everywhere, only use them where absolutely required.
Use classes to describe things, not identify things.
?????
Profit.
However, for readability purposes, it's sometimes nice to have a unique ID for each element instead.
This makes absolutely no sense to me. What makes an ID more readable than a class? There's no point assigning unique identifiers to each of a group of related elements if there's no benefit in having identities.
For what it's worth, realize that a single element can have both classes and an ID. If your elements need to be uniquely identified somehow, give them IDs. If multiple elements should be styled identically and are all similar in purpose anyway, use classes. If your elements fit both criteria, give them both attributes, and use each attribute accordingly.
IDs should not be used for styling. Use classes instead. IDs have a very high specificity, and are difficult to override (leading to more IDs, and longer selector chains). Also, IDs are used for JavaScript DOM selection, so if you're using the same IDs in your CSS that you're using in your JavaScript, you've tied the styles to the scripts, and that's bad separation of concerns.
IDs are for JavaScript. Classes are for CSS.
Note: JavaScript and specificity are not the only reasons. Others include fragment identifiers and code reuse. As I say in the comments, there are several smart people who advise against IDs (start there and follow the links)
I use IDs for elements that have clear responsibility, Classes for element that have same presentations, for example:
HTML:
<div id='sport-news'>
<article class='news'>...</article>
<article class='news'>...</article>
</div>
CSS:
.news { /* global styles */ }
[id=sport-news] .news { /* specific styles */ }
JavaScript:
var sportNews = document.getElementById('sport-news') // faster
, news = sportNews.childNodes;
For me, [id] .class is more readable than .parent-class .child-class.
When designing, I will use both id's and classes. For specific items I will use id only. But if you need to apply same styles for different items, use classes. You cannot use same id for different items because id is specific to one item only.

Is it code-smelly to have empty classes in the middle of a class hierarchy?

I sometimes end up with a class hierarchy where I have an abstract base class with some common functionality and a couple of implementing classes that fall into two (rarely more) groups which I want to treat differently in some cases. An example would be an abstract tree node class and different branch and leaf implementations where I want to distinguish branches and leaves at some point.
These intermediate classes are then only used for "is-a" statements in flow control and they don't contain any code, although I have had cases where they "grew" some code later.
Does that seem smelly to you? In my tree example, one alternative would be to add isLeaf() / isBranch() abstract methods to the base class and implement those on the intermediate classes, but that didn't seem to be any better to me, really, unless I'd mean to have classes that could be multiple things at once.
To me, using "is-a" tests in flow control is just as smelly as using switch/case. In a good OO design, neither is needed.
Yes, deep inheritance hierarchies are a code smell anyway.
Yup, definitely a code smell -- don't code these empty classes unless you're ready to write that code into it. Think YAGNI (you aint gonna need it) -- don't do it unless you need it already.
Also, have you considered cases wherein these classes are only there to provide abstract methods, or to group them based on capabilities in terms of methods or properties?
If that's the case, maybe what you really need are interfaces, not additional abstract classes?
In general, empty classes are a code smell.
I agree your isLeaf or isBranch methods are a correct alternative.
They add information about the objects , which is helpful.
(This is because, on the super class, you can't express that subclasses are "either leaf or branch").
The two methods with opposite results might also be considered as code duplication.
You could use only one... But I would recommend return an enumerated value LEAF or BRANCH.
A class that doesn't contain any code is definitely a code-smell....
Seems alright to me, if you're going to put new functionality in later.
But if not, an enum is generally used here.
-- Edit
Though I must agree with Ber, that you shouldn't generally be using 'is-a' anyway.