Prototype JS - Can't chain element.previous(0).match() - prototypejs

Long story short, I've had a long story here but reduced it to Q&A to help others!
I had the following loop:
$$('#leftCntr label').each(function(elem){
if($(elem).previous(0).match('h3'))
{
console.log($(elem).previous(0).innerHTML);
}
});
it didn't work... but the problem was very obvious...
i had to check if there really IS a previous, otherwise you can't chain the functions

Some elements don't have previous elements... -_- but only parents ofcourse,,
It only took me 3 to 4 hours to solve this |-)
So I hope I could help someone with this!!!
$$('#leftCntr label').each(function(elem){
if($(elem).previous(0) && $(elem).previous(0).match('h3'))
{
console.log($(elem).previous(0).innerHTML);
}
});
p.s. just starting with a stackoverflow account because it's just the best site around for stuff like this and I want to help too!! :) I hope to provide you people with more of my solutions to awkward problems when I encounter them!

Related

Does C# 6 make it possible to imply type inference (not explicitly use the var keyword)?

This is an odd question, I know.
Earlier this week, I was browsing hacker news and glossed past an article about the power of C# 6. I meant to 'pocket' the link at the time but I didn't and now I can't find the article again.
Long story short, there was an example of code which looked roughly like this...
using static Variables;
public class Blah
{
public Blah()
{
s = "something"
Console.WriteLine(s);
}
}
... as if to say, somehow it was possible using some magical combination of C# 6 features to remove the 'var' element of that equation and have valid code.
I'm struggling to see how that's possible without some extra Roslyn magic and even then, I'd struggle.
If you know where the article is please let me know. If not, is this even remotely possible? I'm fairly confident it would be an odd thing to do,..I'm just intrigued.
Thanks in advance.

When are comments "too much", and when are they not enough? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
There is an on-going minor debate where I work about the efficacy of comments within code. One of the leads instructed his developers not to use comments as they are too "old fashioned", and a couple of other developers indicated that they never use comments because they feel all they do is clutter up the code.
I have always pretty much adhered to the practice that I comment the top of every file with a basic comment block, comment each method/class/etc definition, and then I comment any place in the code where I think I might come back in 6 months and think to myself, "WTF".
Clearly this is subjective, but I'm curious to know if anyone has any really good arguments or experiences for one way or the other.
I'll just point you to Jeff Atwood's wonderful post on the subject, which hits the nail right on the head.
In all my career, I have never come across that wonderful beast "self-documenting code". Maybe I've just been unlucky, but I'm beginning to suspect it doesn't actually exist.
Every once in a while I run across code that is so elegantly partitioned, has such compellingly obvious method, field and variable names that everything I need to know is obvious from the code.
In the general case, only really great code gurus write such code. The rest of us cobble together something that works.
If you're a really great code guru, don't bother sullying your divine code with superfluous comments.
If you barely know what you're doing, be careful to document your blundering attempts so others can try to salvage the mess.
If you're average (and most of us are, sort of by definition) then leave some hints in comments for yourself and others to make things easier at maintenance time, but don't insult anyone's intelligence and waste space by documenting the REALLY obvious. Ideally, your comments should describe your code at a meta-level, indicating not what you're doing but why. Also how, if you're doing something unusual or tricky.
"One of the leads instructed his developers not to use comments as they are too "old fashioned", and a couple of other developers indicated that they never use comments because they feel all they do is clutter up the code."
If I ever heard a developer I was working with talk like this, I would correct them. If I didn't have the necessary rank to correct them, I would leave the job.
Very clearly written code, with good identifiers -- the stuff sometimes referred to as 'self-documenting' -- does a fine job of illustrating what the code is doing. That's fine as far as it goes. The job of the comments is to explain why.
This topic tends to be discussed a lot, but here are my US$0.02 on the subject:
I would rather see too many comments than not enough. Failing at anything, you can always delete superfluous comments from the code; however, you can not derive meaning from them if there are none there to begin with.
I've heard some developers argue that other developers that "over document" (definitions of this vary by person) their code are not good developers. While saying that you are updating a counter might be a sign that you don't know what you are doing, having a clear guide to some of the business logic sitting there in the middle of the method you are working on can be quite useful.
While there are some excellent developers out there that can write extremely clear code that doesn't require comments, most developers aren't that good or they spend more time writing the code to be self documenting than they would if they had just included a couple comments.
You don't know the skill level of the next person to read your code and if the language constructs you are using might be confusing it is usually a good idea to include a comment that someone can use to Google a tutorial with.
The problem with comments is that they tend to stay long after the code that was commented has changed or even been deleted.
As a rule of thumb I'd only comment public API and difficult to understand algorithms.
Don't use comments to explain what you did - that's what the code is for, use comments to explain why you did it.
Diomidis Spinellis just wrote a nice column for IEEE column (quoted on his blog), outlining the problem, and a few solutions:
When commenting, we’re always a couple
of keystrokes away from disaster:
restating the code’s function in
English. And that’s when problems
start.
One should write comment before the code or before the function so that next time looking at the function he/she can know immediately what was the purpose of that code.
It is happened to me many times that I write the code and then forgot the purpose of that. so, I make habit of writing comment before code.
What I'd like to see in the comments is an explanation why a method that is obvious and much simpler than the method used in the code doesn't work.

Is it acceptable to have useless code?

I see that some programmers add code that, after all, does not do anything useful. For instance (C#):
[Serializable]
class Foo {
// ...
string SerializeMe() {
return new XmlSerializer(typeof(this)).Serialize(this).ToString(); // serialize to xml (syntax wrong, not important here)
}
}
The class is marked as Serializable, but the only way it is serialized is by means of XmlSerialization, which does not require that class attribute at all.
I personally hate this kind of useless code, but I see it quite often and I'm curious as to what others think about it. Is this not so serious a flaw after all? Is it common practice in the industry? Or is this just plain bad and should be removed no matter what?
Good Source Control means that useless code or code that is no longer required should be removed. It can always be retrieved from the source control at a later date.
My rule of thumb,
If its not used get rid of it.
All surplus comments, attrributes are just noise and help your code to become unreadable. If left there they encourage more surplus code in your code base. So remove it.
I try to follow the YAGNI principle, so this bothers me as well.
Does it take even a minimal effort to read that additional (useless, as you added) code?
If yes (and I think it is so) then it should not be in the code. Code like this is polluted with extra snippets that are not useful, they are there "just in case".
The "later on refactoring" of these things can be painful, after 6 o 12 months, who is going to remember if that was really used?
Really don't like it.
Because I then spend valuable time trying to figure out why it's there. Assuming that if it's there, it's there for a reason, and if I don't see the reason, then there's a chance I'm missing something important that I should understand before I start messing with the code. It irritates me when I realize that I've just wasted an hour trying to understand why, or what, some snippet of code is doing, that was just left there by some developer too lazy to go back and remove it.
Useless one-liner code can and should be removed.
Useless code that took time to write can and should be removed...but people in charge tend to get queasy about this. Perhaps the best solution is to have a ProbablyUselessButWhoKnows project where everyone can check in pointless code that might be used again in two or three years. If nothing else, this way people don't have to feel nervous about deleting it.
(Yes, in theory you can get it out of source control, but old deleted code in source control is not exactly highly discoverable.)
In a commercial project - I'd say no, especially if someone can de-assemble it for reading and then has a WTF moment.
In a home-project - sure why not, I often keep some snippets for later use.
Well I can't comment this particular piece of code without knowing your background but I personally follow strictly a rule not to have anything in code unless I really need it. Or at least know that it may be useful some day for something I have in mind already now.
This is bad code.
Bad code is common practice.
That being said sometimes it is not worth the effort in changing stuff that isn't "broken".
It would seem that perfection is attained not when no more can be added, but when no more can be removed. — Antoine de Saint-Exupéry
Is think the meaning of useless is that it cannot and will not be used. I also think that an open door is very open.
If there is an active plan to use this additional feature, then keep it in.
If you know it will never be used, or if that plan stopped being relevant 6 months ago, then pull it out. I'd comment it out first, then remove it fully later.
I'm in the midst of rescoping a lot of variables that were public but really only need to be protected or private, simply because they don't make sense from an API perspective to be exposed--that and nothing uses them.

Do you update ancient code comments that are wrong? [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 10 years ago.
G'day,
Inspired by a comment I made in my answer to this question on commenting Perl regexps I was wondering the following.
When you are working on older, old, bloody ancient, code do you update comments that are out of sync with the code or do you just update the code and ignore the comments that are already "miles out" from the reality of the current code?
I guess basically approaching things from the "broken window" syndrome?
BWS basically says that people just say "stuff it" and don't take care to fix errors that are there if they see that people, already involved with the system in question, didn't care enough to fix these sorts of things. A totally pervasive mind set IMHO!
I'd be interested to see what other people "at the coalface" do.
cheers,
I will absolutely fix bad comments.
Sometimes it is just to delete them so that they don't mislead.
Better still, I prefer to refactor the code so the comments are not necessary - self documenting code is better than comments because it can't get out of date.
Recently I started following more of Uncle Bob's Clean Code advices and I'm trying to transform comments into functions that enclose (extract) the commented code in a function that is at least as meaningful as the comment it replaces.
I always try to update them if I can, or at the very least add a note to the effect that they might be wrong. It's a worthwhile investment of a small amount of time.
The other thing I always do is add any relevant bug numbers, and what effect those edits had - that's always useful to see further down the line.
If the comment is necessary, I'll update it, otherwise I'll attempt to change the code to the point where I can just outright delete the comment and let the code document itself.
When i find useless GhostDoc-generated comments, i sometimes just delete them:
What's the purpose of these comments?
/// <summary>
/// Saves the form properties.
/// </summary>
/// <param name="form">The form.</param>
/// <param name="propertyNames">The property names.</param>
void SaveFormProperties(Form form, string[] propertyNames);
As a fairly fresh programmer, I don't really work much on older code as much as my own, but I try to go back every once in a while to ensure my own comments are mildly close to the truth. It makes no sense to leave comments that don't properly describe the function of the code.
That said if you're in a hurry it makes no sense to waste too much time updating comments. Adding one to the effect of "This is out of date" solves the problem of retaining navigation without leaving it ambiguous as to how accurate it is.
If your documentation is being generated from the comments (I highly recommend this anyway) then yes, I keep the comments in meticulous synch with the code.
I immediately fix the comments if I see a problem, and probably note down what it would take to improve the code.
If I then get hit by a bus, the code is all the better for my quick, pointed attention.
Then, if I have time, I'll sort the code itself out (fixing it usually requires time consuming regression testing). If not, I'll leave it for another day, but at least I'll know what the problem is right away when I do have time to come back to it.
Comments are oftten really useful for telling any future maintainers or programmers either what the code is doing or why it is doing it that way.
If you change the code without updating the comments, at best it's going to be confusing, if not downright misleading.
I strive to follow the Boy Scout Rule and leave the code cleaner than I found it. I will look to update the comment or refactor the code to obviate the need for the comment. I find that it is generally better not to have a comment at all than it is to have an incorrect comment.
I would fix the comments.
Why not fix any problem you can? If you understand the code you're working on, the comments should be the easiest fixes of all. Obviously if you've taken the trouble to delve into it the code should all be left better than you found it.
I would even posit that in groups where multiple people will be touching the code the comments could be considered just as important as the code itself. Without it the communication of ideas is broken down.
In practice I probably don't comment as well as I should. It's hard to admit that you or someone else will probably be digging around in your "masterpiece" later.
I would fix the comments. I saw some answers said they would rewrite the code if the comments were out of date. It seems absurd to me to rewrite working code just because the comments are bad. That kind behavior might even get you fired if your work is important enough.
I always fix the comments - primarily because I am usually the one who works on a piece of code. It may be an OCD like thing for me, but I just like code that I am working on to look nice - good variable names, formatting (not an issue now with modern IDE's), and comments.
I don't believe code can be "refactored to the point it is self-documenting". It can be refactored to the point where only comments for functions, procedures, member variables, classes etc. are needed, because each function call is only 1-5 lines each. Coming from a Lisp background I like to program through decomposition - much simpler, testable, and easier to prove correct.
If the project is under version control (and it should be nowadays, but you never know) and there's a huge hunk of out-of-date comments, I delete the hunk and leave a new comment to the effect that I've deleted a hunk of old comments that no longer seemed illuminating, and I submit with a note that I've deleted out-of-date comments.
Eventually, I'll remove the comment that mentions the deletion, or replace it with comments that apply to the new code.
However, here's the downside to changing old, supposedly meaningless comments in a system that's being maintained by a group of programmers:
The comments aren't acting as comments anymore! They are acting as landmarks for programmers familiar with the code. They're landmark comments as opposed to explanatory comments.
Programmers may actually be searching on keywords in landmark comments to navigate the file.
If you remove landmark comments, or even change them, you may drastically slow programmers who are using them to navigate the file. You're messing with the mental maps of people who have a long relationship with the code, and you'll do more damage than good. The brain's a funny thing. It may be much easier to remember a word or phrase in a funky comment than the name of a method.
It seems to me that if the comments are dreadfully out-of-date with the code, you should learn why. It seems incredibly presumptive to assume that the other programmers don't care about the code. Maybe they do, maybe they don't. If you're taking over the files from a guy who left, and you have clear ownership, dig in! If you're the new guy amongst a bunch of guys who've been working on the code for 20 years, and there's other evidence that they do care about the code, maybe you're missing something.
This is similar to the question of reformatting--changing spacing, altering where the opening braces go, etc. And much depends on ownership. Are you going to be in a file 20 times as much as the guy next to you? Or 1/20th as often? If it's the latter, do you really want to disorient him?
So make sure that's not what you're doing, or tomorrow you may hear someone yelling, "Where the hell is that function?"

What's the least useful comment you've ever seen? [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.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
We all know that commenting our code is an important part of coding style for making our code understandable to the next person who comes along, or even ourselves in 6 months or so.
However, sometimes a comment just doesn't cut the mustard. I'm not talking about obvious jokes or vented frustraton, I'm talking about comments that appear to be making an attempt at explanation, but do it so poorly they might as well not be there. Comments that are too short, are too cryptic, or are just plain wrong.
As a cautonary tale, could you share something you've seen that was really just that bad, and if it's not obvious, show the code it was referring to and point out what's wrong with it? What should have gone in there instead?
See also:
When NOT to comment your code
How do you like your comments? (Best Practices)
What is the best comment in source code you have ever encountered?
Just the typical Comp Sci 101 type comments:
$i = 0; //set i to 0
$i++; //use sneaky trick to add 1 to i!
if ($i==$j) { // I made sure to use == rather than = here to avoid a bug
That sort of thing.
Unfilled javadoc boilerplate comments are particularly useless. They consume a lot of screen real estate without contributing anything useful. And the worst part is that where one such comment appears, hundreds of others are surely lurking behind.
/**
* Method declaration
*
*
* #param table
* #param row
*
* #throws SQLException
*/
void addTransactionDelete(Table table, Object row[]) throws SQLException {
I've found myself writing this little gem before:
//#TODO: Rewrite this, it sucks. Seriously.
Usually it's a good sign that I've reached the end of my coding session for the night.
// remember to comment code
wtf? :D
Something like this:
// This method takes two integer values and adds them together via the built-in
// .NET functionality. It would be possible to code the arithmetic function
// by hand, but since .NET provides it, that would be a waste of time
private int Add(int i, int j) // i is the first value, j is the second value
{
// add the numbers together using the .NET "+" operator
int z = i + j;
// return the value to the calling function
// return z;
// this code was updated to simplify the return statement, eliminating the need
// for a separate variable.
// this statement performs the add functionality using the + operator on the two
// parameter values, and then returns the result to the calling function
return i + j;
}
And so on.
Every comment that just repeats what the code says is useless. Comments should not tell me what the code does. If I don't know the programming language well enough, to understand what's going on by just reading the code, I should not be reading that code at all. Comments like
// Increase i by one
i++;
are completely useless. I see that i is increased by one, that is what the code says, I don't need a comment for that! Comments should be used to explain why something is done (in case it is far from being obvious) or why something is done that way and not any other way (so I can understand certain design decisions another programmer made that are by far not obvious at once). Further comments are useful to explain tricky code, where it is absolutely not possible to determine what's going on by having a quick look at the code (e.g. there are tricky algorithms to count the number of bits set in a number; if you don't know what this code does, you have no chance of guessing what goes on there).
Thread.Sleep(1000); // this will fix .NET's crappy threading implementation
I once worked on a project with a strange C compiler. It gave an error on a valid piece of code unless a comment was inserted between two statements. So I changed the comment to:
// Do not remove this comment else compilation will fail.
And it worked great.
I don't believe it. I came into this question after it had 22 answers, and no one pointed out the least possibly useful type of comment:
comments that are wrong.
It's bad enough that people write superfluous comments that get in the way of understanding code, but when someone writes a detailed comment explaining how something works, and it's either wrong in the first place, or wrong after the code was changed without changing the comment (much more likely scenario), that is definitely the worst kind of comment.
GhostDoc comes up with some pretty interesting ones on its own.
/// <summary>
/// Toes the foo.
/// </summary>
/// <returns></returns>
public Foo ToFoo()
// secret sauce
// Don't know why we have to do this
try
{
...some code...
}
catch
{
// Just don't crash, it wasn't that important anyway.
}
*sigh
Came across a file once. Thousands of lines of code, most of it quite horrendous. Badly named variables, tricky conditionals on loops and one comment buried in the middle of the file.
/* Hmmm. A bit tricky. */
//' OOOO oooo that smell!! Can't you smell that smell!??!??!!!!11!??/!!!!!1!!!!!!1
If Not Me.CurrentMenuItem.Parent Is Nothing Then
For Each childMenuItem As MenuItem In aMenuItem.Children
do something
Next
If Not Me.CurrentMenuItem.Parent.Parent Is Nothing Then
//'item is at least a grand child
For Each childMenuItem As MenuItem In aMenuItem.Children
For Each grandchildMenuItem As MenuItem In childMenuItem.Children
do something
Next
Next
If Not Me.CurrentMenuItem.Parent.Parent.Parent Is Nothing Then
//'item is at least a grand grand child
For Each childMenuItem As MenuItem In aMenuItem.Children
For Each grandchildMenuItem As MenuItem In childMenuItem.Children
For Each grandgrandchildMenuItem As MenuItem In grandchildMenuItem.Children
do something
Next
Next
Next
End If
End If
End If
Default comments inserted by IDEs.
The last project I worked on which used WebSphere Application Developer had plenty of maintenance developers and contractors who didn't seem to be bothered by the hundreds, if not thousands of Java classes which contained the likes of this:
/**
* #author SomeUserWhoShouldKnowBetter
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
There was always that split-second between thinking you'd actually found a well-commented source file and realising that, yup, it's another default comment, which forced you to use SWEAR_WORD_OF_CHOICE.
I saw this comment yesterday in a C# app:
//TODO: Remove this comment.
My favorite all-time comment.
/* our second do loop */
do {
Whoever wrote it - you know who you are.
a very large database engine project in C many many years ago - thousands of lines of code with short and misspelled variable names, and no comments... until way deep in nested if-conditions several thousands of lines into the module the following comment appeared:
//if you get here then you really f**ked
by that time, i think we knew that already!
In a huge VB5 application
dim J
J = 0 'magic
J = J 'more magic
for J=1 to 100
...do stuff...
The reference is obviously THIS ... and yes, the application without those two lines fails at runtime with an unknown error code. We still don't know why.
Taken from one of my blog posts:
In the process of cleaning up some of the source code for one of the projects I manage, I came across the following comments:
/*
MAB 08-05-2004: Who wrote this routine? When did they do it? Who should
I call if I have questions about it? It's worth it to have a good header
here. It should helps to set context, it should identify the author
(hero or culprit!), including contact information, so that anyone who has
questions can call or email. It's useful to have the date noted, and a
brief statement of intention. On the other hand, this isn't meant to be
busy work; it's meant to make maintenance easier--so don't go overboard.
One other good reason to put your name on it: take credit! This is your
craft
*/
and then a little further down:
#include "xxxMsg.h" // xxx messages
/*
MAB 08-05-2004: With respect to the comment above, I gathered that
from the filename. I think I need either more or less here. For one
thing, xxxMsg.h is automatically generated from the .mc file. That might
be interesting information. Another thing is that xxxMsg.h should NOT be
added to source control, because it's auto-generated. Alternatively,
don't bother with a comment at all.
*/
and then yet again:
/*
MAB 08-05-2004: Defining a keyword?? This seems problemmatic [sic],
in principle if not in practice. Is this a common idiom?
*/
AHHHRRRGGHHH Just found this in some ancient code, bet the guy thought he was pretty funny
private
//PRIVATE means PRIVATE so no comments for you
function LoadIt(IntID: Integer): Integer;
The worst comment is one that gives a wrong explanation of what the code does.
That is worse than no comment at all.
I've seen this kind of thing in code with way too many comments (that shouldn't be there because the code is clear enough on its own), and it happens mostly when the code is updated (refactored, modified, etc.) but the comments aren't updated along with it.
A good rule of thumb is: only write comments to explain why code is doing something, not what it does.
Would definitely have to be comments that stand in place of error handling.
if(some_condition){
do_stuff();
}
else{
//An error occurred!
}
I just found this one, written on the line before a commented-out line of code:
//This causes a crash for some reason. I know the real reason but it doesn't fit on this line.
100k LOC application that was ported from vb6 to vb.net. It looks as though a previous developer had put a comment header on one method and then copied and pasted the exact comment onto every method he wrote from then on. Hundreds of methods and each one incorrectly commented...
When i first saw it i laughed... 6 months later the joke is wearing thin.
This is an absolutely real example from a database trigger:
/******************************************************************************
NAME: (repeat the trigger name)
PURPOSE: To perform work as each row is inserted or updated.
REVISIONS:
Ver Date Author Description
--------- ---------- --------------- ------------------------------------
1.0 27.6.2000 1. Created this trigger.
PARAMETERS:
INPUT:
OUTPUT:
RETURNED VALUE:
CALLED BY:
CALLS:
EXAMPLE USE:
ASSUMPTIONS:
LIMITATIONS:
ALGORITHM:
NOTES:
******************************************************************************/
/** function header comments required to pass checkstyle */
The two most unhelpful comments I've ever seen...
try
{
...
}
catch
{
// TODO: something catchy
}
I posted this one at the Daily WTF also, so I'll trim it to just the comment...
// TODO: The following if block should be reduced to one return statememt:
// return Regex.IsMatch(strTest, NAME_CHARS);
if (!Regex.IsMatch(strTest, NAME_CHARS))
return false;
else
return true;
One I've never found very helpful:
<!--- Lasciate ogne speranza, voi ch'intrate --->

Resources