An efficient and simple object factory for PureBasic

Posted by on May 3, 2009

Whenever you deal with structures and what have you it’s obvious that there has to be a better way of doing it. Think about it, you encapsulate your structure-related code in such a way that it becomes clean, nice and tidy — in other words it makes it easy to understand what it does.

However in essence, you end up writing pretty much the same allocate / deallocate, list, etc. code every time you incorporate a new “class” into your project. Why should we?, let’s avoid it all together and focus our efforts in the task at hand rather than in the mundane stuff.

If you open your eyes you’ll see that this is an obvious pattern but what isn’t so obvious is how do you implement a template that deals with it in an efficient and clean way within the current constraints of the language.

Well… Have no fear, EasyObject is here!
First, download it. Secondly, embrace it.

Third, you’re free to post any comments regarding on how to enhance it if you dear to!.

Ok, now let’s describe this thing a little more and leave the marketing speech in the past.

From the “readme”:

EasyObject is an object factory template for PureBasic. It allows you to register any structure as a “class”. With EasyObject you can define constructors and destructors as well as iterators with ease.

The purpose of EasyObject is mainly to encapsulate trivial and redundant code usually regarded to allocation, deallocation and keeping track of the objects. The usage is fairly simple: classes can be registered and unregistered. Once a class has been registered, we can create new objects and delete them at will. If we decide to unregister a class, all of the objects will be freed and their respective destructors will be called.

More from where that came from…

Macros in this case are used as an aid to define templates (like you would in C++ for instance). There are certain limitations that forced me to design the template as it is right now but the usage is very simple. We’re not trying to mimic any language here but rather provide a way of dealing with objects without having to write redundant code all the time. Because overloading doesn’t exist in PB, the constructor will be called twice (once by the template and once by yourself) if you want to define the members using said ctor, just make certain that any dynamic allocations are performed only once or you’ll have a nasty memory leak in your hands.

It’s clear that some limitations are present in the template but for most of the tasks this is a great addition to anyone’s code.

Let me know if you find any bugs!

Cheers,
GuShH