Archive for September, 2010

Blog Seperator
September 21st, 2010

Logic Busters - Part 1: Singletons

Identifying and eliminating double instantiation of objects and single-synchronous-request “caching”

“Logic Busters” is a continuation of the “Schema Busters” series with an emphasis on business-logic practices that you can implement when engineering your web-applications. The concepts discussed in this series will differ from the previous in that they are geared towards programming practices and tips as opposed to database schema and query design. In this first section we will discuss the concept of singletons, how to implement singletons, and efficiency gains from the utilization of singletons. Since singletons deal heavily with object management and objects have a tendency to be reflective of database entities I hope this subject will serve as a proper transition from our database studies into the realm of application logic.

What is a Singleton?

The singleton is a mathematical concept that simply states any instance of an object must be equivalent to itself and is universally unique from all other objects. If there were another object with the exact same properties it would be one and the same as the original. In programming it is quite possible and easy to violate the Singleton concept. Imagine instantiating two copies of an object and performing separate and distinct operations on them effectively make them unequal. This in turn destroys any possibility of maintaining object singularity.

Why use the Singleton pattern?

Before continuing let’s analyze the benefits and costs of such behaviors. Obviously being able to manipulate two copies of the same object independently provides great flexibility, but at what cost? An immediate concern rises in the situation of multithreaded or asynchronous environments (multitasking in laymen’s terms), where data integrity and symmetry can prove vital. This issue is best illustrated by looking at a concept called conflicting transactions which is more commonly associated with database transactions. Imagine that we have the following database table:

tblUser
userId login password email active

…and the following two transactions where the value of “@parameter-name-here” is passed at transaction call:

Name:
Trans_UpdateUserId
Description:
Updates the user id
Query:
UPDATE tblUser SET userId = @userId WHERE userLogin = @userLogin

Name:
Trans_UpdateUserEmail
Description:
Updates the user email
Query:UPDATE tblUser SET email = @email WHERE userId = @userId

If we are to run these two transactions independent of each other on a user with the below described data, we now have three scenarios:

User:
1. userId = 1
2. login = ‘JGFree’
3. password = ‘secret’
4. email = ‘jgfree@lifeblue.com’

Transaction Scenario 1:
1. Trans_UpdateUserId is run with @login = ‘JGFree’ and @userId = 2
2. Trans_UpdateUserId finishes
3. Trans_UpdateUserEmail is run with @userId = 1 and @email = ‘new@email.com’
4. Trans_UpdateUserEmail finishes
5. Final state of user:
userId = 2, login = ‘JGFree’, password = ‘secret’, email = ‘jgfree@lifeblue.com’

Transaction Scenario 2:
1. Trans_UpdateUserEmail is run with @userId = 1 and @email = ‘new@email.com’
2. Trans_UpdateUserEmail finishes
3. Trans_UpdateUserId is run with @login = ‘JGFree’ and @userId = 2
4. Trans_UpdateUserId finishes
5. Final state of user:
userId = 2, login = ‘JGFree’, password = ‘secret’, email = ‘new@email.com’

Transaction Scenario 3:
1. Trans_UpdateUserId is run with @login = ‘JGFree’ and @userId = 2
2. Trans_UpdateUserEmail is run with @userId = 1 and @email = ‘new@email.com’
3. Inconsistent behavior from here on out since both transactions will try to access same record at the same time.
4. Note that this inconsistency can also be caused by switching 1 and 2 of this scenario.

For the sake of our discussion we will disregard Transaction Scenario 3 since this kind of conflict is more appropriately addressed by Database Management Systems and Memory Access Systems and how they handle this kind of simultaneous access conflict, a concept that is not pertinent for us at this moment. The reason I use these transactions is to show that two copies of the same object, like the above user with the above described properties, subjected to two different transaction scenarios can result in different object states.
Now we should stop and consider that this behavior is either desirable or undesirable depending on your project’s technical specifications. If it happens to be desirable then we can disregard this entire study and get back to work (you time-thieving, blog-trolling slacker). Otherwise we can begin the implementation of Singletons to make sure that object state is maintained across multiple transactions.

Implementing Singleton objects and how they work

Implementing a Singleton requires little additional coding, but a strong consideration for consistency. The basic concept is to statically store an instance of whatever object we are creating a singleton out of, and upon redundant load calls we simply reference the static singleton object. Most object-oriented classes have a constructor or instantiate method that loads all of the properties of an object based on its identifier. When initially called, we should check if the identifier matches that of our singleton object. If so we return the singleton object. Otherwise we continue loading the new instance and replace our singleton object with the resultant object. In a similar manner, every time we make a change to our object we must also update the singleton.

Immediately we can see how this kind of structure can reduce our database calls significantly. Imagine that we load the same instance of an object three times throughout the span of a request. Utilizing the singleton concept we now reduce our database use by 66%. We can expand upon this idea by allowing for Singleton Dictionaries which is simply a static collection of objects mapped by their identifier. If we are loading all users three times throughout the span of a request, we are now producing significant traffic (dependent on your user pool obviously). Since it is semi-difficult to include code in this blog and the code I would provide is available elsewhere, I will simply refer those interested to sites already containing examples of singleton use:

-http://www.developertutorials.com/tutorials/php/php-singleton-design-pattern-050729-1050/
-http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html

Now hopefully your program does not require you to load every single user three distinct times in a single request. Singletons are extremely situational and are not your primary means of reducing resource use. An obvious place to implement a singleton would be for managing the object currently logged in since it often gets referenced multiple times in a page load. Look for these kinds of situations to implement this data structure.

Conclusion

Looking back at our example where we performed asynchronous transactions on a non-singleton object yielding different possible results, we can now see how a singleton would enforce the legitimacy of both transactions. Each transaction would update the singleton which would then be the result of both transactions as opposed to any kind of deviation produced by the order of transaction operation. Transaction 1 will now produce the same results as Transaction 2 since the userId is consistent for both transactions, Trans_UpdateUserEmail and Trans_UpdateUserId.

Singletons are a great data structure to consider when tweaking your application to maximize performance. They are not the answer to all of your resource management needs, but they serve their purpose beautifully. If you enjoyed learning about this data structure and how it can be applied, I encourage you to seek out other data structures as they have the potential to improve your site/application performance and reduce the complexity of your code. I recommend beginning with the “Current User” example I provided above, and then reevaluate your program to see where this kind of technology makes sense.

September 21st, 2010 in Nerd Matrix, Web Development | Comments (2)
Blog Seperator
September 13th, 2010

PHP Factory Design Pattern Part 1

For my next several blogs I’m going to be discussing a powerful PHP design pattern, the factory. Since PHP applications and the data structures they interface with are getting larger and more complex there is a need to streamline and simplify how these data structures are loaded into useful objects.

For example, let’s take robust CMS. A simple CMS has only one content type: a page. However, for more complex CMS systems you have multiple content types such as events, publications, and even products. Each one of these content types needs to have its own properties and methods that are unique to that content type. We end up with a problem. How do we deal with the unique needs for each type of content and maintain an efficient application?

It makes no sense whatsoever to include all of the properties and methods for every content type into a single class definition and database table. The class would be a behemoth. Once the object was loaded it would be a resource hog, eating up memory and processor power. On a small site with little traffic this might be ok, but any high volume CMS would grind to a halt under these conditions.

On the flip side, doing a new unique class for each content type is not much better. To request a piece of content then render it properly to the browser you would need to search across multiple classes and database tables. Not only that, because there are multiple tables, there could easily be URL and naming conflicts. Also, great care would have to be taken to ensure that all of these objects followed a common interface. If not, loading appropriate content could become a “switch case” and “if else” nightmare. Maintenance on that kind of system gives me the shivers just thinking about it.

Enter the factory design pattern. This design pattern lays out a few nice rules that simplify situations just like our example. First it would allow for a unified method for loading all content types, from one place. Second it would require consistency within all the classes. Everything would have to work the same way on a basic level, and the unique functionality would be in addition to that. There would be one central place where the core data was loaded, and then any extra information would be held in it’s unique storage medium, such as a database table.

First let’s look at what a factory is:

  • A factory is a class that is designed to load various types of objects that all share a common interface.
  • A factory class does nothing but load objects.
  • A factory intelligently decides what object should be loaded based on the parameters it is given.
  • Most often the objects a factory loads have a shared purpose.

Let’s look at what defines the factory design pattern:

  • Classes the factory loads are structured in a similar way so that they can be loaded using the same basic method call.
  • Classes the factory loads follow a unified structure, most often defined by a parent class or an interface.
  • Classes the factory loads do not need anything from the factory once they are loaded. The factory’s job is done.

As you can see, the factory pattern provides a means to load similar objects from one place. It is an extremely useful pattern within PHP web applications. In my next post I’ll provide some UML and coding examples to flesh out this useful design pattern.

September 13th, 2010 in Nerd Matrix, Web Development | Comments (1)
Blog Seperator
September 3rd, 2010

Inspirational Design Sites

Since my last blog entry was on the ills of creative block, I figured it appropriate to follow up with a list of design blogs/sites that I use on a regular basis to keep up with what’s hot in the design world. (I know this topic has been done before on the LB blog, but…not by me! )

I’ve talked before about how important I think it is as a designer to immerse yourself in the world of design . Personally, I sometimes obsess over it to the point of it being a bit unhealthy, but what can I say - I love the stuff.

When I was a design student at the Art Institute of Dallas, the library was full of design annuals, books, & magazines on design of all kinds. Inspiration was never more than a library trip away. But have you ever looked at the prices of these annuals and publications? Man, they’re not cheep! That’s why a high quality design site is worth gold; they’re super accessible and best of all…FREE!

Here’s a list of some goodn’s:

1. Logo Pond
Welcome to my latest obsession. Logo Pond is a free site where some of the biggest and best logo designers (along with anyone else who wants to upload their work) post designs for critique, feedback, and show. It’s a huge resource for inspiration, and a great place to get critiques from some of the best in the business. If your submitted logo makes the gallery (and our Taste of Watters Creek logo recently has), you’ve done something outstanding.

2. Logo Design Love
Moving on with logo sites, Logo Design Love is a great place to find articles on what’s going on in the world of logo design, articles on the logo design process, and interviews from top logo designers.

3. Logo Lounge (I promise not all of these will be logo sites!)
Logo Lounge is the website of the famed Logo Lounge book series. Without being a member, access to the site is limited, but there’s still some good content to get at, like the logo trends article. If you are a member, you can upload logos to be considered for their publication (fingers crossed for a future pick from the LB!).

4. Under Consideration
This site mostly shows brands who have currently undergone image overhauls or revamps and gives commentary. Sometimes the commentary errs on the negative side, but it’s cool to see who is updating and what they’re updating to.

5. Behance
Behance has got to be my all-time favorite. This place is a great resource for creative professionals of all kinds. Users upload projects and the best ones get showcased in the gallery. Let me tell you, the work here is hot, hot, hot! It includes everything from fashion, product design, photography, web, branding, print, illustration, painting, animation, architecture, interior design, and sound can be found here. It is truly inspiring!

6. Smashing Magazine
Geared for design on the web, Smashing is good for both graphic guys and developers alike. They have informative articles, interviews, themed showcases, great inspirational entries, and I love all their freebies - specifically the icon sets.

7. Luke Lucas
Luke Lucas is an Australian designer who deals mostly with typography illustration. His blog is mostly about the aforementioned. It’s not something I get the pleasure to do very often - if at all - in my professional career, but it’s super inspiring to me and I respect the heck out of it. Overall, there’s a lot of cool artsy stuff there.

8. fffffound
This site is pretty cool - sometimes a little too cool. At times it’s too much of a hipsters paradise for me, but there’s also a lot of stunning cutting edge imagery that can be found here. Users can posts and share their favorite found images from around the web, mostly having to do with art and design. Warning - sometimes the images contain “artsy” nudity and can be rather racy. Gasp! Not my thing at all, but there’s lots of wholesome design goodness at ffffound too.

9. Design Observer
Founded by Pentagram’s Michael Bierut and others, Design Observer is a more intellectual approach to the design world. There are lots of well written essays and commentary for when you feel like getting all brainy about design.

10. Under Consideration FPO
Aka, For Print Only, is all about topnotch projects from the wonderful world of print design. What’s really cool about this site is that it shows a project overview and details, including quantity produced, production cost, production time, print method, dimensions, paper stock used, etc. For a design nerd me, it’s really cool to see all of those real-world specifications. Inspiration + real-world education = a better designer.

11. Page Crush
A self proclaimed inspirational design hub, page crush is chalk full of examples of well designed websites. It’s a nice stop to gather some quick ideas for web layouts if you’re feeling a little creatively stumped.

12. ISO50
This is the blog of graphic design guru Scott Hansen aka ISO50 I’ve been a long-time fan of ISO50’s work. His blog is a nice showcase of design stuff that inspires him, including a lot of retro design goodies, as well as some practical information entries like design magazine critiques & overviews.

13. The CSS Awards
Another web design specific blog a lot like page crush. What I really like about this site is that it ranks every featured site on a scale of 1 - 10 on the criteria of design, creativity, usability, and content. The rating is displayed in a cool color-coded graphic and the featured work is always top-notch.

14. FWA
FWA stand for Favorite Website Award. It is a recognized industry award program and inspirational portal. If you’ve won an FWA, you’ve done something truly amazing. When you want to be floored & inspired by some forward-thinking outside of the box conceptual madness, this is the place. These sites push boundaries in design, functionality, and content. I heart FWA.

15. AIGA
In their own words, “AIGA, the professional association for design, stimulates thinking about design, demonstrates the value of design and empowers the success of designers at each stage of their careers. AIGA’s mission is to advance designing as a professional craft, strategic tool and vital cultural force. Founded in 1914, AIGA remains the oldest and largest professional membership organization for design, and is a nonprofit, 501(c)(3) educational institution.” Couldn’t have said it better myself! Their site is a great stop for all things design, including inspiration, professional resources, education, the business of design, and articles.

Well there you have it, folks - 15 of my favorite design site bookmarks. If you’re a design junkie like me who has a huge scrolling list of bookmarks of design sites & blogs, I hope I’ve turned you on to one or two that you haven’t been to before. If you’re new to the world of design sites, well then…welcome to the obsession. Is there one I missed? Please leave comments with your favorite design site and maybe I’ll feature it in my next blog.

September 3rd, 2010 in Web Design | Comments (1)