Announcing: StartupQ8 Event for February 2015

Originally posted on :

We’re excited to announce the first StartupQ8 Event of 2015! Join us on Monday, February 2nd as we welcome two well-traveled entrepreneurs who will share their experiences with us.

The first segment will feature app developer Mazyad AlAbduljalil, a long time member of the StartupQ8 Community. He has developed apps from Kuwait to San Francisco, and will share his insights into how to build a mobile app MVP. Also this month, Mohammed AlBesharah, founder of Jaribha, will talk about the challenges he faces as an entrepreneur building a crowd-funding platform in Kuwait. As always,Global Investment House has graciously agreed to host the talk.

See you guys Monday Feb 2nd at 7:20 pm!

Schedule:

7:20 – 7:30 Intro
7:30 – 8:10 Mobile App MVP with Mazyad AlAbduljalil
8:10 – 8:20 Mini-break
8:20 – 9:00 An interview with Mohammed AlBesharah
9:00 – 9:20 Networking

As always, the event will be in English and it is…

View original 16 more words

Creating a Map Editor for a Game (6/6)

This is the sixth part of a series highlighting the development of a Map Editor app for a game. In the previous posts, we looked at the data model that drives the map editor, and how we are generating C++ code automatically using python scripts. As promised, this part will be all about the entities of the Cocoa application.

Scripting languages are so freakin’ useful. I just had take that out of my chest. There were tons of times where I really wanted to write a small program that would make my life a little easier, but the pain of writing it would exceed its usefulness. I remember that one time when I wanted to know when a webpage on a very old site is updated, and wrote a full fledged MacOS Cocoa status bar app just to monitor the status… It was a pain, and certainly not worth the time. However, now that I learned python over the course of the last few months, this task would take at most 1 minute to code, and would definitely be worth it! from introduction import end.

If I were to ask any programmer on the face of the earth what he would expect the entity classes for this Map Editor app would be, they would definitely say “MapMeta” class, “MapAction” class, … etc. It makes sense to assume that, since these are the basic entities of the map, right? Well, it would be correct if this was your typical software that you write everyday, but it isn’t. We explained that this map editor should have these entities defined in a plist, and controlled from there, hence being data-driven. So, writing any code that is tailored to those entities is a no no. So, what to do?!

I will go ahead and say that, initially, I loaded those plist files into NSDictionaries and NSArrays, and the app worked fine. With the power of Key-Value Coding (KVC), which is behind Cocoa bindings, I was able to implement a very generic data model without a single subclass. That is almost impossible to do without making the code horrible unreadable, but fortunately, I utilized ObjC’s categories to work around that! So, no subclasses, just categories :D.

So, did I just stick with this? Unfortunately, the answer is NO. A HUGE burden, believe it or not, was backwards-compatibility. Just by using these vanilla data structures, it was extremely hard to add a proper “version control” thing. This is simply because when you load a plist/json, you typically load the whole thing using a few lines of code, and get a root object. You would either have to traverse it and sort the old version mess somehow, or write your own parser… Not an approach I would prefer. So, let’s just see how it was ultimately done! (Another small problem was that KVC is used heavily to bind the data with the UI. Since these data structures are “highly decoupling” (you access them through keys and indexes, not concrete properties), it makes things hard to debug and write safely)

If we can’t create explicit subclasses, nor use generic data structures, then what’s the compromise we are looking for? I’ll tell you what it is: It’s an “adapter” class that represents a UI element, but has a reference to the actual data! Let us start visualizing what’s going on:

The data models:

EverCraftModel

The Adapter classes:

EverCraftAdapters

That’s it! Two adapter classes is all we need, really. One class is for the entities that are shown in the top left outline view, and the other is for the parameters that are shown in the bottom left outline view. I don’t think there is anything else to it, honestly. The only interesting part in this would be the serialization, then again, it’s a totally different story…

Conclusion:

I’ll go ahead and admit that I probably didn’t give this series my all, especially this last part. Explaining the data side is always tricky, I guess, even more so when you are doing some weird data wizardly and shtuff. Well, I think I am more excited about what’s coming next, so let’s brush this under the rug!

Creating a Map Editor for a Game (5/6)

This is the fifth part of a series highlighting the process developing a Map Editor for a game. In the previous posts, we looked at the data model that drives the map editor, and how we are generating C++ code automatically using python scripts. As promised, this part will be all about the Cocoa application, that is, the Map Editor itself.

I believe that there is a very interesting relationship between the size of a development team, the scope of the project, and the number of tools and scripts that have been developed for the project. Obviously, as the number of developers in a team increases, the project can afford to set aside some man hours for tool development that in turn contributes the the success of the project. On the other hand, when you have a small team, there isn’t much that you can do except salvage the Internet for tools already developed for you that you can start using immediately. Meh… Let’s just get started with the post already.

YES! Today we will actually see the UI of this so-called map editor! :D. I mean, initially I didn’t want to divert any attention to the Map Editor itself, since the novelty lies in the data driven process of manipulating the Map Editor’s features. Ultimately, I realized there is a lot to learn from the Map Editor UI development side, too. Without further Ado, let us look at how it looks like as of Today!

meta

prefab

selection

I thought I’d give a glimpse of the UI before we see the inner details. Mind you, there is no way I can cover all the details exhaustively, but a quick run through all the major components that make this Map Editor possible.

First, I would like to shed some light on the views of the application. We will see the view components in detail, and a little bit of the controller part, too, to get a complete picture regarding the views. Only after we talk about all the views, will we start discussing the application model. So, the first view we will be presenting is the upper left panel that has the basic structure of the map components.

meta

Before we see the code for this component, let me try and explain it at a relatively abstract level. This component is referred to as NSOutlineView. You can provide it with a tree of objects, and it will properly show the objects in a hierarchal fashion. So, when an object has children, it will show the expand triangle to indicate that children exist. That is all there is to it, really. Remember, the UI is not concerned with the implementation details and logic, it is just representing the data for the user.

There are a few things I want to talk about here: How are we supplying the objects to the outline view? How does the outline view know that the object has children, or what to set as the row name?

To answer the first question, we are using an NSTreeController. This class is just another object controller that can handle a tree of objects. You can think of object controllers as predefined controllers (from the MVC pattern) that can automagically connect a model to a view without writing the controller code yourself. Other examples include an array controller, which you can bind to a table view, and BAM! The table view displays the objects that are inside an array.

Screenshot 2014-01-01 21.38.53With the tree controller representing the model to the outline view, we can then use Cocoa Bindings to say something like: “Hey, outline view. Get the object tree from the controller, and fetch the ‘label’ property from any object inside the tree and use it as the row name”. Yeah, sounds crazy, but that’s how it works!

What was said previously begs the question: But where does this label come from? Excellent question, Bob. I have been talking about object hierarchy and structure, but I never really talked about the object itself. The objects in the hierarchy are actually instances of a custom class called: ECObject. By looking at the structure of this class, you can easily realize that the properties defined are what we bind to the outline view and tree controller.

  1 
@interface ECObject : NSObject
  2 
 
  3 
/* Label is set by the user and displayed with the object in the renderer */
  4 
@property (copy) NSString *label; /* DATA */
  5 
/* The fixed class_id or prefab_id this object was instantiated from */
  6 
@property (copy) NSString *class_id; /* LINK */
  7 
/* The parameters of the prefab */
  8 
@property (copy) NSArray *parameters; /* INDEPENDENT */
  9 
/* The child prefabs that this instance can instantiate */
 10 
@property (copy) NSArray *prefabs; /* CONFIG */
 11 
/* The children container */
 12 
@property (strong) NSMutableArray *children; /* DATA */
 13 
/* The links between subjects and observers. Retained for a reason */
 14 
@property (strong) NSArray *links; /* CONFIG */
 15 
 
 16 
/* COCOA BINDINGS HELPERS */
 17 
/* Is this value fixed or can be changed by the user? */
 18 
@property (getter=isFixed) BOOL fixed; /* CONFIG */
 19 
/* Can the user delete this instance in the GUI? */
 20 
@property (getter=isDeletable) BOOL deletable; /* CONFIG */
 21 
 
 22 
/* selection */
 23 
@property (getter=isSelected) BOOL selected;

Screenshot 2014-01-01 21.53.32Now, regarding how the outline view knows the object has children, this comes for free when we bound it to the tree controller. The tree controller has to be set up with the property that refers to the children in the ECObject. I also set the object type of the tree controller content to ECObject. Note, the image on the left has been photoshoped for brevity sake.

One last thing I would like to cover here are the “Add” and “Delete” buttons. Because I need granular control on adding objects to this outline view, I cannot simply bind the add button to the tree controller (Even though that is possible!!). If we did bind them, what will happen is, an ECObject will be instantiated by passing alloc and then init messages to the ECObject class (a fancy way of saying, [[ECObject alloc] init] is called). That won’t do. We need to allocate the ECObject based on the parent’s prefab property. For example, from the images in the very beginning, “Objects” has a prefab “MapObject”, so we need to allocate an ECObject that has “MapObject” parameters and properties. This is all part of the Model, though, so we will see the details later. The important point here is, we enable “Add” if the ECObject has prefabs, and clicking “Add” will display the prefabs for the user to choose from. After choosing a prefab, an ECObject is instantiated from the prefab and added as a child of the selected ECObject. Delete is simply enabled if the deletable property is true on the ECObject.

I think this covers the components outline view pretty well (this is what I refer to the outline view we just covered). Moving along, we shall now look at the lower left view, which also happens to be an outline view! The difference, though, is that this one is view-based, and the previous was cell based. Don’t concern yourself with this difference, though. Anyways, this component is referred to as the parameters outline view, since it displays the parameters of an ECObject. Refer to the previous code snippet, and look for the parameters property.

meta In the MapMeta example on the left, you can see that based on the parameter’s type, we show the appropriate UI component. For example, if the parameter is a boolean, a checkmark is shown. Unfortunately, all we have in this example are numbers, which use an NSTextField component with an attached NSFormatter that makes sure the user enters a valid number. Note how parameters can have children. “map_size” is of type “Size”, which is just a parameter with two child number parameters.

Similar to how we used the ECObject class to represent an object in the components outline view, we use ECParameter class here to represent the objects in the parameters outline view. Since it is pretty much the same procedure, I won’t bother explain it again. However, one interesting part is how the parameters outline view morphs based on the parameter type! I’ll just paste the code that does that. It is located in an NSTableCellView subclass, called ECMorphingCell.

  1 
- (NSControl *)_morphToSwitchCell
  2 
{
  3 
    NSButton *button = [[NSButton alloc] initWithFrame:self.bounds];
  4 
    [button setButtonType:NSSwitchButton];
  5 
    [button setTitle:@""];
  6 
   
  7 
    return button;
  8 
}
  9 
 
 10 
- (NSControl *)_morphToTextFieldCell
 11 
{
 12 
    NSTextField *field = [[NSTextField alloc] init];
 13 
    return field;
 14 
}
 15 
 
 16 
- (NSControl *)_morphToNumberInputCell
 17 
{
 18 
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
 19 
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
 20 
   
 21 
    NSTextField *field = [[NSTextField alloc] init];
 22 
    field.formatter = formatter;
 23 
    return field;
 24 
}
 25 
 
 26 
...
 27 
 
 28 
- (NSControl *)_resolveParameter:(ECParameter *)param
 29 
{
 30 
    id value = param.value;
 31 
    NSString *content = param.content;
 32 
    NSString *enums = param.enumRef;
 33 
   
 34 
    if (content || enums)
 35 
    {
 36 
        ...
 37 
    }
 38 
   
 39 
    else if ([value isKindOfClass:[NSString class]])
 40 
    {
 41 
        self.type = eMorphingCellTypeText;
 42 
        return [self _morphToTextFieldCell];
 43 
    }
 44 
   
 45 
    else if ([value isKindOfClass:[NSNumber class]])
 46 
    {
 47 
        CFNumberType numberType = CFNumberGetType((CFNumberRef)value);
 48 
        switch (numberType)
 49 
        {
 50 
            case kCFNumberCharType:
 51 
                self.type = eMorphingCellTypeSwitch;
 52 
                return [self _morphToSwitchCell];
 53 
               
 54 
            default:
 55 
                self.type = eMorphingCellTypeNumber;
 56 
                return [self _morphToNumberInputCell];
 57 
        }
 58 
    }
 59 
   
 60 
    if (value)
 61 
    {
 62 
        NSLog(@"Warning: unresolved object type: %@", value);
 63 
    }
 64 
   
 65 
    self.type = eMorphingCellTypeNone;
 66 
    return nil;
 67 
}

I will only mention that this is all pretty straight forward, except the enum and options type. When the type of a ECParameter is an enum, we need to show a combo box with the available enums. Similarly, if the type is a list of options (strings). This is a bit more involved, were we query the “Model Manager” for these options, and assign them to a combo box so the user can see his options.

DAMN IT!! I PUBLISHED THE POST BY MISTAKE!! I am typing the rest right now…

Anyways, all I have left is the rendering view, which renders all the entities as visual objects the user can interact with. It might look a bit complicated, but it is actually quite simple.

prefab The basic idea behind this is: I subclassed NSView and overrided drawRect: in order to render the Model. Inside the view, I dispatch a timer that calls setNeedsDisplay 2 times per second, so I don’t have to worry about the model changing at all. This is a less efficient polling approach, but works really well, so meh. Then, within drawRect:, I get the model, and do some quartz drawing! I’ll post some code so you can get the main idea:

  1 
- (void)drawRect:(CGRect)r
  2 
{
  3 
    /* Get all the data model */
  4 
    NSArray *meta = [[ECDataBank sharedBank] mapMeta];
  5 
    NSArray *objs = [[ECDataBank sharedBank] mapObjects];
  6 
    NSArray *zones = [[ECDataBank sharedBank] mapZones];
  7 
    NSArray *spawns = [[ECDataBank sharedBank] mapSpawnAreas];
  8 
   
  9 
    int padding = [meta[@"padding"][@"value"] intValue];
 10 
    NSArray *size = meta[@"map_size"][@"children"];
 11 
    CGSize mapSize =
 12 
    {
 13 
        2*padding + [size[@"width"][@"value"] doubleValue],
 14 
        2*padding + [size[@"height"][@"value"] doubleValue]
 15 
    };
 16 
    /* map size is used to compute the transform */
 17 
    self.mapSize = mapSize;
 18 
   
 19 
    id selection = nil;
 20 
    /* render the objects as a box on the tilemap */
 21 
    for (NSArray *obj in objs)
 22 
    {
 23 
        if ([obj[@"isSelected"] boolValue])
 24 
        {
 25 
            selection = obj;
 26 
        }
 27 
       
 28 
        rect = [self _rectFromObject:obj];
 29 
        [rects addObject:[NSValue valueWithRect:rect]];
 30 
 
 31 
        [[NSColor colorWithCalibratedWhite:0.6 alpha:1.0] set];
 32 
        [[NSColor blackColor] setStroke];
 33 
       
 34 
        CGContextAddRect(ctx, rect);
 35 
        CGContextDrawPath(ctx, kCGPathFillStroke);
 36 
        /* render the name of the object on the top left */
 37 
        CGContextConcatCTM(ctx, [self _textTransfromForRect:rect]);
 38 
        [obj[@"name"] drawInRect:rect withAttributes:nil];
 39 
        CGContextConcatCTM(ctx, CGAffineTransformInvert([self _textTransfromForRect:rect]));
 40 
    }
 41 
   
 42 
    ...
 43 
}

Actually, there is one really cool and super complicated part in this: The ISO Transform! I am sure you noticed, the map is skewed and rotated. The (0,0) point in the map is the top middle block, which is not the same as the regular cocoa coordinate system, where (0,0) is in the bottom left. We achieve that by transforming the renderer to achieve that ISO look. The biggest challenge is not that, though. It is mapping the mouse events to the transformed coordinates! So, we know that our custom NSView has (0,0) at the bottom left, but we want the mouse to give us (0,0) when we click at the top of the map! We achieve that through affine transforms, which I won’t bother explaining! :D

Conclusion:

Actually, writing about the model of this application will take a while, might as well take that on in part 6… So, make sure you come back for that one, too!

Google App Engine (GAE)

When man first brought forth the power of programming, they were doing everything from scratch. Slowly, developers started to contribute frameworks and wrappers to make it easier to use a resource. I mean, imagine having to write an iOS app or a web app by aligning transistors? Yeah, it’ll probably take 29343 years to write a hello world app, with bugs of course. Hence, people came up with the ISA (instruction set architecture) to facilitate software developers with the hardware they ultimately want to run programs on. That isn’t enough, is it? It’ll probably take 22 years to write an Assembly program that authenticates users, tracks sessions, connect to the datastore, … etc. “Well, let’s write a higher level language”, developers agreed. Now, we have cool languages like C++, Java, … etc. I am sure that is enough? Nope. Even with a high level programming language, we have frameworks on top of frameworks, and on top of all that a Platform as a Service (PaaS). That’s GAE.

Even though I praised GAE a little too much in the introduction, it’ll be all downhill from here (lol, no actually not that harsh). GAE is a great platform to deploy your applications and forget about them as they scale to accommodate millions of users. It scales automagically, it has a whole set of available tools for you to leverage, and many perks that makes it very desirable. The most glorious feature that dragged me in is the free-to-start price model that they have. You can deploy your full fledged app for FREE, and start using it and testing it all you want. The charges only kick in when you get some traction, which by then, you hopefully have some money from those users.

With all that being said, I came here to express my unlimited frustration regarding how some of their provided services work >_<. You want to use their built-in OAuth framework? Go ahead! :D But, the user must sign in using a google account… You want to track users automagically using their Users framework? Go ahead! :D But, the user must be authenticated with their accounts service using a friggin’ google account. :| . OK, I give up. I’ll still use GAE, but their is no way I can force my users to login using a google account, so I’ll reinvent the wheel, in a way :'(.

Design Patterns: Structural

In previous posts, we covered 11 behavioral design patterns. For now, we will switch to structural design patterns, and hopefully, Creational design patterns will follow.

In life, when something doesn’t work out, I have the tendency to view it as an advantage. This is actually one of the first lessons I learned in the Kuwait Fund training I went through. It may sound cheesy and simple, but you might be astonished how worked up and stressed we get sometimes over the smallest things that we can take to our advantage. Stuck in traffic? Listen to a useful audio book. Cancelled a trip to the Maldives? Do so more coding :D. And so on…

With that weird introduction out of the way, let’s dive into a real intro. What are structural patterns? It’s a pattern where you simply organize the structural flow of your objects. When we talked about behavioral patterns, each pattern allowed us to impose new behaviors based on the program flow. Here, it is a lot simpler, where we simply organize the objects in a way that gives us new desirable features, which in turn solves important design problems. So, let us present the patterns we will be exploring today!

designpatterns_struct


Proxy

Use case: ★★★★
Elegance: ★★★★★


Overview

The proxy pattern is quite simple, and clicks very well with Objective-C, especially. I don’t know about other languages. As a matter of fact, ObjC has an NSProxy class, which eliminates the need to write the boiler plate code to implement this design. So, onto the design! It is simply like putting a body guard/secretary for an object. Instead of holding a pointer to the object itself, and passing that around, you would create a proxy object which references the “protected” object.

Examples

The reasons why we would want to do this are abundant. Smart pointers in C++ do that, so the proxy keeps count of how many references are pointing the object, and deallocates it when all the references are gone. Notice, this is not a garbage collector! This is a much more efficient approach that involves creating a “small garbage collector” for each object you want to NOT bother deallocate when you are done with it.

Another good reason to use this pattern is when the protected object is actually huge, or resides in a database, and we do NOT want to use it immediately. Hence, we defer that objects allocation to a later time, a time when we actually need it. Let’d give an analogy for this first. This works as if you really want to sleep, but if don’t want to be caught flatfooted. So, you would ask someone to stand outside, and wake you up if the boss approaches. So, back to the proxy pattern, when you try to access the not-yet-initialized object through the proxy object, it will intelligently allocate the object it’s protecting first, then passes your access message. Lazy loading at its best. This pattern is used extensively in CoreData, actually.


Adapter

Use case: ★★★
Elegance: ★


Overview

This pattern is lucky to get a once star for elegance. It is really basic, and I would advise against using it for your own classes. The only good thing about this pattern is that the name is so clear to us, and we can immediately realize what is the use case for it would be. We use adapters everyday in our lives to plug an old thunderbolt display’s power cord to a new Retina MacBook Pro (In this case, we use the MagSafe to MagSafe2 adapter). We use adapters when traveling to plug our electronics to the countries power sockets, and so on.

It is exactly the same use case in the programming world. You would have an old or incompatible component that you would really like to reuse with your code, given that you don’t want to change the code in the component’s class (or you can’t). You would write an adapter class that, when instantiated, creates the reusable component immediately. Then, you would define specific operations for the adapter and implement them my mapping those calls to the encapsulated component.

Examples

I think the examples are abundant in this field. A simple example would be an adapter class I wrote when developing Islamicaster, not knowing this is the adapter pattern. I had the Objective-C NSCalendar and NSDate classes, but it was a pain to use them in my code, since they don’t provide direct access to simple things, like return the first day of the month. I either have to write redundant code everywhere, or write an MCDate class that uses internal NSCalendar & NSDate objects to calculate those calls, which is what I did. So, when I call “First day of the month”, the method invoked would call certain methods on the NSDate class, pass that to NSCalendar, and with a little bit of luck, return the expected result.

Another cool example would be if you have a class that can format text, but you wrote it without following any specific standard, then you want to reuse it in your Cocoa application. In Cocoa, you’re better off attaching an NSFormatter subclass to a Text field, since everything would be handled for you that way. So, you would create an NSFormatter subclass that implements the necessary subclass requirements, and computes the results by using the formatting code you wrote earlier.


Bridge

Use case: ★★
Elegance: ★★★


Overview

I really don’t have anything against this pattern, it just feels like the type that only clicks when it clicks. I mean, there are very special cases where it works epic-ly. So, this pattern is actually awesome. It allows you to grow two separate class hierarchies independently, and link them with each other dynamically. Ooooo, such big words there, so let’s dumbify it a bit. This pattern allows us to have two class hierarchies that are related to each other, since one of them uses the other, but we don’t want to impose changes to one hierarchy when the other changes. When I think about it, this pattern is actually VERY close to the visitor pattern, but instead of decoupling the classes and varying the behavior, the classes from one hierarchy would hold pointers to objects from the other hierarchy, based on the requirement.

Examples

Let us imagine … Wait, before we imagine, I am a game developer, and most of my examples aren’t game related :(. Let me fix that. Ehm, so… Let’s imagine we have a hierarchy on “GameObject” classes. Inheriting from this class, we have “Unit”, “Building”, … etc. Now, we have a requirement to implement a custom Christmas theme, which changes the sound played when selecting buildings, the particle effects, … etc. The cleanest way we can do that is by writing a separate Theme hierarchy, which is inherited by X-mas theme, halloween theme, etc., and then the class would simply query the theme object it has for the appropriate data. Alternatively, the object can just make calls like: “playSound(getID())”, and make it the theme’s job to play the asset, but that is less likely to work.


Decorator

Use case: ★★★
Elegance: ★★★


Overview

I think Java is the only language that tends to have almost all these design patterns in its frameworks :s. Not necessarily a good thing, nor a bad thing, it probably just contributes to the learning curve. Anyways, the decorator pattern in a nutshell: You have a base object that you want to enhance dynamically, so you would define a base decorator interface, and any other class that implements this interface can decorate your object (Your object must implement that interface as well).

Examples

So, let’s say you have a Sound class that plays a sound. You want to apply different filters to that sound, based on the user’s selection (reverb, hall, bass, … etc). You can achieve that using the decorator pattern as follows: When the user select the sound he wants to play, you would instantiate a base sound object with the sound file, and set a variable “AudioStreamer playingSound;” to that object. The Sound object implements the interface “AudioStreamer”, which simply defines a method that takes in an audio stream “stream(Audio a);”. We would also write classes, like “ReverbFilter”, “AcousticFilter”, … etc that all implement the “AudioStreamer” interface. So, when the user enabled reverb effect, all we have to do is: “playingSound = new ReverbFilter(playingSound)”. Now, when we play the sound, we go through the reverb effect class, which adds the effect to the sound object found within.


Facade

Use case: ★★★
Elegance: ★★★


Overview

In the facade pattern, we are simply trying to reduce a complicated system into a single class that can be easily used by the client. That’s all there is to it, really. (I wonder if it is just me, or these structural patterns are boring compared to behavioral patterns.)

Examples

You have downloaded this shiny new SDK for this new technology you have, and you want to get started with the device ASAP, but you realize that there are TONS of classes, and they are all interlinked. If you want to play audio on the device, you first have to query the kernel for that resource, and get permission, and then do some I/O to fetch the sound data, and encode it using another class to a suitable format for the device, and then execute a blocking call to the audio hardware to play the sound… You might as well go do something else, right? OR! You can write this facade object and implement these steps in a function called “playSound(s)”, and now you can use this facade to easily play sounds in the rest of your application.


Flyweight

Use case: ★
Elegance: ★★★★


Overview

Flyweight is kind of awesome, but super specialized. You would basically use a flyweight to support large number of “heavy” objects. By using the flyweight pattern, you would actually cause these objects to have a “weight so light, they almost fly”, hence the flyweight name. How can we turn these heavy objects to lighter ones? We simply separate the object’s heavy/reusable parts from the light/configurable parts. The heavy part is cached and is unchangeable, while the lighter part is easily changed and created.

Examples

If we had a game with 1000 sprites, where each sprite is either a dog, a cat, or a unicorn, we can make our sprite class a flyweight object by making it hold a reference to the image data, instead of creating one for its own. So, when you instantiate a cat object, it would go through the cache FIRST, and try and get the image data from there. The position, anchor point, … etc of the sprite, however, are instantiated each and every time, which makes sense.


Conclusion

I apologize for the crappy work I did here in this particular post, I sometimes thing I would’ve been better off holding it till I actually feel like writing about design patterns (Now, I sooooo want to write about web app development). Anyways, this is out of the way, at least, and there is one more set of patterns to cover (creational)… Or wait, there is also the bonus patterns, which should actually be awesome. Until then, stay hungry, stay foolish!

Terminology! [WSGI]

This is part of the Terminology series.

Wikipedia: http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface

WSGI is Web Server Gateway Interface, and is mainly a standard for Python web applications and frameworks to talk to the web server. The idea came from the incompatibility that was brought from the diversity of Python web applications and frameworks. Each application should be supported explicitly by a service provider, or you would be completely out of luck to use that framework with this provider… Well, that sucks. Up until WSGI came along, and told both parties, let us sandwich an interface layer that abstracts the web server from the web app, eliminating any compatibility issues. The interface does NOT support neither the web servers nor the web frameworks. The web servers and web frameworks are suppose to be WSGI compatible (Or so did I understand). So, the effort is carried by the servers and frameworks.

Terminology Series

My efforts to actually remember all these terminologies I am coming across on a daily basis are fruitless (Especially these days because I am delving into the world of web development). After some deep thought and consenting with my inner self, I came to the realization that I would be better off writing a blog post about EVERY single new thing I learn about ASAP. Bonus points for you if you read it and discuss it here, since that will help us both cement these terminologies…

So, whenever I write a new blog post regarding a new terminology, the title of the post shall conform to the following RFC standard. To put it simply, the title would conform to the following regex expression: Terminology! \[.{1,26}\]. Yeah… That’s all! The first terminology of the series is coming up next!