custom class property in ExtJS - javascript

What is best practice for naming custom property in ExtJS?
Is it a good idea to precede name with an underline?
Ext.create("Ext.Window,{
height:50,
_custom:"xxx",
_action:"yyyy"
});
another idea is using data_ prefix to mimic html5 custom attribute convention.

I personally don't like anything in a variable name that carries additional syntactic information (Uncle Bob dedicates a whole section to this principle in http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), not to mention the ugly code it produces (e.g. mywindow._custom).
I would just give your variables descriptive names, and then your code will read better and you shouldn't have to worry about collision with Ext properties (if you were worried about).
I like this much better:
Ext.create("Ext.Window,{
height:50,
customNameOfSomething:"xxx",
actionToPerform:"yyyy"
});

Agreed with others, and will add that the underscore in particular is more or less an accepted standard for private variables in most syntaxes (though Ext JS itself does not use it, and keeps private variables marked as private via comments or undocumented by convention). I definitely would choose some other way to name public configs if you insist on choosing some convention, though I agree with others that it's probably not necessary. I would guess that in most real cases, your custom properties are not going to be so generic as to clash (and if they are, you probably chose poor names for whatever you're adding).

You have to remember that you're designing a custom property that might be used by others. This means that it has to be descriptive of its behavior. That's what is most important. Using an _ is very rare and isn't really natural to developers using the code, so it's gotta be user friendly.

I decided to to use _ as a prefix for custom variables. because:
It prevent any collision
Self-documenting
It's users friendly
It would be better if Sencha used a mechanism to prevent the mixing up.

Related

Why check for element/attributes before removing it?

In the Working with the Attribute Node chapter in Learning Javascript - A Hands-On Guide to the Fundamentals of Modern Javascript, the author Tim Wright said on Page 73:
Removing an attribute is as simple as getting one. We just target the element node and use the method removeAttribute() to get it out of there. There are no Javascript exceptions thrown if you try to remove an attribute that doesn't exist, but it's still best practive to use the same hasAttribute() method we mentioned earlier, shown in Listing 4.6.4
Listing 4.6.4 Javascript Used to Remove the Class Value of Our Image
if(document.getElementById("pic").hasAttribute("class")) {
document.getElementById("pic").removeAttribute("class");
}
If there's no exceptions thrown either way, isn't checking whether it exists or not redundant? The same outcome will arise. The argument that the book says is that check for the paramenter before removing it saves the browser parsing through unneccesary code, but if(document.getElementById("pic").hasAttribute("class")) {} is even longer than document.getElementById("pic").removeAttribute("class"); on its own!
Why is this best practice then?
In my opinion your assumption is absolutely right. I think the "advice" in the book is kind of catastrophic (to use a dramatic term). Havent heard about that "best practice" anywhere before. There is absolutely nothing you could achieve by using element.hasAttribute prior to removing / changing an attribute but slow down your code. A browser does not magically have a lookup list for attributes to check for their existence that is not used when it set or get an attribute. It may be best practice - in the authors opinion - for producing readable and understandable code, though.
Furthermore, in my opinion you should never use setAttribute at all! Use setAttribute only then there is no built in standard method for getting or setting a certain attribute. Here class is in question, use
element.className = 'myclass';
instead of
element.setAttribute('class', 'myclass');
Browsers have optimized routines when using such standardized methods. If not being used when you assign or delete an attribute to an element then the browser has to figure out what kind of attribute it is, and may perhaps trigger special operations afterwards - not everytime nessecary.
You can check if a browser supports a specific attribute-method like this
if (typeof window.document.body.className === 'string') {
//className is supported for node elements
}
Most of those attribute-methods acts like getters and setters. You can read and write, and the use of some them are even more effective than other approaches. Example :
element.outerHTML = '';
clean more memory up than
element = null;
It is of course not an attribute to an element, but to show why one should prefer using built in methods targeting a specific part of an element.
There is many, many standard methods as element.className you can use to target a specific standard attribute. They are mostly named as the attribute name in camelcase notation. Use setAttribute only for your own custum attributes, like
element.setAttribute('data-my-custum-attribute', 'hello');
Which is perfectly legal markup according to the HTML5 standard. Or use it as a fallback, if the browser doenst support a certain attribute method. This can be the case for very old browsers. But even IE6 supports className.
I will recommend two books which I think is really valuable for understanding javascript in the depth (not claiming that I do in full, but those books have helped me a lot) :
Javascript - the good parts, by Douglas Crockford
Secrets of the JavaScript Ninja, by John Resig (the guy behind jQuery)
Buy the books! They are gold as reference on your desk.
One thing I have on my mind is that removeAttribute might be a much heavier function call regarding the operations it does, i.e., it modifies the DOM and HTML, and could also affects meta data in the browser.
In comparison, hasAttribute is just a read operation, which is much lighter and won't have impact on meta data. So it's better to check if the element has the attribute or not.
If removeAttribute itself already does hasAttribute checking, then I agree it is pretty much redundant.
its useful for when you are writing a large program or working in a group.... you need to check that you dont remove something that is being used by something/someone else. if there is a more technical answer, hopefully someone else will supply it.

I want to stop using OOP in javascript and use delegation instead

After dabbling with javascript for a while, I became progressively convinced that OOP is not the right way to go, or at least, not extensively. Having two or three levels of inheritance is ok, but working full OOP like one would do in Java seems just not fitting.
The language supports compositing and delegation natively. I want to use just that. However, I am having trouble replicating certain benefits from OOP.
Namely:
How would I check if an object implements a certain behavior? I have thought of the following methods
Check if the object has a particular method. But this would mean standardizing method names and if the project is big, it can quickly become cumbersome, and lead to the java problem (object.hasMethod('emailRegexValidatorSimpleSuperLongNotConflictingMethodName')...It would just move the problem of OOP, not fix it. Furthermore, I could not find info on the performance of looking up if methods exist
Store each composited object in an array and check if the object contains the compositor. Something like: object.hasComposite(compositorClass)...But that's also not really elegant and is once again OOP, just not in the standard way.
Have each object have an "implements" array property, and leave the responsibility to the object to say if it implements a certain behavior, whether it is through composition or natively. Flexible and simple, but requires to remember a number of conventions. It is my preferred method until now, but I am still looking.
How would I initialize an object without repeating all the set-up for composited objects? For example, if I have an "textInput" class that uses a certain number of validators, which have to be initialized with variables, and a class "emailInput" which uses the exact same validators, it is cumbersome to repeat the code. And if the interface of the validators change, the code has to change in every class that uses them. How would I go about setting that easily? The API I am thinking of should be as simple as doing object.compositors('emailValidator','lengthValidator','...')
Is there any performance loss associated with having most of the functions that run in the app go through an apply()? Since I am going to be using delegation extensively, basic objects will most probably have almost no methods. All methods will be provided by the composited objects.
Any good resource? I have read countless posts about OOP vs delegation, and about the benefits of delegation, etc, but I can't find anything that would discuss "javascript delegation done right", in the scope of a large framework.
edit
Further explanations:
I don't have code yet, I have been working on a framework in pure OOP and I am getting stuck and in need of multiple inheritance. Thus, I decided to drop classes totally. So I am now merely at theoretical level and trying to make sense out of this.
"Compositing" might be the wrong word; I am referring to the composite pattern, very useful for tree-like structures. It's true that it is rare to have tree structures on the front end (well, save for the DOM of course), but I am developing for node.js
What I mean by "switching from OOP" is that I am going to part from defining classes, using the "new" operator, and so on; I intend to use anonymous objects and extend them with delegators. Example:
var a = {};
compositor.addDelegates(a,["validator", "accessManager", "databaseObject"]);
So a "class" would be a function with predefined delegators:
function getInputObject(type, validator){
var input = {};
compositor.addDelegates(input,[compositor,renderable("input"+type),"ajaxed"]);
if(validator){input.addDelegate(validator);}
return input;
}
Does that make sense?
1) How would I check if an object implements a certain behavior?
Most people don't bother with testing for method existance like this.
If you want to test for methods in order to branch and do different things if its found or not then you are probably doing something evil (this kind of instanceof is usually a code smell in OO code)
If you are just checking if an object implements an interface for error checking then it is not much better then not testing and letting an exception be thrown if the method is not found. I don't know anyone that routinely does this checking but I am sure someone out there is doing it...
2) How would I initialize an object without repeating all the set-up for composited objects?
If you wrap the inner object construction code in a function or class then I think you can avoid most of the repetition and coupling.
3) Is there any performance loss associated with having most of the functions that run in the app go through an apply()?
In my experience, I prefer to avoid dealing with this unless strictly necessary. this is fiddly, breaks inside callbacks (that I use extensively for iteration and async stuff) and it is very easy to forget to set it correctly. I try to use more traditional approaches to composition. For example:
Having each owned object be completely independent, without needing to look at its siblings or owner. This allows me to just call its methods directly and letting it be its own this.
Giving the owned objects a reference to their owner in the form of a property or as a parameter passed to their methods. This allows the composition units to access the owner without depending on having the this correctly set.
Using mixins, flattening the separate composition units in a single level. This has big name clash issues but allows everyone to see each other and share the same "this". Mixins also decouples the code from changes in the composition structure, since different composition divisions will still flatten to the same mixed object.
4) Any good resources?
I don't know, so tell me if you find one :)

The disadvantages of JavaScript prototype inheritance, what are they?

I recently watched Douglas Crockford's JavaScript presentations, where he raves about JavaScript prototype inheritance as if it is the best thing since sliced white bread. Considering Crockford's reputation, it may very well be.
Can someone please tell me what is the downside of JavaScript prototype inheritance? (compared to class inheritance in C# or Java, for example)
In my experience, a significant disadvantage is that you can't mimic Java's "private" member variables by encapsulating a variable within a closure, but still have it accessible to methods subsequently added to the prototype.
i.e.:
function MyObject() {
var foo = 1;
this.bar = 2;
}
MyObject.prototype.getFoo = function() {
// can't access "foo" here!
}
MyObject.prototype.getBar = function() {
return this.bar; // OK!
}
This confuses OO programmers who are taught to make member variables private.
Things I miss when sub-classing an existing object in Javascript vs. inheriting from a class in C++:
No standard (built-into-the-language) way of writing it that looks the same no matter which developer wrote it.
Writing your code doesn't naturally produce an interface definition the way the class header file does in C++.
There's no standard way to do protected and private member variables or methods. There are some conventions for some things, but again different developers do it differently.
There's no compiler step to tell you when you've made foolish typing mistakes in your definition.
There's no type-safety when you want it.
Don't get me wrong, there are a zillion advantages to the way javascript prototype inheritance works vs C++, but these are some of the places where I find javascript works less smoothly.
4 and 5 are not strictly related to prototype inheritance, but they come into play when you have a significant sized project with many modules, many classes and lots of files and you wish to refactor some classes. In C++, you can change the classes, change as many callers as you can find and then let the compiler find all the remaining references for you that need fixing. If you've added parameters, changed types, changed method names, moved methods,etc... the compiler will show you were you need to fix things.
In Javascript, there is no easy way to discover all possible pieces of code that need to be changed without literally executing every possible code path to see if you've missed something or made some typo. While this is a general disadvantage of javascript, I've found it particularly comes into play when refactoring existing classes in a significant-sized project. I've come near the end of a release cycle in a significant-sized JS project and decided that I should NOT do any refactoring to fix a problem (even though that was the better solution) because the risk of not finding all possible ramifications of that change was much higher in JS than C++.
So, consequently, I find it's riskier to make some types of OO-related changes in a JS project.
I think the main danger is that multiple parties can override one another's prototype methods, leading to unexpected behavior.
This is particularly dangerous because so many programmers get excited about prototype "inheritance" (I'd call it extension) and therefore start using it all over the place, adding methods left and right that may have ambiguous or subjective behavior. Ultimately, if left unchecked, this kind of "prototype method proliferation" can lead to very difficult-to-maintain code.
A popular example would be the trim method. It might be implemented something like this by one party:
String.prototype.trim = function() {
// remove all ' ' characters from left & right
}
Then another party might create a new definition, with a completely different signature, taking an argument which specifies the character to trim. Suddenly all the code that passes nothing to trim has no effect.
Or another party reimplements the method to strip ' ' characters and other forms of white space (e.g., tabs, line breaks). This might go unnoticed for some time but lead to odd behavior down the road.
Depending on the project, these may be considered remote dangers. But they can happen, and from my understanding this is why libraries such as Underscore.js opt to keep all their methods within namespaces rather than add prototype methods.
(Update: Obviously, this is a judgment call. Other libraries--namely, the aptly-named Prototype--do go the prototype route. I'm not trying to say one way is right or wrong, only that this is the argument I've heard against using prototype methods too liberally.)
I miss being able to separate interface from implementation. In languages with an inheritance system that includes concepts like abstract or interface, you could e.g. declare your interface in your domain layer but put the implementation in your infrastructure layer. (Cf. onion architecture.) JavaScript's inheritance system has no way to do something like this.
I'd like to know if my intuitive answer matches up with what the experts think.
What concerns me is that if I have a function in C# (for the sake of discussion) that takes a parameter, any developer who writes code that calls my function immediately knows from the function signature what sort of parameters it takes and what type of value it returns.
With JavaScript "duck-typing", someone could inherit one of my objects and change its member functions and values (Yes, I know that functions are values in JavaScript) in almost any way imaginable so that the object they pass in to my function bears no resemblance to the object I expect my function to be passed.
I feel like there is no good way to make it obvious how a function is supposed to be called.

Should HTML element classes have prefixes depending on their use?

I've been told that it's standard practice to prefix class names on HTML elements with "jq" or "js" so that the designer doesn't conflict with the developer.
I've been around a little and I've never seen this done and personally feel this creates an artificial and unhelpful divide between design and code.
The question is whether this is indeed standard practice, and moreover, I would like references to articles explaining why this is done (what problem does it solve).
I'm the front-end developer at my organisation and as such am responsible for the CSS. I create all the required classes for layout and UI, as well as periodically tidying up unused styles and mark-up.
Our developers never need to add classes for presentation, but they do occasionally add classes for Javascript. In these instances I have asked them to prepend their classes with js-.
This simply helps me identify classes that are not used for presentation, but are still required for functionality. My other class names are all descriptive of the content.
Before we introduced this it was much harder to keep the mark-up tidy (by removing unused classes) as classes could seem redundant (with no references in the stylesheets), but were still used.
I've not come across any documentation saying this is a bad idea. It works for us, so is simply a matter of personal preference.
This sounds like an old fashioned convention for me especially in context with html/javscript/css.
Classes should only be used for layout reasons. If there are classes anyway, defined by a designer, then they can and should be used by developers. Values for pure programm controls should be defined using custom attributes (http://www.javascriptkit.com/dhtmltutors/customattributes.shtml). This practice together with detailed and well-thought-out naming conventions mostly avoid problems.
It also sounds like classes would have to be assigned to elements twice often with this prefix pratice. One more reason to ask how a practice like that can be a good or even standard one.
Edit:
Prefixes can be useful inside plugins for e.g. javascript libraries of course to avoid class conflicts!
It's not a general standard practice, but it may be a standard practive within a specific organisation.
Using prefixes to specify usage of an identifier is called hungarian notation. It's mostly used to specify data types in script languages without strict typing, but the original intention was just to specify any aspect that was crucial to the use of the identifier.
Using prefixes like that can be useful to make sure that classes intended for design doesn't conflict with classes intended for program control. It's however not dependant on who is creating the class, but how the class is used. If a developer creates a script that adds a class to elements to change their appearence, the class is used for design so it should not be prefixed as a program control class name. A class name used for program control would only be used for that, and have no visual style applied to it.
As with most programming practices, it's more important that you pick a standard and stick to it, than picking the standard that is absolutely best.
Not only is it not standard practice (except, presumably, in your organisation), but the W3C advises against it. Class names should be used to further describe the contents of semantic HTML tags, rather than as reference points for design or development.
I would expect well-structure HTML pages to have consistent classes for similar content types which would be perfectly suitable for JavaScript usage.
A designer who cannot write HTML correctly, remembering that the HTML markup is supposed to describe the content not style it, should not be writing HTML IMO.
I've certainly not heard of this as a 'standard' practice. Reading guidelines and articles, I have never seen a prefix infront of a class.
However, it might be handy prefixing a class name if you were going to use that class with jQuery. It will be easier to identify and also it would let others know that it used by a function.

How to indicate public/protected/private members in JSDT outline view?

Javascript Developer Tools (JSDT) for Eclipse provides a nice outline view of Javascript classes, with a little symbol next to them to indicate visibility.
Looking at Preferences->Javascript->Appearance->Members Sort Order, it seems able to indicate whether a method is public, private or protected, but all of my use the "default" marker, a blue triangle.
Does anyone know how it determines which symbol to use? I've tried using Javadoc and JSDoc formatted comments. My private methods start with a leading underscore, and that doesn't give it a hint either.
Not a big deal, just would be nice to know...
Seems that it is just a standard Java-based settings tree (used in many plugins) but without real implementation of JS private members stuff. Oh, we can hope that it is reserved for future use :)
There's no syntactical way of making a method private, public or protected in JavaScript, it strictly relies on where the method is defined (scope).
Marking a methods privacy is something else, there really isn't a standard for that. All I've ever heard of is the "underscore" for private members. So maybe JSDT doesn't implement this.
I believe there is a #private annotation supported by JSDoc. Not sure how standard it is, or whether JSDT supports/enforces it.
Since JSDT is a reimplementation of the JDT interfaces, it may just be reusing JDT's private/protected/public model best it can, without an actual way to mark fields/methods for access control.

Categories

Resources