Adding other DOM elements to a view in Backbone - dom

I'm in a situation where I'm manipulating sub elements of a view and not sure if I'm properly handling them. This specific example is I have a carousel that has left and right buttons that disappear on certain events (for example, if you get to the end of the carousel in one direction). In order to manipulate these objects I've been doing something like this, but it doesn't feel right:
$(this.el).find('.right-paddle').hide();
Or in some cases during instantiation call something like this:
this.rightPaddle = $(this.el).find('.right-paddle');
so that I can do something like this later:
this.rightPaddle.hide();
Is this bad form?

In order to manipulate these objects I've been doing something like
this, but it doesn't feel right:
Why not? What's wrong about it? Is it too much to write? Views are bound to 'parent' DOM elements and more often than not they have some children or elements within it that must be found in order to manipulate them. It's perfectly valid
Or in some cases during instantiation call something like this:
If you refer it quite often it's a good habit to cache the instance since DOM traversal is expensive. In your case it seems to be perfectly valid.
Is this bad form?
No. There is more than one way to do it. Do what makes your application more maintainable and readable and not necessarily strive for premature optimizations or hard-to-read code, unless it's very performance critical (should still be easy to read though :)
Does this help alleviate your concern?

Related

How do I remove an inherited object from a child without altering the parent

(note: names were changed to protect the guilty)
So, let's say I am doing modifications in VisualCruft 8 (long since discontinued by the vendor), and applying those modifications to ERP software from "Company A" (long since bought out by "Company S", who then discontinued the software a few years later due to VisualCruft being discontinued itself).
One of the modifications I frequently need to do is to add, change, or remove fields to a form. This is the bread-and-butter of most ERP software and shows up several times a year. The layout of our ERP package, we'll call it "HotPockets Version 3", divides the forms into "class libraries" that in turn are just buckets to hold the form objects proper; and of course, there are "control" objects embedded inside the "forms".
With each install of HotPockets 3 you get the system version of the form, and a child version in a separate class library that is just a re-class of the parent, so that the forms, controls, business logic, etc. are all present in the child. The intent, as stated by the original ("Company A") vendor, is to allow you to make changes to the child that override the parent, while allowing said vendor to release patches/changes/whatever into the parent. In theory this looks great. In practice, there are issues. Specifically, how does one remove or change a control on a form, when the control itself is defined in the parent, and the parent is not to be changed? The intent is to replace a control with a different control that has different behavior, although in some cases I have also had to remove a control altogether. So, you could also ask this as "How do I remove an inherited object from a child without altering the parent"?
There are some known solutions to this, but I am asking the question because I want to see if there is a better answer than what I will provide. To avoid duplicate answers, I will list the currently known solutions, but keep in mind, I am looking for what is not listed here.
Improper Solution 1
While I am not supposed to modify the parent, I do have access to the parent code. I can simply note all of the properties and methods for the control in question, delete the control from the parent, then go back into the child and re-implement all of the properties and methods. For drastic changes, such as replacing a single text box with a grid of something, this is doable. It is, however, completely "against the rules" and the VAR that provides support for this product kinda frowns on it (note: the VAR is NOT "Company A" or "Company S"). Do keep in mind that not only is the original vendor defunct but the product and the language are defunct as well.
Improper Solution 2
"Hide" the component on the parent form, then (if incorporating a new component) add the new changes to the child. This sounds great in practice, until you realize that all of the old code hooks into the parent, which is now...invisible. Which means renaming the parent's version of the component, and going through all of the "port the properties and methods" listed in Solution 1. In which case...why am I doing this again?
Improper Solution 3
For those instances where I want a control to go away, I can hide the control in the child by setting the visibility property. This does not remove or alter any existing code, and everything continues to function. However, the control and the database field bound to it are now "tied up" and unavailable unless I look at something like Solution 1 or Solution 2, because any attempt to mess with the control will possibly result in side effects during calls, and/or replacing data underneath the control programmatically makes it impossible for the user to observe what is happening. And this only addresses the control visually going away - it does not address replacing it.
Extremely Improper Solution 4
Damn the torpedos, delete the control from the parent, full steam ahead!
Obviously, this is a very bad decision...
You'll note that all of the solutions involve touching the parent, something that I am not supposed to do - which brings us full circle to the question.
Other Solutions Not Available
Replace HotPockets Version 3 with something else. This is not in the realm of my decision making.
Rewrite whatever I need for HotPockets Version 3 with (insert favorite pet language here). While I would not mind doing this - I do have my own pet languages like most folks - it's not a possibility because VisualCruft pretty much works with just itself. Trust me on this, it's about 10x more effort than it is worth to write an extension in VisualWidget 3.14159 or HeyDoYouSmellCoffee or even ILikeSnakes, figure out some kind of cross-language calling, integrate it, test it, get IT management to sign off on it, get the VAR to also sign off on it, than it is to just stick with the native tools in VisualCruft.
Have the VAR do it. Don't take it the wrong way, the VAR does a good job providing ongoing support and has provided lots of useful modifications. But there are cost-factors that play into this, and it's more cost-effective if the changes were made by me, rather than the VAR. This has nothing to do with them at all.
First let me say that from my point of view it is not so easy to quickly get what your question is.
With each install of HotPockets 3 you get the system version of the
form, and a child version in a separate class library that is just a
re-class of the parent, so that the forms, controls, business logic,
etc. are all present in the child. The intent, as stated by the
original ("Company A") vendor, is to allow you to make changes to the
child that override the parent, while allowing said vendor to release
patches/changes/whatever into the parent. In theory this looks great.
In practice, there are issues.
>In theory this looks great.
No it does not! Inheritance is the strongest relationship two entities (aka classes) can have. That is why it has been proposed by Gamma in 1994 and it is widely agreed that:
Favor delegation over inheritance!
Delegation is far more decoupled then inheritance. In your case e.g. you could create a key-value store for your customers custom form fields.
However from your question it is not clear to me if such a change is within your field of responsibility.
But this is the source of all the "evil" you are describing.
Further on my impression is within your question you mix up a parent-child-relationship within the class structure at design time and a parent-child-structure of a tree-like class-composition of the objects-structure at run time.
Think of it this way: Your classes are File and Folder, and Folder can contain Files... By this you can create arbitrary tree like structures at runtime. This is called the "Composition Design Pattern". If you are not aware of it you will get lots of information on the net.
Finally within your bounty you are proposing
that this is a limit of the OOP paradigm
.
IMHO it is not - it is a serious flaw in the design due to a clear misuse of inheritance.
So back to your question:
How do I remove an inherited object from a child without altering the parent?
At design time or at run time? (You can not alter a inheritance at run time)
Remove the inheritance completely at design time.
The question "How do I remove an inherited member of a child" in and of itself is incorrect. I actually know what you mean in this context. However, your wording for the question is basically asking something impossible. If you are creating a parent-child, is-a, inheritance chain between two types, you are assuming one is a more specialized form of the other. If you ever think that human may someday evolve so much that it would have nothing in common with "animals", you should never inherit "human" from "animals". Let's remember that inheritance is as coupled as it gets between classes.
I think Martin is correct in stating that this is not really a limitation in the OOP paradigm. Surely "Hot Pocket" designers knew what type of modifications their users should be able to do when they used inheritance for the child classes. They definitely wanted to "allow" certain changes and "disallow" certain other changes. For example they wanted you to be able to change the behaviour of a control but not be able to remove it.
Having said that, if you do not agree and believe that adding or removing controls is definitely something "Hot Pocket" designers had in mind, then they should have also provided you with a means of doing just that.
All in all, there are three possible scenarios:
-A "Hot Pocket" designers actually give you a way to achieving
this(which obviously wouldn't have led to your question here).
-B "Hot Pocket" designers messed up. They didn't have a clue a user may need
to delete a control in a child class.
-C "Hot Pocket" designers knew
what they were doing. They don't want you to be able to add or delete a control
to the child forms.
In Case A), we already have a solution. Just as the "Hot Pocket" people.
In case B), as it is their fault they can't frown on you having to change the parent because otherwise you have no "good" choice.
In case C), you either submit to the limitation or as in your case, you are forced to change the parent although that is not supported. Of course, that would cause frowns and come with its caveats because you are going against the design.
This is getting longer that I intended, I finish with maybe one more solution that you have not added.
Given the fact that you have no way of "deleting" an inherited member, maybe a better approach than changing the parent would be actually adding a new parent for your special case. If you need to remove a control, in a new copy of the parent make your changes and have the child inherit from the new parent class. By doing this you are actually extending the framework rather than changing it. Maybe this would cause less frowns?

HTML xpath tree dump? using Ruby Watir

Help! In carefully stepping through irb to control a browser (Firefox and Chrome) using the Watir library, it seems the xpath addresses are too shifty to rely on. Eg. one moment, the xpath for one's balance seems consistent, so I use that address in my script. Sometimes it works, but too often crashing with "element not found" although every time I manually step through, the webpage data is there (firebug inspect to confirm).
Yes, using Ajax-reliant sites, but not that changing....bank websites that pretty much remain the same across visits.
So question....is there some way watir-webdriver can simply give me a long, verbose dump of everything it sees in the DOM at the moment, in the form of an xpath tree? Would help me troubleshoot.
The big answer is to not use xpath, but instead use watir as the UI is intended to be used.
When it comes to a means to specify elements in browser automation, by and large Xpath is evil, it is SLOW, the code it creates is often (as you are finding) very very brittle, and it's nearly impossible to read and make sense of. Use it only as a means of last resort when nothing else will work.
If you are using a Watir API (as with Watir or Watir-webdriver) then you want to identify the element based on it's own attributes, such as class, name, id, text, etc If that doesn't work, then identify based on the closest container that wraps the element which has a way to find it uniquely. If that doesn't work identify by a sibling or sub-element and use the .parent method as a way to walk 'up' the dom to the 'parent container element.
To the point of being brittle and difficult readability, compare the following taken from the comments and consider the code using element_by_xpath on this:
/html/body/form/div[6]/div/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/p/table[‌​2]/tbody/tr/td[2]/p/table/tbody/tr[3]/td[2]
and then compare to this (where the entire code is shorter than just the xpath alone)
browser.cell(:text => "Total Funds Avail. for Trading").parent.cell(:index => 1).text
or to be a bit less brittle replace index by some attribute of the cell who's text you want
browser.cell(:text => "Total Funds Avail. for Trading").parent.cell(:class => "balanceSnapShotCellRight").text
The xpath example is very difficult to make any sense of, no idea what element you are after or why the code might be selecting that element. And since there are so many index values, any change to the page design or just extra rows in the table above the one you want will break that code.
The second is much easier to make sense of, I can tell just by reading it what the script is trying to find on the page, and how it is locating it. Extra rows in the table, or other changes to page layout will not break the code. (with the exception of re-arranging the columns in the table, and even that could be avoided if I was to make use of class or some other characteristic of the target cell (as did an example in the comments below)
For that matter, if the use of the class is unique to that element on the page then
browser.cell(:class => 'balanceSnapShotCellRight').text
Would work just fine as long as there is only one cell with that class in the table.
Now to be fair I know there are ways to use xpath more elegantly to do something similar to what we are doing in the Watir code above, but while this is true, it's still not as easy to read and work with, and is not how most people commonly (mis)use xpath to select objects, especially if they have used recorders that create brittle cryptic xpath code similar to the sample above)
The answers to this SO question describe the three basic approaches to identifying elements in Watir. Each answer covers an approach, which one you would use depends on what works best in a given situation.
If you are finding a challenge on a given page, start a question here about it and include a sample of the HTML before/after/around the element you are trying to work with, and the folks here can generally point you the way.
If you've not done so, work through some of the tutorials in the Watir wiki, notice how seldom xpath is used.
Lastly, you mention Firewatir. Don't use Firewatir, it's out of date and no longer being developed and will not work with any recent version of FF. Instead use Watir-Webdriver to driver Firefox or Chrome (or IE).
You just need to output the "innerXml" (I don't know Watir) of the node selected by this XPath expression:
/
Update:
In case that by "dump" you mean something different, such as a set of the XPath expressions each selecting a node, then have a look at the answer of this question:
https://stackoverflow.com/a/4747858/36305

Is it best to use if statements or switch statements in cellForRowAtIndexPath? - UITableView

When setting up cells in UITableView, is it best to use if statements or switch statements as a general practice?
I'm talking specifically about cellForRowAtIndexPath here and other UITableView methods, not as a general programming question.
Because I am so old that I worry about performance, I would probably do it this way ............ but wait: modern compilers, quite simply, "take over" and optimize/compile how they want.
So in my opinion, it truly and profoundly makes no difference, for that reason:
You have no clue what modern compilers are doing, so it's pointless worrying about writing it one way or the other way.
I tend to prefer "if" rather than complicated modern switches, purely as a stylistic matter and to wave the flag for old-fashionedness.
You could possibly say: try to "return" from the routine as early as possible on each path so it doesn't pointlessly traverse stuff at the end. I lose sleep over things like this, it's a great question.
One point .. in iOS programming there is tremendous value in doing things the same way others do them. I hate that fact, but, it's true! So in the specific question at hand, if you can gleam an Apple idiom -- do it that way, for sure.
It makes no difference whatsoever.
You should ensure that you try and reuse a "compatible" cell via the dequeueReusableCellWithIdentifier method on the provided UITableView instance, but other than that you just need to return a valid UITableViewCell - how you get to that end-point is completely irrelevant.
That said, as a bit of advice I'd try and keep things as "light" as possible to ensure that the user interface remains responsive. (i.e.: Don't try and interrogate complex data structures within this method - do all that beforehand and simply grab the results from the relevant data source within the cellForRowAtIndexPath.)
There are probably dozens good reasons for each method, plus a lot of other solutions. Here's my opinion on that:
If you set up a fixed number of elements (enumerated), name them with an enum type and use switch statements. It is very structured, easily readable, and with some compiler settings you'll get a warning if you miss a case.
In case of open/unlimited/not-so-well-structured choices, use if. Sometimes, more than one cell comes from the same code block, sometimes a helper object is used, etc.
As with every code: Keep it simple, readable and easy to maintain. if or switch is not a performance-critical decision here.

Design - When to create new functions?

This is a general design question not relating to any language. I'm a bit torn between going for minimum code or optimum organization.
I'll use my current project as an example. I have a bunch of tabs on a form that perform different functions. Lets say Tab 1 reads in a file with a specific layout, tab 2 exports a file to a specific location, etc. The problem I'm running into now is that I need these tabs to do something slightly different based on the contents of a variable. If it contains a 1 I may need to use Layout A and perform some extra concatenation, if it contains a 2 I may need to use Layout B and do no concatenation but add two integer fields, etc. There could be 10+ codes that I will be looking at.
Is it more preferable to create an individual path for each code early on, or attempt to create a single path that branches out only when absolutely required.
Creating an individual path for each code would allow my code to be extremely easy to follow at a glance, which in turn will help me out later on down the road when debugging or making changes. The downside to this is that I will increase the amount of code written by calling some of the same functions in multiple places (for example, steps 3, 5, and 9 for every single code may be exactly the same.
Creating a single path that would branch out only when required will be a bit messier and more difficult to follow at a glance, but I would create less code by placing conditionals only at steps that are unique.
I realize that this may be a case-by-case decision, but in general, if you were handed a previously built program to work on, which would you prefer?
Edit: I've drawn some simple images to help express it. Codes 1/2/3 are the variables and the lines under them represent the paths they would take. All of these steps need to be performed in a linear chronological fashion, so there would be a function to essentially just call other functions in the proper order.
Different Paths
Single Path
Creating a single path that would
branch out only when required will be
a bit messier and more difficult to
follow at a glance, but I would create
less code by placing conditionals only
at steps that are unique.
Im not buying this statement. There is a level of finesse when deciding when to write new functions. Functions should be as simple and reusable as possible (but no simpler). The correct answer is almost never 'one big file that does a lot of branching'.
Less LOC (lines of code) should not be the goal. Readability and maintainability should be the goal. When you create functions, the names should be self documenting. If you have a large block of code, it is good to do something like
function doSomethingComplicated() {
stepOne();
stepTwo();
// and so on
}
where the function names are self documenting. Not only will the code be more readable, you will make it easier to unit test each segment of the code in isolation.
For the case where you will have a lot of methods that call the same exact methods, you can use good OO design and design patterns to minimize the number of functions that do the same thing. This is in reference to your statement "The downside to this is that I will increase the amount of code written by calling some of the same functions in multiple places (for example, steps 3, 5, and 9 for every single code may be exactly the same."
The biggest danger in starting with one big block of code is that it will never actually get refactored into smaller units. Just start down the right path to begin with....
EDIT --
for your picture, I would create a base-class with all of the common methods that are used. The base class would be abstract, with an abstract method. Subclasses would implement the abstract method and use the common functions they need. Of course, replace 'abstract' with whatever your language of choice provides.
You should always err on the side of generalization, with the only exception being early prototyping (where throughput of generating working stuff is majorly impacted by designing correct abstractions/generalizations). having said that, you should NEVER leave that mess of non-generalized cloned branches past the early prototype stage, as it leads to messy hard to maintain code (if you are doing almost the same thing 3 different times, and need to change that thing, you're almost sure to forget to change 1 out of 3).
Again it's hard to specifically answer such an open ended question, but I believe you don't have to sacrifice one for the other.
OOP techniques solves this issue by allowing you to encapsulate the reusable portions of your code and generate child classes to handle object specific behaviors.
Personally I think you might (if possible by your API) create inherited forms, create them on fly on master form (with tabs), pass agruments and embed in tab container.
When to inherit form and when to decide to use arguments (code) to show/hide/add/remove functionality is up to you, yet master form should contain only decisions and argument passing and embeddable forms just plain functionality - this way you can separate organisation from implementation.

What's better: Writing functions, or writing methods? What costs more performance?

Currently I am making some decisions for my first objective-c API. Nothing big, just a little help for myself to get things done faster in the future.
After reading a few hours about different patterns like making categories, singletons, and so on, I came accross something that I like because it seems easy to maintain for me. I'm making a set of useful functions, that can be useful everywhere.
So what I did is:
1) I created two new files (.h, .m), and gave the "class" a name: SLUtilsMath, SLUtilsGraphics, SLUtilsSound, and so on. I think of that as kind of "namespace", so all those things will always be called SLUtils******. I added all of them into a Group SL, which contains a subgroup SLUtils.
2) Then I just put my functions signatures in the .h file, and the implementations of the functions in the .m file. And guess what: It works!! I'm happy with it, and it's easy to use. The only nasty thing about it is, that I have to include the appropriate header every time I need it. But that's okay, since that's normal. I could include it in the header prefix pch file, though.
But then, I went to toilet and a ghost came out there, saying: "Hey! Isn't it better to make real methods, instead of functions? Shouldn't you make class methods, so that you have to call a method rather than a function? Isn't that much cooler and doesn't it have a better performance?" Well, for readability I prefer the functions. On the other hand they don't have this kind of "named parameters" like methods, a.f.a.i.k..
So what would you prefer in that case?
Of course I dont want to allocate an object before using a useful method or function. That would be harrying.
Maybe the toilet ghost was right. There IS a cooler way. Well, for me, personally, this is great:
MYNAMESPACECoolMath.h
#import <Foundation/Foundation.h>
#interface MYNAMESPACECoolMath : NSObject {
}
+ (float)randomizeValue:(float)value byPercent:(float)percent;
+ (float)calculateHorizontalGravity:(CGPoint)p1 andPoint:(CGPoint)p2;
// and some more
#end
Then in code, I would just import that MYNAMESPACECoolMath.h and just call:
CGFloat myValue = [MYNAMESPACECoolMath randomizeValue:10.0f byPercent:5.0f];
with no nasty instantiation, initialization, allocation, what ever. For me that pattern looks like a static method in java, which is pretty nice and easy to use.
The advantage over a function, is, as far as I noticed, the better readability in code. When looking at a CGRectMake(10.0f, 42.5f, 44.2f, 99.11f) you'll may have to look up what those parameters stand for, if you're not so familiar with it. But when you have a method call with "named" parameters, then you see immediately what the parameter is.
I think I missed the point what makes a big difference to a singleton class when it comes to simple useful methods / functions that can be needed everywhere. Making special kind of random values don't belong to anything, it's global. Like grass. Like trees. Like air. Everyone needs it.
Performance-wise, a static method in a static class compile to almost the same thing as a function.
Any real performance hits you'd incur would be in object instantiation, which you said you'd want to avoid, so that should not be an issue.
As far as preference or readability, there is a trend to use static methods more than necessary because people are viewing Obj-C is an "OO-only" language, like Java or C#. In that paradigm, (almost) everything must belong to a class, so class methods are the norm. In fact, they may even call them functions. The two terms are interchangeable there. However, this is purely convention. Convention may even be too strong of a word. There is absolutely nothing wrong with using functions in their place and it is probably more appropriate if there are no class members (even static ones) that are needed to assist in the processing of those methods/functions.
The problem with your approach is the "util" nature of it. Almost anything with the word "util" it in suggests that you have created a dumping ground for things you don't know where to fit into your object model. That probably means that your object model is not in alignment with your problem space.
Rather than working out how to package up utility functions, you should be thinking about what model objects these functions should be acting upon and then put them on those classes (creating the classes if needed).
To Josh's point, while there is nothing wrong with functions in ObjC, it is a very strongly object-oriented language, based directly on the grand-daddy of object-oriented languages, Smalltalk. You should not abandon the OOP patterns lightly; they are the heart of Cocoa.
I create private helper functions all the time, and I create public convenience functions for some objects (NSLocalizedString() is a good example of this). But if you're creating public utility functions that aren't front-ends to methods, you should be rethinking your patterns. And the first warning sign is the desire to put the word "util" in a file name.
EDIT
Based on the particular methods you added to your question, what you should be looking at are Categories. For instance, +randomizeValue:byPercent: is a perfectly good NSNumber category:
// NSNumber+SLExtensions.h
- (double)randomizeByPercent:(CGFloat)percent;
+ (double)randomDoubleNear:(CGFloat)percent byPercent:(double)number;
+ (NSNumber *)randomNumberNear:(CGFloat)percent byPercent:(double)number;
// Some other file that wants to use this
#import "NSNumber+SLExtensions.h"
randomDouble = [aNumber randomizeByPercent:5.0];
randomDouble = [NSNumber randomDoubleNear:5.0 byPercent:7.0];
If you get a lot of these, then you may want to split them up into categories like NSNumber+Random. Doing it with Categories makes it transparently part of the existing object model, though, rather than creating classes whose only purpose is to work on other objects.
You can use a singleton instance instead if you want to avoid instantiating a bunch of utility objects.
There's nothing wrong with using plain C functions, though. Just know that you won't be able to pass them around using #selector for things like performSelectorOnMainThread.
When it comes to performance of methods vs. functions, Mike Ash has some great numbers in his post "Performance Comparisons of Common Operations". Objective-C message send operations are extremely fast, so much so that you'd have to have a really tight computational loop to even see the difference. I think that using functions vs. methods in your approach will come down to the stylistic design issues that others have described.
Optimise the system, not the function calls.
Implement what is easiest to understand and then when the whole system works, profile it and speed up what's slow. I doubt very much that the objective-c runtime overhead of a static class is going to matter one bit to your whole app.