Blog

  • Code Reuse: Pros and Cons

    Introduction

    Notes of a soldier from the oh-so-bloody front. Depending on the scope of your project, you may have the opportunity for code reuse. The reasons you might want to do so are two-fold.

    First, you reduce duplication of efforts. If you have already created a Hyperlink enabled CellRenderer for your DataGrid once, why do it again?

    Second, you create, or build upon, an ever growing utility code base. While it may not be in the “utils” package per se, you’ll soon end up with re-usable events, common GUI controls and widgets, and yes even utility classes. Whether by merely being in a different folder means the client doesn’t own it is up to you or your sales team.

    Duplication Killed on Sight

    On the current project I’m on, we re-use a LOT. My eagle-eye boss the architect head-shots any duplication he sees. Thus, we the developers have been trained to quickly identify something we create for re-use if possible and either plan accordingly when building it, or go in search of “spare parts” from existing classes throughout the main code-base for re-use. Our main base consists of 3 company names, each containing at least 3 individual “products”. The first question I ask my fellow developers, and they in return, when starting to build something new is, “Has this been done before?” Re-inventing the wheel has no place in a production cycle unless you can clearly point out how the original wheel design was flawed, can be done better, and done so in a reasonable time frame approved by the client.

    This also helps ensure I don’t code something similar to what has already been done. To the client’s point of view, they already paid for a LoginForm… why should they have to pay for a new one when all they want is for it to be green instead of blue?

    “Coworker, the login form’s blue by default, but the mockups I have here are green.”

    “That’s because the View using it sets it to blue; it has a color property that is an inherited style; you can style it yourself, just do color=’#yourcolor’.”

    “Oh… nice!”

    Suddenly, I spend 10 minutes finding the file & including it, setting it’s color, registering for it’s login event, and building a test file to see it in action. This instead of 4 hours doing the same building a green one. Take how much you make per hour, multiply by 4, and then sub-tract what you make in 15 minutes. That difference is what you just saved the client by “asking a question”. I’ve learned the hard way to ask a lot of questions to the point of being annoying and forcing people to repeat themselves.

    The same goes for building more complex things that have to be unique to a point. The most common example which I already alluded to is the CellRenderer. This is a class commonly utilized in Flex & Flash development to customize what is showing in a DataGrid column; each row will render the custom class instead of the default and pass it an item to render. Since every DataGrid on a project is unique, you inevitably end up with a multitude of cellrenderer classes. These classes are, at least for me, notoriously hard to share so you attempt to make them as generic as possible so others can either use them as is, or do the most common thing and extend your base one to customize it to their needs.

    This is an important point. The 30 or so lines of code that are required to setup a cellrenderer are suddenly already written for you, and the other developers on your team. This is a great place where inheritance really works and should be exploited. It doesn’t stop there; some of the cellrenderers created could be used elsewhere as well. The only challenge is how are they designed from a visual standpoint. Styles can handle a lot, but most Designers I have had the pleasure of working with have a knack making something unique, and unique isn’t always re-usable. You can either find a happy compromise with your designer, or respect it’s artistic integrity and recognize the fact that it is truly made specifically for a certain need and shouldn’t be made re-usable.

    Con of a Component Buffet

    The first con to reusing already built components hits the design side hardest. One of the biggest grips people have had with any Flash / Flex component is styling and skinning. While CSS styling has come a long way in Flex 2, there are always those times where the artist (in you or beside you) goes, “It’s just not right…”. Sometimes extending the base component just for styling purposes is the best repose since the base component isn’t muddied with application specific styling routines.

    The second con which can really come to a front in teams is you just don’t like the component. Any developer who isn’t apprehensive about using a component they didn’t write makes me nervous. You trust code you didn’t write? Sometimes you don’t have a choice or recognize the alternatives are unacceptable. We’re all human, and have our coding styles, and even if notation and other rules are enforced on your team, you can still dislike the implementation of something. This should be in the back of your mind when creating code for reuse as well. How will my code be perceived? The base rules such as encapsulation should be followed, but obviously there are other esoteric and styles of implementation that can drastically impact your involvement to ensure others spend very little of theirs getting acclimated to how it works for example.

    Sum Greater Than Its Parts

    For components that are made up of other components via Composition, I’ll ask my fellow developers if the pieces I need are already built. For example, if I’m creating a form, I’ll re-use the extended TextInput’s we have. For the above CellRenderer, if it has to display a Date, I’ll set the labelFunction to utilize the DateUtils class we have which will take a regular Date object and make it look like, “Tue 5/23/2006”. I didn’t have to write the base class of the CellRenderer and I didn’t have to write a class to format dates, I just had to use the class. I’ve been doing the same thing for a long time without really thinking about it. For example, I take for example I can just “use a DataGrid” and “extend it with a CellRenderer”. Macromedia / Adobe spent a lot of time developing one that could be reusable. Naturally, there comes a point where something is coded to business rules or a certain design, and the pragmatic in me knows when to stop trying to overdo it.

    Let’s turn it up a notch, though. What if you’ve built a DataGrid that has custom cellrenders, text fields on the bottom to filter it, and is tied to a specific ValueObject it knows how to display, and display well? Can you re-use that? Absolutely! Just because you don’t right now doesn’t mean you won’t later. You should typically design with the intention to do so, but not so much you don’t ever actually complete anything beyond a pimped out skeleton. Adamantine ingots may have great potential, but are merely blocks of immobile metal until merged with, say, a regenerative Canadian supersoldier’s skeleton. Put what you write to use sooner rather than later.

    This is where code reuse really shines. You’re near mini-application status component which does a lot is now re-used by your team. If the components within it follow normal styling rules and expose their innards to those who wish to extend it, your golden if certain custom styling needs to be applied. What could possibly be a con about this?

    Package Structure

    Package structure. Package structure, for those who don’t know, is how code is organized into folders. Folders are called “packages” because they have code and other packages in them depending on how deeply you nest your code. Code is placed into class files (.as or .mxml) and placed into folders. The typical naming scheme goes deployment type, company, project, and then regular code. This can take the form of com.adobe.utils.DateUtils where you have a com folder that contains an adobe folder which in turn contains a utils folder which contains the DateUtils.as file. You then import the class or “package path” into your code and the class DateUtils, and your code will know what folder to look in from the import statement.

    Some projects do get large enough where you do in fact have more than 1 project folder. Code re-use is typically thought of through View’s of some sort client developers. There is however, no reason you cannot re-use View’s across projects. You just reference the package path. The pro’s are, work effort utilized on a project can be re-used on other projects. Sometimes you can plan for this re-use, and sometimes it’s a pleasant surprise.

    Licenses

    I suppose depending on license that you could use it for different companies as well, but each license has specific rules on how code is used. Creative Commons is pretty simple; just keep the author’s name in the code unless she/he says otherwise. From that point forward, you can modify and re-modify to your heart’s content with no license fee. Others are a lot weirder. Some companies require you supply them source code. Some don’t even know what source code is. Still others own everything you write while in their presence, thus preventing you from using any of your own re-usable stuff. A common tactic I’ve seen is to have your company’s name next to the client’s company name. All common view’s and utility classes are put in yours, and the custom developed work is put in the client’s package path.

    Global Ramifications

    That last point is another important point. Code by it’s very nature residing in your company’s folder has a very special, and important place; it’s created for re-use. On the current project, or projects, it’s re-used in many places. While all uses of it are immediately improved upon once you improve the base component, thus improving the whole project, this can have unforeseen consequences as well.

    For example, you build your own List control to render extremely unique rows that animate instead of simply refreshing. In practice, you see that it is extremely slow, especially when multiple instances of it are used. You go in an re-factor it, finding many places in the code you can speed up. Suddenly, the entire app speeds up where those components are used.

    One of these changes was to expose a method for updating one specific item versus all of them when a piece of data changes. This is accomplished via a new method. That is a bad thing. Suddenly, all the classes that use it now have to update themselves just to access one of the new optimizations.

    Touching a point I brought up earlier, sharing views between projects. The problem with that is if you change a view in one project, you’ve just affect the other one. Code that was seemingly “working” you just broke, and you didn’t know it because you were never compiling, nor even involved in the other project. The important point here is if you are going to identify something as re-usable, make it so, and put it into a global package such as your company’s folder, or another aptly named common folder. Developers who go into the code in those packages know full well the ramifications of what their changes could do for good or ill.

    Tool Shed

    When I got my first apartment, I had 1 screwdriver and 1 small Philips head to my name. Now that I own a house, I have a small utility closet full of tools. I’m sure by the time I’m 80, I’ll need a tool shed to hold them all. The same can be said about your “common” code base. You’ll find over time that it’ll grow into an extremely useful and portable set of code. Remember, you don’t have to write it all yourself, nor does your team. There is a lot of free code on the net that you can test yourself, and then incorporate. This’ll save you from having to create a hammer before you can use said hammer every project; going in, you’ll be equipped to the teeth, and you’ll come out with more ammo than you started with.

    Conclusions

    Reusing code becomes more important that greater the size of the project, and/or in the frequency of projects. Making the most of a developer’s time spent coding is done this way, and allows many others to benefit from that work for months, even years to come. For example, I’ve been using the same preloader in Flash for 3 years, written in ActionScript 1 in Flash 5. I still customize the colors, though, every time.

    With reuse comes great responsibility. If you are designating something as reusable, it can be quite frightening to realize that a lot of others are suddenly depending on this pinnacle piece of code. That is a risk worth taking, and a strength you should prey upon. As long as you recognize the dependencies, and reduce coupling, you’ll start gaining a lot more efficiency from the time you and your team spend coding.

    When I first learned about reuse, I could never get it to work in practice. I either ran out of time and copy and pasted or my original design was perceived to me as being “flawed” even though it worked perfectly fine. I was just being unreasonable. Keep it simple, and you’ll do fine.

    This entry in Word, Flash Paper, and PDF.

  • E4X Doesn’t Suck

    I’ve spoken on past occasions about how un-excited I am about E4X (ECMAScript for XML) with regards to ActionScript 3. Macromedia (now Adobe) made a strong push for XML for 3 player versions. Flash Player 5 had both a built-in XML parser as well as the XMLSocket connection. Flash Player 6 greatly optimized the XML parsing routines and Flash Player 7 did it again.

    Problem was, for application developers dealing with nTier systems (fancy way of saying connecting to various backends), XML wasn’t the most succinct way of communicating, and those messages sometimes were a non-portable, made up language. By then, I was delving into the worlds of WebServices and Remoting. While SOAP implementations utilize XML in the underlying guts of how it works, you as the developer certainly feel like you’re writing regular code talking to code on some other server.

    So, in building a prototype app using Flex 2, Cairngorm 2, and Ruby on Rails, I’m dealing with copious amounts of XML. I feel like I’m in middle-school again. It frightens me to hear myself say that as that same arrogant, holier-than-though attitude of non-big-company technologies is what I used to loathe when talking to Enterprise programmers. I can remember not just me, but countless others accomplishing a lot with just XML strings parsed by hand with very effective outcomes.

    Either way, the thing that is different now is that I have E4X at my disposal. I’m the only one on the planet who feels that the old syntax is ok to use instead and isn’t overly verbose. I guess growing up with firstChild.childNodes makes you numb to the pig-latin you speak in code to get at your data. E4X, unintentionally, I perceived as more verbose because I am trying to learn as well as all the ActionScript 3 packages, mx packages, and countless other new API’s & methodologies at the same time. Spending 40 minutes on getting a new for each loop to work, referring to the docs twice, is all the temptation I need to say, “Fuggit, the old way works just fine, I know it well, and it’s faster at runtime than E4X anyway… why bother with this bs when the syntax isn’t that much cleaner?”

    Many would disagree. I debated with the top Flash minds twice in the past, all with next to no support. Many fawn over it. While I was visiting my boss in Des Moines, Iowa, he took it upon himself one evening to show me some refactored XML to E4X code. He was overjoyed… I didn’t care. Granted I was happy he was happy. He went from 5 verbose lines to 3 cleaner ones.

    “Ok… you’re still parsing… parsing blows.”

    I don’t have a choice with Ruby on Rails. Maybe I do, and don’t know it. There is so much stuff I don’t know about ROR, but I’m going with what I got, and what I got is a consistent and readable messaging schema between Flex and Rails. Rails sends easily understood XML messages, and the ones I send to it, it can read just fine. However, after writing my Delegate to speak the CRUD methods to my Rails controller methods, I really wasn’t looking forward to writing a gigantic Factory class to convert Rails XML messages to Array’s of Value Objects, and vice-versa.

    I’m still not, but found a really easy way to implement it. And thus, I get to why E4X doesn’t suck… I didn’t know it, but E4X supports binding, just like Flex does for binding variables to other variables. Suddenly, my ValueObjects who already implement a toString method to ease debugging:

    public function toString():String
    {
            var s:String = "";
            s += "[class ProjectVO";
            s += " id=" + id;
            s += " projectName=" + projectName;
            s += " updatedDate=" + updatedDate;
            s += " creationDate=" + creationDate;
            s += " ]";
            return s;
    }
    

    Now have a nice way to get their XML equivalent:

    public function toXML():XML
    {
    	var updatedDateString:String = DateUtils.getRubyDateString(updatedDate);
    	var creationDateString:String = DateUtils.getRubyDateString(creationDate);
    	var xmlified:XML =
    		<project>
    			<updated-date type="date">{updatedDateString}</updated-date>
    			<creation-date type="date">{creationDateString}</creation-date>
    			<id type="integer">{id}</id>
    			<project-name>{projectName}</project-name>
    		</project>;
    	return xmlified;
    }

    Now, for my HTTPService, I can just do:

    service.send ( myProjectVO.toXML() ) ;

    It’s also really easy to update in case the Rail’s side changes for whatever reason. I usually can just copy from ServiceCapture, paste into the VO class since XML can now be written without quoting rules, and swap the values with bindings to the VO’s public properties… nice!

    I don’t apologize for all the things I said, but wouldn’t have been so non-enthused had I known about bindings.

    …so… uh… anyone got Remoting working for Rails yet? Or at least a WebService way of using Rails vs. frikin’ HTTPService?

  • Searching for Warmth in a Label

    I’m having a tough time at my current job. The project itself is going well, though, and the code I’m writing is cool and fun. I’m a consultant working with a small team on a large software project. My 2 failings are being ineffective in communication with the client and not giving accurate time estimations on tasks. There are a plethora of other minor frustrations, but the reason, to me, they are a big deal is that it has all caused me burnout in a 2 month time frame. I typically go in 6 to 8 month intervals. The bipolar reaction from manic to reserved state is easy to see in retrospect. I was subscribed to over 40 email lists, most of which I read and responded to regularly. Reading the blogs was a 6 times a day routine. Nightly I’d dive into something code or technology related.

    Now, I’m not subscribed to any email lists, hit the blogs twice a day, and generally don’t even respond to personal emails. I’ve nearly exhausted my supply of games, and am ever searching for additional outlets, physical preferably at this point. I awake early and skip lunch to ensure I am not interrupted when her majesty arrives since I work from home and get easily distracted when not alone. This allows me to “clock out” earlier than normal. Daily, I pull from emotional reserves, almost scraping my deep set beliefs, all in an effort to conjure up a positive attitude to wear for the day. I refuse to mope around like some pathetic survivor. I’m in this game to win or die trying.

    Two separate, non-related events happened recently that really negatively directed my opinion towards my current career course. I immediately started to recognize the difference between Contracting and Consulting. At least, they were perceived that way to me. I started to write a blog entry in my head… and figured I’d go do some reading before I made up my mind. Even before that, I figured I’d give it some time… a lot of time. A few days to churn on my thoughts, and finally some spare time to read. Contracting vs Consulting on Google pulls up a lot of results. The first 10 provided a lot of good reading on just one instance of this comparison in the blogsphere. Even cooler was the comparisons between the UK and US which I can somewhat corroborate from talking to friends in the UK.

    My goal was to get a real sense of the word, Consulting. The comparison to Contracting helped, but so did the wide array of opinions. I had assumed that if you were in consulting, you were a consultant. However, it seems a lot of people are seeking identity through the term, and this offends others who view said terms as mere unimportant formalities that have very little substance. I found common ground on a lot of the writings and it’s nice to read something out of my Flash / Flex / CF comfort zone. It’s also nice to know the majority of the definitions revolve around perception. While its’ natural for software engineers to loathe a loosely defined term (how could something so good, OOP, lead to soo many passionate flame wars for example?), one clear theme is that the definitions of the words contracting and consulting are in the eyes of those procuring their services, and are hence re-enforced after the fact to those who fit the client’s mold of what the word meant to them. So, while at first glance Consulting may mean someone who advises, and a Contractor may mean hired code muscle, both definitions quickly crumble under scrutiny.

    I was hoping to affirm, deny, and challenge my assumptions, and I feel this is a really good first pass. When things start to suck, I tend to do a lot of quick justifications for my situation. I dare say I do my best to ensure 100% are NOT delusions constructed to deny the inevitable and/or obvious, but rather silver linings, and hopefully better perspectives. For example, in all the times in my career where I hated my current situation, I could always find some redeeming factor. Not necessarily redeeming of the forces that contributed to my suffering, but rather some positive and endearing that arose, and continues to do so while I am still there. While it’s sad I need to get into such dire straits to really appreciate and even recognize some, it’s not always that way. I’m pretty quick to recognize good learning and growing opportunities, whether good or ill, regardless of the weather. It’s just easier on the willpower if you give it some reason(s) to buttress it up.

    Case in point, 5 years ago I was at the studio at my former job furiously clicking away at 11:30pm at night, alone on a Friday night, my 3rd one in a row. I was building a website for my boss to sell his house. Rather, I was making changes that my boss wanted via email communication. What did I learn? Don’t use Fireworks to build a website. I use Fireworks to this day for mockups, image editing and compression as well as it being at the hub of my production art workflow. You don’t, however, see 37signals spouting, “Yes, we use Fireworks-created image maps for every page of our site.” And, those tortuous 6 weeks got me extremely good with Fireworks.

    Small potatoes in the grand scheme of things, but valid for me nonetheless.

    Either way, some hour and a half’s gallivant on Google to challenge assumptions has confirmed some, denied others, and learnt me on some new concepts. The jury’s still out, but two things are certainly clear. First, I have no intention of consulting the rest of my life. I had a lot more enjoyment in contracting, and labeling myself under either of the definitions is not what I want to do longterm. Secondly, I have a ton more to learn about consulting.

    Yes, I’m aware the statements contradict themselves, but the latter receives precedence. While I’m frustrated I have no tact with clients, and I refuse to give up when Flex won’t take my 32bit transparency thus taking more hours than approved, I recognize I have a lot more to learn, and should withhold any long term judgments. I’ve learned a lot already, those lessons are valuable, and the influx of them hasn’t slowed down.

    …still, f’me this is frustrating. Flex? You my bitch. Consulting? :: WHAP! :: Thank you… can I have another?

    Some good links I found on just the first page of a Google search. I’m sure if I read some books, periodicals, and talked to others I’d get some more context. Still, this was great for just a 1 hour investment.

    Great Overview of the definitions

    One take on how you are sought after

    10 things to ensure you don’t do with your client

    Consulting vs. Contracting

    Followup

    Original Article

    .NET’rz rebuttal

    Recruiters?

    Honesty

    Best Response

  • Ruby Chronicles #1: Blocks and Yield

    A “wtf” at lunch today while reading this book. There is a section on the 2 types of blocks in Ruby’s methods, and a description of the “yield” method. Totally jacked; it’s basically like sending an anonymous function in ActionScript seperate from a method’s parameters. The function then in turn runs that block of code for every yield statement. The yield statement can also pass parameters to this code block. Why you’d do this is beyond me, but when I yield, I’ll be using yield… imagine that?

    For example, here’s Ruby calling a method, passing a block that the yield will run inside of the method:

    def method
       puts "start of method"
       yield("this'll be arg1", "this'll be arg2")
       yield("this'll be arg1", "this'll be arg2")
       puts "end of method"
    end
    
    method {|arg1, arg2| puts arg1 + ", " + arg2}

    It’ll output (I think):

    start of method
    this’ll be arg1, this’ll be arg2
    this’ll be arg1, this’ll be arg2
    end of method

    The equivalent in ActionScript 1 is:

    function method ( someFunc )
    {
       trace("start of function");
       someFunc.call(this, "this'll be arg1", "this'll be arg2");
       someFunc.call(this, "this'll be arg1", "this'll be arg2");
       trace("end of function");
    }
    
    
    method(function(arg1, arg2){ trace(arg1 + ", " + arg2); });

    Which outputs:

    start of function
    this’ll be arg1, this’ll be arg2
    this’ll be arg1, this’ll be arg2
    end of function

    The only difference is the ActionScript example sends it as an argument whereas in Ruby, it appears to be sent as a seperate entity from the methods invocation parameters.

    Don’t get me started on the Archeologist degree one needs to read printf statements…

    Anyway, weird stuff.