Products

Products
Viewing By Category : OOP/Patterns / Main
December 4, 2009

Starter bare-bones AS camera class

Just starting on this class and thought I'd post a good starting point for learning.

package classes{
   import flash.media.*;
   import flash.net.*;
   
   import mx.core.UIComponent;

   public class Chatcam extends UIComponent{
      private var netconnection:NetConnection;
      private var nsPlayer:NetStream;
      private var video:Video;
      private var vidPlayer:Video;
      private var camera:Camera;
      private var microphone:Microphone;
      private var uic:UIComponent;
      
      public function Chatcam(nc:NetConnection,publishedCam:String=""){
         netconnection = nc;
      }
      public function detectCamera():Boolean{
         return Camera.getCamera();
      }
      public function publishCamera(cameraName:String,publishType:String="live"):void {
         camera = Camera.getCamera();
         camera.setQuality(0,100);
         camera.setKeyFrameInterval(15);
         camera.setMode(240,180,15,false);
         //cam.setMotionLevel(35,3000);        microphone = Microphone.getMicrophone();
       microphone.setUseEchoSuppression(true);
       microphone.setSilenceLevel(0,2000);
       var ns:NetStream = new NetStream(netconnection);
       ns.attachCamera(camera);
       ns.attachAudio(microphone);
       ns.publish(cameraName,publishType);
      }
      public function displayPublishingVideo():void {
         video = new Video();
       video.attachCamera(camera);
       addChild(video);
      }
      public function displayPlaybackVideo(cameraName:String):void {
         nsPlayer = new NetStream(netconnection);
       nsPlayer.play(cameraName);
       vidPlayer = new Video();
       vidPlayer.attachNetStream(nsPlayer);
       addChild(vidPlayer);
      }
      
   }
}

Example usage:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()" xmlns:media="flash.media.*">
   
   <mx:Script>
      <![CDATA[
         import mx.core.UIComponent;
         import flash.net.*;
         import flash.media.*;
         import classes.Chatcam;
         
         public var nc:NetConnection = new NetConnection();   
         public var ns:NetStream;
         public var rtmpPath:String = "rtmp://localhost/devCRW";
         public var cc:Chatcam;
         
         public function init():void {
            nc.client = new Object();
            nc.addEventListener(NetStatusEvent.NET_STATUS,ncStatusHandler);
            nc.connect(rtmpPath);
         }
         public function ncStatusHandler(e:NetStatusEvent):void {
            switch (e.info.code)
            {
               case "NetConnection.Connect.Success":
                  stat("Connected");
                  cc = new Chatcam(nc);
                  if(cc.detectCamera()){
                     stat("displayPublishingVideo");
                     cc.publishCamera("myCamera");
                     cc.displayPlaybackVideo("myCamera");
                     addChild(cc);
                  }else{
                     stat("Problem with camera.");
                  }
             break;
             case "NetConnection.Connect.Rejected":
                  stat("Rejected!");
             break;
             case "NetConnection.Connect.Failed":
                  
               break;
               case "NetConnection.Connect.Closed":
                  
               break;
               default:
                  
            }
         }
         public function stat(msg:String):void {
            status.htmlText += msg + "<br>";
         }
      ]]>
   </mx:Script>
   
   <mx:Text x="198" y="10" text="Status:" id="status"/>
   
</mx:Application>

September 8, 2009

MVC - Structured View Layer Development

Is it me or is the view layer in the MVC pattern being ignored or at least understated? Working on my most recent project I stepped up my MVC and OO emphasis during development and noticed that we, web developers, aren't doing anything structured as far as view development goes, at least I can't find anything searching the net. We conform the underlying complexities, like the model layer, into formal design and standards (OO for instance) but don't hold the view to the same or comparable expectations. We make sure that the view layer is seperated from business logic at the layer level but when it all comes together at the view level we fail to make anything formal out of that. I'm attempting here to formalize and structure my view layer borrowing my experience in MVC and OO methodologies. It may be done already somewhere else but I can't find it and I need it, so here it is, right or wrong it's a jumping point.

If you look at the view layer in an object oriented approach and formalize the views as pseudo classes you may be able to deduce where I'm headed. For example, views or pages have properties and methods that can be used to create UML class diagrams during the design phase. In addition you can carry these through the implimentation phase and realize the seperation within your page view code. The view is more than just the HTML layout of tables and div tags where content sits, it's a layer, not just a file. We already seperate CSS, Javascript, and other like concerns but not the inner page code structure, and I'm not just refering to physical speration. It's just assumed that by the time you get to the actual view programming that you'll be able to just do it, no planning or formal organization required.

I'm not talking about architecting the view in an object oriented manner, that's just too much. I believe the view can benefit from organized structuring of page concern seperation and we want to use this technique in planning and in coding. To demonstrate this I'm going to create a simple and quick fictitous site with a few views in an MVC structured application.

Here's a draft of a UML class diagram showing how I might plan my views and view layers on paper. Notice that my page views are now represented as classes with properties and methods. Keep in mind that UML diagrams and planning is an iterative process and will change quite frequently but, we must start somewhere.

Notice first the hirarchy from Application through layout and to individual nested pages. These are connected to show how each page view inherits it's elements from upper view layers. I'm not advocating that this is the right way to diagram or think of it, just my way for now.

The application node is the top node here and has properties and methods you should recognize. This sits in the view layer in an inner application layer. An application layer in my mind can also include other nodes like UDF and configuration files.

Inner view layers:

    Container layer - the top most containing layer surrounding all other inner view layers in an application. All other view layers inherit from the application layer.     HTML layer - Defines containers and layout structures in which to place content.     Content layer - Contains the content of page views and any externally viewable content media they may include.

My site has a default_layout page that displays content layers, and as usual frequently repeated elements across multiple views are located here too; ie the header, footer, and navigation. Notice it's properties here. The value for jsDir will be the physical path that will be used in the source attribute of a script tag or anywhere else we may find a need for it. For example:

<$cript type="text/javascript" src="<cfoutput>#jsDir#</cfoutput>ddlevelsmenu.js">

The homeLink property has a value equal to the actual href tag, the link back to the home page. And in this property we can edit the link as needed from one easy to find location in this view. The default layout view here also composes of the CSS, the JavaScripts, and anything else you would need to include somehow. These inclusions, not expanded here, could be psuedo classes with properties and methods as well.

Moving down the view layer we have the content layer view nodes which is the meat of our site to the user. They inherit properties and methods of the layout layer as well as defining their own. In this diagram we can see what the content views inherit, most useful when trying to remember what your content view pages are capable of before any code goes into it.

Starting with the home content view I created a userListLink property containing the href link to the userList content view. That property can be used anywhere in the home content view.

Next, the userList content view will output a list of users that we retrieved from the control layer after being queried and cast to an array in the model layer. So the users array will be a property of array type. Notice I don't type simple properties such as strings. There are two other properties, listPerPage (how many to paginate per page), and userDetailLink which is the href for the link to the userDetail content view. Here we also have methods for this view.

The userCountTotal() function placed here for example is a simple function the view can call from anywhere to get a value. And no matter where or how many times this function is placed it can be altered from one location.

Let's take for example the next function, wTitle(), to see how this works in practical code. The purpose of this function is to encapsulate a piece of content and seperate it from the views tables and divs, making the design much easy to read, move around, and format. The best way to show this is probably a before and after example.

Before using view layering:

<cfsilent>
<cfscript>
users = event.getValue('users');
listPerPage = getController().getSetting('listPerPage');
userDetailLink = "<a href=''>View Details</a>";
catagory = event.getValue('catagory');
</cfscript>
</cfsilent>
<cfoutput>
<div class="centerPadding">
<span class="largetext" style="text-transform:capitalize;"><strong>#catagory#</strong> readings</span>
<br />
<span class="smalltext">Always only $2.99 per minute!</span>
<br /><br />
<table width="100%" cellspacing="0" cellpadding="3" border="0">
<tr>
...

After using view layering:

<cfsilent>
<cfscript>
users = event.getValue('users');
listPerPage = getController().getSetting('listPerPage');
userDetailLink = "<a href=''>View Details</a>";
catagory = event.getValue('catagory');
function wTitle(){
writeoutput("
<span class=""largetext"" style=""text-transform:capitalize;""><strong>#catagory#</strong> users</span><br />
<span class=""smalltext"">List of all users from the #catagory# catagory.</span><br /><br />
"
);
}
</cfscript>
</cfsilent>
<cfoutput>
<div class="centerPadding">
#wTitle()#
<table width="100%" cellspacing="0" cellpadding="3" border="0">
<tr>
...

Notice how we took out a huge chunk of content making the layout much easier to conceptualize and edit. This also lends to seperating concerns for content programmers and design layout artist. In making these separate I usually rule out any chunks that are either small or contain more layout code such as td repeaters. All I want to be left with below the content functions is basically a skeleton of table and div tags.

The userDetail content layer view has two properties. User is a user object passed in from the controller and the userListLink is an href string used to link back to the userList node. There are two functions used to output content, wUserImage() is the code to output the image for the user. The wUserDescription() function is called to format and place the description block how and where you would like. Think of these functions as an easy way for a layout artist to place content within his work that the content programmer has already developed. These functions could also take in arguments if the programmer feels witty. Then a view layer API can be documented and used by the design artist.

What I'm doing inside the views to seperate content and layout design isn't as important as the benifits realized from the view layer model in the design phase. The other models such as those in the model layer can now be associated with nodes in the view layer. Eventually I want to produce a document where every element that is a part of the process can be modeled to and from each other and between layers in a world view type map.

It's all pretty simple and not well thought out for now, the result of about a day of thinking. I do plan to expand it if I can't find anything comparable out there. For now it seems to help me a lot with organizing and visualizing page views. Esspecially when you consider that I'm already thinking this way for the other layers.

September 6, 2009

Generating and using site documentation, cfcdoc

I'm completely embarrased to admit it but, I didn't know until yesterday that not only can I create my own web site's API documentation automatically but how useful it can be. Sure beats glazing over my directories and trying to remember where everything is and what it does.

My latest project has got me dealing heavily with application API's and it's important to read and understand how to apply the API to development, especially when using OO framework architectures. Reading and using the API's for my Coldbox framework (here) I got to thinking that having this documentation for my own site would be very useful and very cool. It literally puts OO into perspective, for me anyways since I like the API's, and helps me to visualize how my classes (components) are organized, if anything is out of place, and if I can optimize anything.

At first I was using the CFIDE component utilities (localhost:8300/cfide/componentutils/) like the explorer and the componentdoc. But it would always list packages from everywhere, including the CFIDE and WEB-INF folders. And then it would list the pakages from the mappings as well as the folder it pointed to. So I edited the code to exclude folders, thinking that there's got to be a better way, and there was. Looking back at Coldbox's API I notice it's from an open source RIAforge thing, get it here: CFCDoc. It's so easy, just extract the zip to your root under a folder, like '/api/' and go there. There's information about what to do next because all the packages you'll see at first are the one's in the /api/ folder you placed it in, not very useful. But basically you add or delete folders to include through a simple config xml file and that's it, your exploring your very own API.

Depending on the length you want to go to in your documentation you can go really wild with component and function attributes like hint and displayname, probably more too. Using these extra attributes I'm sure you thought were useless and time consuming you can add enough information to make the API a virtual users manual. At the very least you can use the API to match up with your UML class models. I'm thinking also that planning a site's structure could be done API style instead of UML style, maybe even faster. You can think of what classes you need and how to package them for your application doing API visualization. In other words, what should your API look like and is it all packaged logically from an API documentation perspective?

September 4, 2009

Do ColdFusion programmers need to be object oriented gurus?

Before I begin let me just say that although I'm not a certified Java developer, which would make me an automatic OO guru, I do develop Flash and Flex applications using AS3, which is an OO language. Yes, when it comes to OO I know what I'm talking about and have studied and used patterns for a few years. I'm not a pure OOist but who is and who really needs to be?

I'm so tired of chasing that alusive brass CFOOP ring of knowledge, trying to become a an object oriented guru with the deepest depths of understanding. I'm already there and so are you, seriously, its not as far as you thought. And I'm talking to CF verterans that use cfc's as objects, and patterns (whether they know it or not) to solve problems. You may not be using pure OO but you are OOing purely enough. For those reading this that know nothing of OO please stop and go read a few beginner OO basic articles and then come back.

There's only about a 10% difference between OO in an "OO language" like Java, and OO in the ColdFusion scripting language. And that 10% difference is used about 1% of the time. So you can't create interfaces (technically you can with underlying Java), big deal, and completely irrelevant too. Creating "I" classes is simply rewriting the original class in a more impressive way and there's only a 1% chance you'll actually need the real thing. Interfaces for the most part are for compile time error checking and CF is not a compile time language, not at our level it isn't.

Let's see, what else is there that I'll probably never have a need for, or can do in some other CF way. Overloading, constructors, overriding, and multiple inheritance, and that's about it. As for the constructor, we use an init function on object instantiation as a consturctor for now but, CF 9 will have implicit constructors. Overriding can be accomplished in CF using composition. BTW, implicit getters and setters will be available in CF 9 also.

Other than the lack of multiple inheritence (which isn't a requirement to be considered a true 'OO capable' language, like Java and Smalltalk), if Adobe added overloading capabilities then CFers could be concidered OOers too. And just like a Java coder can produce crappy non-OO code so can a CF coder create crappy non-OO CF code.

Here's the thing though, follow me. ColdFusion is a RAD tool that can be structured in an OO way following proper OO techniques. ColdFusion is OO when and if you need it to be but we certainly don't want it to be totally and purely OO, ever, EVER. If you make it pure OO say goodbye to rapid development and say goodbye to the market it is ment for. OO was devised to help solve complexed problems in very large systems, something that CF can but doesn't do much of. Those complexed and very large systems are far and few between, the market is in the average system, which don't need OO much any ways.

All that being said, if you've got the jest of OO terminology down and have enough understanding of the underlying principles that you can apply it safely, stop worrying about it and get back to work. The only way you can become a better OOer is to practise it. And as for those Java guys laughing at us CFers when OO is mentioned, they're just trying to chase away the new kids in their OO sandbox, spoiled sports don't want to share the spotlight. Honestly I don't consider anyone an OO programmer based on the language he uses, it's how he uses the language that defines a programmers OO understanding. And if people will stop refering to CF as it was prior to the MX version we'de stop having this debate in the first place. Once apon a time, ColdFusion couldn't be architectured with OO principles, but now it can. The end.

September 3, 2009

Free web-based UML diagram tool

This is really cool, a simple web-based UML diagram tool you can use on the fly without being at the web site it is served from. Without even going to, or even signing up with, Yuml.me I can create a UML model typing in what I want into the address bar, then just copy and paste that into my blog or anywhere else I can use the URL to share and display it.

Since you asked, of course I'll show you an example right here. I will create a user gateway class [UsersGateway|+DNS;+User|+getUserBean();+getAllUsers()]:

You simply use an img tag with the source http://yuml.me/diagram/class/, the "scruffy" option makes the output look less formal.

September 1, 2009

ColdFusion OO, MVC, and Frameworks

Saying that you don't need OO or MVC to build a ColdFusion application or web site is like saying you don't need blueprints and building code standards to build a skyscraper or a house. Granted, blueprints are overkill for a birdhouse but, OO and frameworks are overkill for a one product web site too. You should know when all the overhead is needed and when it is just going to be overhead. To me, it seems like this is the real problem when it comes to utilizing more sophisticated coding techniques rather than just plain old coding.

In all actuality most of the complaints, confusion, and questions come from weekend programmers who don't need to concern him or herself with such extremes. But they make a mountain out of a mole hill (or an application out of a web site in this case) because they want to hunt with the big dogs or think they need to or should, or they just feel inadaquite if they don't. I don't blame them, I did too, and I wouldn't be where I am today if I didn't venture into the world of software engineering. But all that stuff didn't add anything positive to my low level projects at the time except taking more time to do it, so be careful.

Here's the honest to goodness truth about using all that fancy stuff. Any site or application created using any of that overhead can be created just as well with straight down proceedural coding. The end user, and sometimes even the client wouldn't know the difference between one and the other unless you pointed it out and showed them. In all frankness, only about a quarter of web sites need to bother with anything more than simple code, yet three quarters of web developers think they should.

My advice to web development noobs is to stick with the one thing you need to get the job done unless and until that job requires more than what that language can do efficiantly on it's own. Who knows, you might develop a simple site that makes you a millionaire without ever knowing what OO is. But if that site begins to grow unwieldly with errors coming from nowhere, it's time to turn to more sophisticated techniques. It's time to use MVC, properly incorporate a framework, and maybe even learn some OO terms and patterns. Then the question "when should I use the fancy stuff" becomes "how, what, and where do I use these".

Personally I use an MVC architecture on anything over a dozen pages, frameworks on anything with more than a few applications, and OOD/P on anything considered an enterprise. If you must, its important that you be able to do these things with professional precision to get something out of it. Your not going to get any ROI using a framework on any application if you've never used one before, so don't practice where your paycheck comes from.

MVC is a term used to describe a seperation of concerns, the business model, the user interface, and the central controller. It's not a product and there is no one right way to do it. As long as the thinking is done in one place, the displaying done in another, and neither knows about the other except through a controller, your using proper MVC architecture. Pretty simple right? If you only have a few events, or page views, then yes it is.

But, try rolling your own MVC on a medium size project and you'll grow to appreciate frameworks rather quickly. A framework is basically an MVC, structured and expanded for medium to large scale projects. That is, it supports agile development by not only insuring best practise MVC organization, but also offers commonly used programming logic in prebuilt API's. It's the foundation or base that will be the strongest part of your structured application if used properly.

Object oriented programming basically helps when you can objectify parts of a program into seperate entities and only if there will be a lot of them. In addition it's only benificial if those parts will be very active during the life of the application. By active I don't mean the use of the application, I'm talking about moving things around, enhancing them and depricating them, or allowing others to use them. If an object is going to be static in that regard, then it shouldn't be factored into the decision to use OO.

In summary, something important to think about while you hone your enterprise software engineering skills is that, as you get more comfortable with this sophisticated stuff you'll become more able to use those bigger skill sets on smaller scales. I for one find myself able to flesh out an OO UML model for a simple site in a matter of minutes. An OO noob might waste valuable precious days over the same thought with a negative ROI. So yes, you can use this stuff on smaller scales effectively when it becomes second nature and you don't have to think about how but what. As for all those naysayers that are swimming against the industry tide and trying to convince you that it's all uneccessary, they couldn't be more wrong. The storm is coming, mark my word. Maybe not in our life time but soon, developing web sites will be out of the range for the average Joe and the strongest of proceedural coders will be lost without keeping up. Stop pouting and start evolving, accept it, embrace it, love it.

June 20, 2009

Consume object or object property

Here it is in a nutshell. I have a controller cfc in my framework that directs execution instructions to the business model cfc's. But I'm wandering if I should pass whole objects, like a user object, and get values as needed from it's methods within the business model? Or should I just pass the object's properties to the business model classes as needed?

Another way to put it is this(model/securityService.cfc):

instance.securityGateway.login(User.getUsername(),User.getUserpassword());

or

instance.securityGateway.login(User);

The business model gateway in this example would be something like(model/data/gateway/securityGateway.cfc):

<cffunction name="login"..>
<cfargument name="username"../>
<cfargument name="password"../>
...
</cffunction>

or

<cffunction name="login"..>
<cfargument name="User" type="model.data.gateway.User"../>
..
</cffunction>

Maybe because I'm not a seasoned OO veteran but I'm looking at this and trying to figure out the best course and can't decide which one to take. From the service cfc do I pass in the user object or it's properties (username & password)?

For now I'm passing the object's properties if the gateway method only requires data and doesn't need to access any of the objects other methods like setters. If the gateway method here needed to use the object's methods instead of just it's properties, then I'd pass the entire object. So what do you think is best practice?

May 18, 2009

Inherit or not?

Quick question, quiz, poll. Which one of the following would be the best solution in most cases?
userTransactionsQuery = User.getBankTransactions()

or

userTransactionsQuery = Bank.getUserTransactions(User.getAcctID())

I'm thinking that it's wrong to give a bank method to a user object. Maybe I've had too miny *hic* Red Bulls.

June 4, 2008

Coldbox beanfactory populatebean method

I have to say I love this automatic bean population thing going around. Model-Glue does it also but since I mostly use Coldbox, that's what I'm showing here.

WTF, you may ask? Well, you know how when you submit a form to edit a user account for example, and then you have to pass all those form elements to your user bean object's getters and setters one by one. userObj.setUsername(form.username), userObj.setUserpassword(form.password) and so on.. well you can forget about ever doing this again.

HOW!?!? By using the Coldbox beanfactory populatebean method. You can play with form elements first if you need to, then simply call the populate method passing in the current userbean, and then Coldbox will match form elements to the bean's getter and do the heaving lifting for you returning an updated bean ready for saving.

2 simple lines, get bean and populate bean. Then do whatever else you prefer from there to save it wherever etc..

<cffunction name="doEditAccount" access="public" returntype="void" output="false">
      <cfargument name="Event" type="coldbox.system.beans.requestContext">
      <!--- Logic --->
      <cfscript>
         userBean = getPlugin("sessionstorage").getVar("User");
         getPlugin("beanFactory").populateBean(userBean);
         getUsersService().saveUser(userBean);
         getPlugin("sessionstorage").setVar("User",userBean);
      </cfscript>
      <!--- Display --->
      <cfset setNextEvent("myaccount.general.dspAccountHome")>
   </cffunction>

The most important thing to remember is that your actual bean cfc object must use an init method with setters. And the form element names should be the same as the bean names.

A bean's init:

<cffunction name="init" returntype="User">
<cfargument name="username">
<cfset setUsername(arguments.username)>
</cffunction>

So that:

<input type="text" name="username">
Matches:
<cffunction name="setUsername">
<cfargument name="var">
<cfset variables.instance.username = arguments.var>
</cffunction>

Hope that helps. :)

May 21, 2008

UML Sequence Diagrams made easy

Web based sequence diagram tool. Enter your logic and out pops the image for your documentation.

Web Sequence Diagrams

More Entries


Copyright © 2005-2006 Clint Willard. All rights reserved.
Aura skin for Clint Willard's BlogCFC inspired by Brooks Bilson's Bolg.
All trademarks property of their owners.