Flex <fx:Script /> best practices? - apache-flex

Just wanted to ask about what to do when using as includes (ie <fx:Script source="includes/my_as3_file.as" />.
The problem is that in all of my files I'm using class-only modifiers, such as private, public protected, and FB sometimes protests regarding these. A friend told me that what he does is changing the file extension to .ias, but in this way, he loses code highlighting, content-assist and enabling breakpoints.
Thanks.

I like to use something called a ViewHelper (posted a link)
http://www.kensodev.com/2010/08/19/keep-your-mxml-files-neat-with-view-helpers/
This way, the MXML file is pure MXML at all times, and the view helper is coupled and has a reference to the view meaning you can do something like this in your view helper
myView.dataGrid.visible = false;
And of course many more things.
Even when I use RobotLegs's mediators, I still use the view helper for all actions that concern the view such as animations, hiding and shoeing things, state changing and more. I use the mediators only to mediate with the RobotLegs framework (re-dispatch events) and listen to the eventDispatcher.

Personally, I'm not a fan of using includes. As you've mentioned, it tends to obfuscate what's actually going on within a view, and makes it difficult to quickly scan a file and grok it's behaviour.
One of the best practices I've always followed is to reduce the amount of code within an <fx: Script /> block to almost none.
If you are using an include file, this suggests that your views are very script-heavy, which can lead to poor code reuse, and difficulty in writing testable code.
Instead, consider using the Presentation Model pattern where the logic is moved out to a separate class. Alternatively, there's also the Mediator pattern, however personally I've found this leads to more heavily coupled code - though that's likely down to my crappy execution, than a failing of the pattern.

Use code behind!
or
[mxml_file]AS.as for Actionscript file name.
ex MXML: MyView.mxml and the as file MyViewAS.as
then it will look like <fx:Script source="MyViewAS.as" />

Renaming the .as file to .ias, in my opinion, is one of the worst solutions one can come up with ( it's just horrible ). I also kinda disagree with Marty, because in Flex 4, the architecture is different from Flex 3 ( although Spark is built on top of MX - if we were talking about Flex 3, then I'd agree with what Marty said ). In Flex 4, the Skin is now considered to be the "View" and class making use of the view is the "Controller"... meaning that things are now much better separated than they were in Flex 3, where a components kinda played the role of both the View and Controller ( http://www.slideshare.net/saurabhnarula/flex-4-skinning-2634949 ).
Coming back to the original problem: It's true that Flash Builder is not perfect, but if you know that you don't have any errors in your code and it keeps on throwing some weird stuff at you, then simply try closing it and starting it again ( Clean your project afterward ). Whenever I set an .as file as the source for my MXML component, I like to have the file next to the MXML class ( ex: MyMXMLComponent.mxml and MyMXMLComponentAS.as, both being at the same level - source="MyMXMLComponentAS.AS" ). This 99% of the time works fine, but really rarely, I might have also received some weird errors from Flash Builder ( which usually got solved by closing it and cleaning the project afterward - on a couple of occasions, there was actually an error in my code which seemed to totally confuse/crash the compiler and make it throw some really senseless error messages, so definitely try to make sure that your code is correct ).
Personally, I'd suggest that instead of using .as files, you try to use the "code behind" approach ( search on Google / Adobe for more info on this - I wanted to post a link, but since I'm a new user, I'm limited to 1 link / post... hah ). Using code behind, you will surely never run into the problems you might run into with .as file and you will surely never have problems with code hinting. In case you have never used code behind before, then it might feel "strange" at the beginning, but you'll get used to it and you'll surely not want to write code "the old way" ever again.

Related

Calling methods from one ASP.Net web form from another web form

A site I'm working on has two different pages, and each one is attempting to do the same thing. One of the pages, though still in use, has not been updated and so the code is no longer doing everything it is meant to do.
Rather than continue this wet solution and copy the missing code, I would like to make use of the code that has been updated. Ideally I would copy the function into a helper class or make a base class to provide this functionality, but the one function calls many private functions, and each of the private function mixes business logic with the presentation logic.
I have no documentation and a short time scale, so to do this would not be feasible. So my question is, what are the disadvantages of calling the function on page1.aspx from page2.aspx? It is a shared function so I'm hoping it will be OK but advice would be appreciated.
Sounds like a bloody mess to me. You are not to descript but without really seeing whats going on it is hard to say. If this code is touching dom elements and hitting page cycle events it will probably be a pain. I would say.. take the actual business logic and put it in another class outside of the page and then reference the business logic that way but for dom elements directly webforms is already over complicated I would try staying away from making it worse. Perhaps you can pull these dom elements into a user control and reuse it on both pages? Either way sounds like you have plenty of fun a head of you :)
It would be best if you showed some of the code, but I have to say that if the two methods are Shared, then you're probably ok.
However, such Shared code doesn't belong on either page. It belongs in some other class that can be accessed by both pages.

Is there any reason to put code in the code behind rather than in the aspx file?

Any time I need to write code I almost always put it in the code behind file. For some reason this has always seemed like the "right" way to write code.
Based on most of the examples I see online, a lot of other people choose to write code this way too, but it seems like putting your code in the aspx file allows you to do all the same stuff as well as offering a few advantages.
Top of the list being:
Easier to make changes since no
recompile.
You have access to all code if
you can't find the project in source
control (this recently happened to
me).
Is there any benefit to having code in a code behind file? Is there any disadvantage to putting code in your aspx file?
Separating the code from the markup results in much cleaner structure, especially for non-trivial pages.
This is one of the major benefits to ASP.Net over ASP Classic.
Easier to make changes since no
recompile.
Depends in what context, you can upload normal ASPX + ASPX.CS to the server and it will compile it for you on IIS.
I use this for my personal web site, I hate having to 'publish' the web site and then upload the files, sometimes on the server I need to make quick edits in Notepad, hence this approach is perfect.
I personally like the setup of keeping them separate.
PS. I use 'Web Sites' not 'Web Projects' which I believe has to be compiled before uploading to the server.
Maintainability. It allows the HTML part to be edited independently of the code, by and large.
When you have a very small project it is just a bad practice. They just tell you it's wrong, but it feels perfectly right.
You will hit the wall when you start working on big projects and especially when you will need to maintain them.
When your project gets big -the GUI part(the form) becomes smaller: one component here, this color there... not too complicated.
On the other hand, the logic part becomes a real pain... if I use a function in 20 pages will I change each replication of the function in each form? If they are almost identical, yet a bit different... how will I implement the solution?
OOP offers many design patterns so that your code will be as clean and efficient as possible... but you have to work with objects rather than a form.
A form is an object, yet it doesn't meet the OOP design patterns rules. And those rules are there to make your life easier.
I once had to maintain a huge system... and every change required changing many forms and testing many forms. After rebuilding the system it became a SMALL system and easy to maintain. It is easy to just build a form from scratch ignoring the entire system... but it's really hard to maintain this form.
Never think of the year you build the project, think of the 20 years you are going to maintain it.
Good luck
Asaf
Stumbled upon this link now searching for the real advantages of putting code in cb files, and to confirm SLaks' answer, see this link for those who still wondered. Really thought processing and speed could've been an advantage as well, but alas...

Is there a benefit to embedding ActionScript in MXML when developing Flex apps?

I always thought that separating the UI from the logic is the way to go like the use of class files in Flash CS3/CS4 or MVC in web frameworks but recently there are plenty of examples and posts using ActionScript embedded in MXML.
Is there a benefit to doing this? Am I missing something.
Don't get too caught up on the "rules" of MVC and the like. Ultimately you want your code to be setup in such a way that it will minimize the impact/churn of future changes. It's less important "where" the code is and more important what and how it's interacting with other code. I see far to many people take a simple component like a login screen and make models, view, controllers, view helpers, service facades, etc. It ends up being like 75+ lines of code for something that should have been about 20. It also spreads the code amoungst a bunch of files rather than one. So in the end, you've made maintenace hard, not easy. I'm not arguing for ignoring design patterns, but rather being practical about it. Hope this helps.
In my experience, there's not much of a difference whether you write a component in ActionScript + MXML, or solely in Actionscript. Personally, if I'm writing something that's layout heavy with a little logic, I'll do it in MXML. Conversely, if it's code heavy and has little layout, I'll write it in Actionscript.
I suppose you could always separate the view and model, but then you have more files to maintain. Sometimes it makes sense, but I have yet to see a compelling reason to do it all the time.
I go by a few simple rules:
If a bit of code is just a single short line and it isn't something you can reuse elsewhere -- mere glue code -- put it directly in the MXML tag.
If it's too long to fit comfortably in the MXML tag or it is something multiple components in that MXML file can use, put it in a function in a Script tag within the same file, and call the function from the MXML tag(s).
Everything else -- full classes, large functions, things used by multiple MXML files -- goes in a separate .as file. This includes single-LOC methods that are part of a larger class, as opposed to the standalone functions the other rules cover.
I agree with Erich Douglass, to a point. Generally, if I can do the layout with MXML it's just easier to maintain. I mean, who wants to write all that crap in a createChildren override if you don't have to? Besides, the MXML is easier to read.
Whatever you do, though, remember that if you are merely calling a separate script file for an MXML component (Foo.mxml calls Foo.as for its ActionScript) you are losing the code highlighting feature that helps you work between the MXML and the ActionScript. I like to keep them both in the same place, so when I click on an ID in an MXML element I can see at a glance where it's being referenced in the AS.

Is it a bad idea to get rid of the mx: in your Flex code?

I am a newbie at Flex, and I don't like the way you have to write the namespace mx: for every control declaration you write. It makes the code cluttery. I would like to write:
<Panel ...
rather than
<mx:Panel ...
I tried writing
xmlns="http://www.adobe.com/2006/mxml"
for the top level element instead of
xmlns:mx="http://www.adobe.com/2006/mxml"
In the top level declaration. This work to an extent, but broke some existing code. For one, XML data that are defined in the document are all appended with aaa: as the namespace during runtime. I've also noticed other issues in my very small sample program.
Is there a way to do this that works, or is this a lost cause? And some background information on why would be appreciated.
Update: Thanks all for the replies, but I would like to have heard from someone who actually tried this and thought it was important. Although most of you told me it was a bad idea, I was not discouraged. I got a couple of programs working this way smoothly now. And plan to do this in all my flex apps. One trick seemed to work for me although I can't claim it'll work universally. If you need separate namespaces within your doc, take, HTTPService parameters for example, you could create a namespace within that element like so:
<HTTPService id="service" url="http://blah.com"
method="POST" result="gotResult(event)">
<request xmlns:p="*">
<p:param1>p1</p:param1>
<p:param2>p2</p:param2>
</request>
</HTTPService>
Hope this helps someone. I am very happy with how clean my code is now, almost as clean as a normal html file. As for people who think writing mx: throughout your code is clearer and what not, I disagree completely. I think languages that require you to repeat the same character sequence excessively in your code - which you should consider a document - have design flaws. Here's an analogy for you: how would you like it if you were reading an article on Barack Obama, and every single sentence contained the words 'Barack Obama', that would get pretty tiresome wouldn't it?
I think that removing the mx namespace will almost certainly cause you trouble with name conflicts as your project gets larger.
Personally I think the mx namespace makes the code clearer rather than more cluttered, especially if you have component based flex development or a lot of your own controls. Having owned a large flex code base for the last two years I find the mx namespace unobtrusive, especially when you have custom objects embedded inline such as item renderers.
My recommendation (unscientifically asserted) is to put up with it, especially if you are finding issues when removing it. I bet you'll stop noticing it after a while.
You need the mx or some xmls:[SOMETHING HERE] because that's the XML namespace that refers to the definition of the controls. It's like using namespaces in normal code.
Just writing Panel is ambiguous and could possibly conflict with another person's implementation of Panel. So we declare to Flex what namespace Panel belongs to (http://www.adobe.com/2006/mxml) and we alias it with mx.
Microsoft's WPF XAML requires this as well.
Just to be the voice of dissension...
In digging through Ely Greenfields code he does that a lot - I'm not sure if the other developers on the Flex SDK team do that but it does lend some credence to the argument for doing it...right?
I agree with the majority of other answers here, it is best to leave it. Eventually you will be wanting to use other namespaces for things such as custom components and you will need a namespace then for making the distinction. Then you will have some with a namespace and some without.
I would say if for no other reason, you should leave it because someday someone else might have to look at your code and they are probably going to find it much more readable with the mx than without.
The mx: is just a way to tell Flex that the Panel (along with any other component) is a part of the Flex framework, that it, built-in in Flex. This helps Flex to know where to look for the Panel, and will make your compiling process faster.
You can also use local: to access components that YOU created. Example: If I want to add some functionality to my Panel, I would type some code, and save it as a customized Panel, dubbed MyPanel. Them, I can use to tell Flex that MyPanel is my component, and it can find if somewhere in my project. Of course, you can name it anything you want :-)
I agree with you that the mx: looks unsightly at first, especially when you already have a strong background in HTML or XML, but you'll get used to it.
Keep in mind that if you are developing applications that should run on all kinds of platforms including mobile devices it is best to stick with pure spark as far as possible as it is supported on most mobile devices these days. There are cases where one is forced to use an mx control like an Accordion for instance. In this case if you do have time to implement it, it is wise to use tools or the basic controls in spark to create these more advanced or complicated controls to use instead.

Tips for avoiding big ball of mud with ASP.NET WebForms

Although ASP.NET MVC seems to have all the hype these days, WebForms are still quite pervasive. How do you keep your project sane? Let's collect some tips here.
I generally try to stay clear of it... but when i do use WebForms, i follow these precepts:
Keep the resulting HTML clean: Just because you're not hand-coding every <div> doesn't mean the generated code has to become an unreadable nightmare. Avoiding controls that produce ugly code can pay off in reduced debugging time later on, by making problems easier to see.
Minimize external dependencies: You're not being paid to debug other people's code. If you do choose to rely on 3rd-party components then get the source so you don't have to waste unusually large amounts of time fixing their bugs.
Avoid doing too much on one page: If you find yourself implementing complex "modes" for a given page, consider breaking it into multiple, single-mode pages, perhaps using master pages to factor out common aspects.
Avoid postback: This was always a terrible idea, and hasn't gotten any less terrible. The headaches you'll save by not using controls that depend on postback are a nice bonus.
Avoid VIEWSTATE: See comments for #4.
With large projects the best suggestion that I can give you is to follow a common design pattern that all your developers are well trained in and well aware of. If you're dealing with ASP.NET then the best two options for me are:
o Model View Presenter (though this is now Supervisor Controller and Passive View).
This is a solid model pushing seperation between your user interface and business model that all of your developers can follow without too much trouble. The resulting code is far more testable and maintainable. The problem is that it isn't enforced and you are required to write lots of supporting code to implement the model.
o ASP.NET MVC
The problem with this one is that it's in preview. I spoke with Tatham Oddie and be mentioned that it is very stable and usable. I like it, it enforces the seperation of concerns and does so with minimal extra code for the developer.
I think that whatever model you choose, the most important thing is to have a model and to ensure that all of your developers are able to stick to that model.
Create web user controls for anything that will be shown on more than one page that isn't a part of masterpage type content. Example: If your application displays product information on 10 pages, it's best to have a user control that is used on 10 pages rather than cut'n'pasting the display code 10 times.
Put as little business logic in the code behind as possible. The code behind should defer to your business layer to perform the work that isn't directly related to putting things on the page and sending data back and forth from the business layer.
Do not reinvent the wheel. A lot of sloppy codebehinds that I've seen are made up of code that is doing things that the framework already provides.
In general, avoid script blocks in the html.
Do not have one page do too many things. Something I have seen time and time again is a page that say has add and edit modes. That's fine. However if you have many sub modes to add and edit, you are better off having multiple pages for each sub mode with reuse through user controls. You really need to avoid going a bunch of nested IFs to determine what your user is trying to do and then showing the correct things depending on that. Things get out of control quickly if your page has many possible states.
Learn/Grok the page lifecycle and use it to your advantage. Many ugly codebehind pages that I've seen could be cleaner if the coder understood the page lifecycle better.
Start with Master Pages on day #1 - its a pain coming back to retrofit.
Following what Odd said, I am trying out a version of the MVP called Model Presentation which is working well for me so far. I am still getting an understanding of it and adapting it to my own use but it is refreshing from the code I used to write.
Check it out here: Presentation Model
Use version control and a folder structure to prevent too many files from all being in the same folder. There is nothing more painful than waiting for Windows Explorer to load something because there are 1,000+ files in a folder and it has to load all of them when the folder is opened. A convention on naming variables and methods is also good to have upfront if possible so that there isn't this mish-mash of code where different developers all put their unique touches and it painfully shows.
Using design patterns can be helpful in organizing code and having it scale nicely, e.g. a strategy pattern can lead to an easier time when one has to add a new type of product or device that has to be supported. Similar for using some adapter or facade patterns.
Lastly, know what standards your forms are going to uphold: Is it just for IE users or should any of IE, Firefox, or Safari easily load the form and look good?

Resources