My Development Space

Yet another Space on C++,Java,Open Source & Software Development!

Pointer++ : A look at Three Enhanced Pointer Libraries

with one comment

What’s wrong with Normal C++ Pointers ?

Normal C/C++ pointers give a great power to the programmer. They allow the programmer to control memory blocks and write efficient code.

Yet, and as the old saying: ” with Great Power .. Comes Great Responsibilty!”, C++ pointers are hard to use and even harder to debug.

There are 3 main issues that make pointers such a pain:

  1. Memory Leaks : that is, Forgetting to release the memory location held by the pointer when done. check out the folloing Code:

    int sumArray()
    {
    int sum = 0;
    int* myArr = new int[10000];
    //Do some work here with the pointer to figure out the sum
    return sum;
    }

    We allocated an array of 10000 numbers BUT WE FORGOT to delete it. So, after the function gets out of the scope, the pointer itself in the programs stack will be deleted leaving the data associated with him in the heap as carbage.

  2. Dangling Pointer: This issue occurs when the memory location pointed at by one pointer is no longer valid or allocated. To demonstrate this issue, take a look at the following Code:

    SomeObj *bad_ptr1, *bad_ptr2;
    char *bad_ptr3;
    bad_ptr1 = new SomeObj();
    bad_ptr2 = bad_ptr1; // both bad_ptr1, bad_ptr2 point to the same memory location
    delete bad_ptr2; // At this Moment, bad_ptr1 points to invalid deallocated memory location, thus bad_ptr1 is a DANGLING POINTER
    {
    char someVal;
    bad_ptr3 = someVal;
    }
    //Now, after the block has been executed, and the local scope variable falls out of scope, bad_ptr3 is a DANGLING POINTER

    AS you can see, bad_ptr1, bad_ptr2 point to the same memory location. bad_ptr2 deallocated this memory segment by calling delete;
    So, if bad_ptr1 ties to use this piece of memory - which was already deallocated, it will casue the program to crash and issue a "Segementation Fault" . The Same situation repeats with bad_ptr3. it pointed to a local variable someval. When someVal falls out of scope, it got deleted automatically, So, bad_ptr3 is now pointing to an invalid memory location.

  3. Double Deallocation: it is a special case of Dangling pointer. if two pointers point to the same memory location and both deleted it. this will also cause an error. I compiled and ran a simple program that does so. and gcc 4.3 issuesd the following runtime error: "double free or corruption".

TheSolution: Enhanced Pointers

We will discuss three types of enhanced pointers that may help overcome the 3 pointer issues.

  1. C++ Standard Library's auto_ptr:

    auto_ptr is a class template provided by the C++ standard Library . That means you don't need to use any additional libraries to start using it. just include the <memory> include file.
    What makes the auto_ptr so special is it solves , by default. the problem of memory leaks. You don't have to worry about where to delete your pointer. It will automatically deallocate the memory location once the pointer itself is destroyed or goes out of scope.
    To learn how to define and use an auto_ptr, have a look at the following code:

    int *i = new int(89);
    auto_ptr x(i);
    cout< cout<<*(x.get())<

    auto_ptr is also a greedy class. It Must make sure it is the only pointer pointing to a given piece of memory. So if  another auto_ptr copies it, it will automatically point to NULL. this feature is useful to prevent Modifying the data from outside its scope, thus preventing Dangling pointers and Double Deallocation.
    take a look at the following code segment:

    int *i = new int(89);
    auto_ptr gready_ptr(i);
    auto_ptr other_ptr= gready_ptr; // gready_ptr will automatically be NULL
    cout<

    auto_ptr Pros:

    • memory leaks by automatically deleting the memory once the auto_ptr is destroyed.
    • prevents more than one auto_ptr s from pointing to the same Object.

    auto_ptr Cons:

    • Doesn't handle multiple pointers to the same object.
    • You can't mix normal pointers with auto_ptr or cast auto_ptr back to normal pointers.
  2. QT's QPointer - QT's Guarded Pointer:

    Qt is a cross-platform application development framework, widely used for the development of GUI programs. Qt is most notably used in KDE, Opera, Google Earth, Skype, Qt Extended, Adobe Photoshop Album, VirtualBox and OPIE.
    QPointer is a part of the Qt  toolkit. It was designed to overcome the problem of Dangling pointers only. a QPointer object behaves like a normal C++ pointer T*, except that it is automatically set to 0 when the referenced object is destroyed. You need to install the QT toolkit library in order to use QT's QPointer. The refrenced Class Must be a subclass of the QObject class. Have a look at the following code to see QPointer in action:

    QPointer label = new QLabel; // QLabel is a class for UI label extending QObject
    label->setText("Status:");
    ...
    if (label) // if label was deallocated somewhere else, label will point to NULL thus it will not enter the if block.
    label->show();

    QPointer's Pros:

    • prevents Dangling pointers.
    • Fully Compatible with the normal C++ pointer. you can freely mix guarded and unguarded pointers as  a guarded pointer will automatically cast to a T *.

    QPointer's Cons:

    • Doesn't handle memory leaks issue, So you still have to recheck your code for any missing delete statements.
    • Works only as a part of the QT library, You can't  use it in a simple non-QT application.
    • You can only use it refrence Objects extending the QObject class. You can't use it to reference primitive data types or Classes not extending the QObject.
  3. Boost's Smart Pointer Family:

    The Boost C++ Libraries are a collection of  open source libraries that extend the functionality of C++.Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time.They can also be used to keep track of dynamically allocated objects shared by multiple owners.
    Boost provides the following smart pointer implementations:

    1. scoped_ptr:
      a pointer automatically deleted when it goes out of scope.
      scoped_ptr is uncopyable, thus no assignments possible. The following Code demonstrates the specs of the scoped_ptr:

      #include
      #include
      using namespace std;
      using namespace boost;

      int fn()
      {
      boost::scoped_ptrptr(new int(90));
      *ptr=300;
      cout<<*ptr< boost::scoped_ptrptr2(new int(900) );
      ptr2 = ptr; // COMPILE ERROR! You can't copy the scoped_ptr to another one
      // NO NEED to delete ptr, it will autodelete itself when it goes out of scope
      return 0;
      }

      scoped_ptr Pros:

      • Handles Both Memory leaks and Dangling Pointers issues.
      • Very fast and efficient.
      • Safer than C++ STL auto_ptr as it is uncopyable.

      scoped_ptr Cons:

      • Doesn't handle multiple pointers to the same object.
      • Cannot be used in C++ Standard Library containers. Or hold a pointer to an Array. Use scoped_array instead.
      • Not compatible with normal C++ pointers. can't mix and cast between types.
    2. shared_ptr:
      a pointer to a dynamically allocated object. The object pointed to is guaranteed to be deleted when the last shared_ptr pointing to it is destroyed or reset. The following code may provide you with a brief information about its features:

      include
      #include
      using namespace std;
      using namespace boost;

      int fn()
      {
      boost::shared_ptrptr1(new int(90));
      boost::shared_ptrptr2 = ptr; // copying is allowed for shared pointers, So both ptr1 & ptr2 point to the same memory segment
      cout<<*ptr2< *ptr2 = 7000; // now both ptr1 & ptr2 point to 7000
      cout<<*ptr< ptr.reset(); // means: delete ptr;
      cout<<*ptr2< return 0; // ptr was deleted previously - when calling reset(), and ptr2 is now out of scope, SO, the memory location IS DELETED AUTOMATICALLY
      }

      shared_ptr Pros:

      • Handles Both Memory leaks and Dangling Pointers issues.
      • Handles multiple pointers to the same object with reference counter.

      shared_ptr Cons:

      • Cannot correctly hold a pointer to a dynamically allocated array.Use shared_array instead.
      • Not compatible with normal C++ pointers. can't mix and cast between types.

    Final Conclusion:

    • You can overcome pointers issues using the new pointer types.
    • If you don't want to use any external libraries, STL's auto_ptr is the best solution for you.
    • If you are writing a QT application, QPointer will be a very helpful utility.
    • If it is OK with you to import external libraries, boost smart pointer family is the ultimate solution.

Written by topquarck

May 23, 2009 at 12:33 am

Posted in c++

Tagged with , , ,

10 Ways to Improve Your Code

with one comment

I’ve just finished   watching a very interesing presentation recorded during QCon SF 2008. it was delivered by Neal Fred. a senior application architect at ThoughtWorks. He is the author of a lot of development  books i wanted to share it on the form of points in case someone doesn’t have time for watching the presentation.

So, let’s begin
**************
**************

10 ways to improve your code:

1. Use Composite Methods: divide the program into SMALL general methods, each of them carries on ONE identifiable task. This will result in a program of small methods with few (6 to 7) lines each
the Benefits:
a. Refactoring will be much easier, imagine refactoring one method that connects to a DB, performs a query against the DB  and fetches the  data. Nightmare isn’t it!!    So, to apply the composite method concept with the previous case, we will create 3 small methods each of them doing ONE task, one for opening the DB connection, one for querying the DbB and the last one is for handling the ResultSet, then you call these 3 methods on your original method that used to do everything on by itself.
b. Making the methods as abstract as possible helps in reusing them.
c. Unit Testing Small dummy methods with one task to do is easy.
d. Method names will become documentation.

2. Do TDD (Test Driven Design/Development): Test Driven Development means writing Test before writing the code ( the test Class is the first consumer of the class).
the Benefits:
a. building the test affects the Design of the actual application. it tells you wah u need exactly before doing it.
b. Better interaction/integration between the app components. assume you want to create a customer class that uses an Order class, So, when you test-first, You are forced to think how customer will interact with order AT design time before you write any code for both classes. that kind of thinking eliminates alot of the integration problems that occur when you write the 2 separate components and try to use them in the real world.
c. encourages you to write Composed methods: by writing a simple small method to pass the test and evolving it till it becomes ready.
d. TDD code tends to be cleaner and has a better complixity.

3. Do Static Analysis: there exist some tools to do some analysis of code written in almost every programming language. for example “FindBugs” does Byte-code- level analysis of java code. It  is able to find bug patterns that might be in your code.

4. Assure Good Citizenship between classes: make sure that Classes interact with each others in a civilized manner. Don’t Mix static and state methods in one place. Singleton Pattern is evil !! it is the OOP alias of the Global variable we used to use back in the days. the problem with singleton is that it mixes the states and the static methods together. it is hard to test/debug. mixes responsibilities.
the alternative to using singleton:
create a Plain object POJO that holds the state, Logic ..etc
and then create a factory to create one an only one object of that POJO and insure that.

5. YAGNI : You Ain’t Gonna Need It!. Write only and only write theings that you actualy need. this minimizes the Complixity of the application – it will grow by time as specs change, so don’t make it even more complex in advance! – . Don’t create your OWN FRAMEWORK or reinvent the wheel. the Best frameworks are the ones Harvested from existing code ! because at least they proved to work once, the concept of Composite method is one case of that harvesting.

6. Question Authority: alot of things are taken as they appear. without raising questions,Why is that done that way. IT’S THE COMPANY POLICY/CULTURE. they tend not to break that things so-called culture without even knowing why are they culture.
ex: managers think pair programming produces code half as fast. But studies show that although it is 50% slower, it is also 50% less in defects and much higher quality.
THE POINT is: dont take everything for granted. DO explore and make expierments. find the goog points and push them to their extreme.

7. SLAP (Single Level Of Abstraction Principle): every thing should be in the same level of abstraction.

8. There are other Languages/frameworks that can solve this particular problem better: it is a common mistake to think that one programming language can do everything with ease. writing MAssive multithreaded code is hard in Java/.NET. instead, use a functional language that runs on the same platform – JRE as in Jaskel or the .NET as in F#-.
the point is: Be smart and use the most appropriate tool to give you the best solution to yout problem.

9. Explore the Backalleys/hidden doors: learn the special features of the language. it will make you solve unusual problems sharper. things like Reflection/regular expressions… etc can save the day. then spread your knowlege to others in the project.

10. Anti-objects: change your perspective, they way you look at the problem and don’t get stuck in one methodology/way of thinking to solve all your problems. it might not give you the optimal solution to the given problem. Sometimes unusual solutions that dont stick to a uniform way of thinking work best.

******************************
*****************************

the presentation : http://www.infoq.com/presentations/10-Ways-to-Better-Code-Neal-Ford

Written by topquarck

April 17, 2009 at 8:32 pm

Posted in soft skills

Becoming a better developer

with one comment

Yesterday, I listened to a great podcat presented by the folks at High Of Coding about how to become a better developer.The podcast introduced many easy-to-follow steps to enhance your software development skills.

I really liked that podcast, So, I decided to summarize it in 10 points and share it.
So. let’s begin …

  1. Love Coding:

    If you don’t have passion for coding, you won’t become a batter developer. you need to take a look at programming and ask yourself:  is it my passion or just a way to get my pay check ?

    "5:01 developers" are  the developers who once it gets5:00 pm is over, they  just close the laptop lid and never open it till the next morning.

    YOU must dedicate one hour daily to develop your coding skills.

  2. Keep updating your skills :

    the IT field is the fastest changing field, new technologies emerge every day, get to know them, update your knowledge constantly.

  3. Be a part of a community:

    Register to forums, discussion boards, user/developer groups. Ask  questions. Answer others’ questions.
    Usually  the problems posted in discussion boards are real-life and you may encounter them  in the future.

  4. Read technical blogs/magazines :

    They  tell you what is going on in the industry, give you great ideas on how things are done.

  5. Start your own project :

    Even for fun. You will see when you are in the process of making your own project, many questions come to mind  of how things are done: how to UI design, what version control system to use, how to design the project , how to unit test it, how to build it, what technology/framework  is relevant to use … etc.
    you will find that your knowledge of alot of fields/areas has grown.

  6. Learn design patterns/software architecture:

    patterns are very important in the software process. there are dozens of patterns
    out there – not just MVC – . learn and apply as more as possible .

  7. Learn to write efficient code :

    don’t repeat/copy-paste the code , it will make problems while refactoring. learn to reuse the code.

  8. Attend events as possible

  9. Present topics/give sessions if possible:

    it will not develop your programming skills, but it will develop your skills as a speaker. contact with the real people, listen to
    others asking, find out what problems face people.

  10. Do code reviews :

    review others code and get others to review your code. this way you will get to find other points of views,
    other ways to solve the same problems, better performance solutions ands so on

The link to the original podcast : http://highoncoding.com/Articles/514_Becoming_a_Better_Developer.aspx

Written by topquarck

March 2, 2009 at 6:27 pm

Posted in soft skills

Tagged with

The Observer Pattern

leave a comment »

As programs grow and get more complex. the Communication between classes problems grow bigger and bigger.
to deomenstrate the two-way communcation Problem, consider the followuing example:

A Window object contains one or more UI objects inside it, say a progress bar.  So, the Window object contains a progress bar object inside it as a memeber variable. The window object has a complete control of the Progress bar object – because it owns it !!. So, when the window object wants to Communicate with the progress bar, it will simply call one of  its  methods. BUT WHAT to do if the progress bar object wants to Communicate with its parent Window??

The Observer Design Pattern is the pattern to solve such problems – among other similar problems. It allows 2-way communication between multiple Classes.  The pattern consists of the following participant classes:

  1. Subject: This is an interface to provide the methods that allow the progress Bar object to communicate with its Container Object – the Window-. The Subject interface provides the following APIs:
    • Attach() : to add an observer to track my changes.
    • Notify() : this method does the actual Communication between the Class and the Observer(s).
  2. Concrete Subject: the Actual class that needs to inform its owner with the change in its state, in our case, it will be the Progress Bar object.
  3. Observer: The interface that provides the ability to listen and react to the sent messages from the Concrete Subjects. it has a very important abstract method called update() which is Called by the Subject when sendin a message.
  4. Concrete Observer: this Class is the One Listening for the messages sent from the Concrete Subject object. It is the Consumer of its messages.

The following Class Diagram shows the classes of the observer pattern:

the Class Diagram of the Observer pattern

the Class Diagram of the Observer pattern

So, the following scinario occurs when applying the pattern :

  1. The Concrete Observer – the Window Object in our example- owns the Concrete Subject – the Progress Bar – and can communicate with it via calling its public methods. The normal Case
  2. When the Concrete Subject – the Progress Bar- wants to communicate with a Observer – the Window, it will Call its inherited method notify() – the mothod in the interface Subject-, the Notify() method will look for all observers and call their update() methods.
  3. The message has arrived to the Observer(s) – in our case, the Window Object. and we acheives the 2-way communication.

Java has provided the mechanism to make it easy for us to implement the observer pattern.The Subject and Observer are generic interfaces interfaces. So, we can write them only once and implement them in our actual code.
Java – since JDK 1.o- provided an interface called Observer that has only one abstract method called update(Observable o, Object arg).

Java also provided a class Observable that contains the APIs used to communicate with the classes implementing the Observer interface – i.e call their update() method-. The Most important APIs are:

  1. addObserver(Observer o)
  2. setChanged()
  3. notifyObservers()

Let’s see the following Java example that demonstrates how to use the Observer/Observable classes.
In this example we have 2 Classes: BigClass and Sub. Normally, the BigClass object has a member of class Sub. We will make the sub Object count from 1 to SIZe, and if it reaches a given number- say 4 – it will notify its owner class – the BigClass object- that it has reached the given number

//*********** BigClass.java ***************//
import java.util.Observable;
import java.util.Observer;</code>

public class BigClass implements Observer {

private Sub theSub = null;

public BigClass(Sub theSub) {
System.out.println("in  the BC constr");
this.theSub = theSub;
}

public void startCount(){
theSub.startCount();
}

public void update(Observable obs, Object obj) {
if (obs == theSub) {
System.out.println("the value: "+theSub.getValue()+" was reached!");
}
}
}
//************** Sub.java **************//
import java.util.Observable;

class Sub extends Observable {

private int n = 0;
private final int SIZE = 100;

public Sub(int n) {
System.out.println("in the sub cons");
this.n = n;
}

public void setValue(int n) {
this.n = n;

}

public int getValue() {
return n;
}

void startCount() {
for (int counter = 0; counter &lt; SIZE; counter++) {
if (counter == this.n) {
setChanged();
notifyObservers();
}//end if
}//end for loop
}//end method
}

and now, we will use them both in the main method

public class Main {
public Main() {
Sub theSubObject = new Sub(45);
BigClass theBigObject = new BigClass(theSubObject);
theSubObject.addObserver(theBigObject);
theSubObject.setValue(44);
theBigObject.startCount();
}

public static void main(String[] args) {
Main m = new Main();
}
}

look at the code; we created objects for both Classes BigCalss, Sub. then we Told the Sub object to set the BigClass Object as its Observer :
theSubObject.addObserver(theBigObject);
Then, we started Counting ….. now, if we stumbled upon the given value, the Sub object will notify its observer – the BigClass Object by following sequence:
setChanged();
notifyObservers();
this sequence will send the message to the observer Object – the BigClass in our example.

As you can see, it is very easy to implement the observer pattern using java.

Written by topquarck

February 15, 2009 at 11:30 pm

A look at Gnu Compiler

with one comment

Gnu Compiler  is one of the strongest and most widely used Compilers today. it is known for its power, flexibility, portability and wide architecture support.

Simply; you can use Gnu Complier on any unix/Linux, Windows or Mac.

you can also compile programs for a wide range of platform, including intel, AMD, ARM, PowerPC, SPARC …etc

Gnu Compiler support Languages like C, C++ (g++), Objective-C, fortran (gfortran), java (gcj), Ada , VHDL ……. use your imagination!!

So, let’s take a look at the architecture of the gnu compiler collection

Gnu Compiler is divided into 3 main components:

  1. front-end.
  2. middle-end.

  3. back-end.

We will take a closer look at theses three Layers:

  1. The Front-end:

    This layer is Language-specific, architecture-neutral to handle the source code file.

    Depending on the programming Language used to write the code , we choose the appropriate fornt-end.

    for example: for C++ source files we use g++, for java files we use gcj …..

    The purpose of the front end is to read the source file, parse it, and convert it into the standard abstract syntax tree (AST) representation. The AST is a dual-type representation: it is a tree where a node can have children and a list of statements where nodes are chained one after another.

    INPUT : the source code , a text file contains the program to be compiled.

    OUTPUT: a tree-like representation of the source code. Also called the Abstract Syntax Tree (AST).

  2. The Middle-end:

    Language-neutral, architecture-neutral layer for enhancing/optimizing the tree representation of the source code (AST). and generating a register-transfer language (RTL) tree. RTL is a hardware-based representation that corresponds to an abstract target architecture with an infinite number of registers. So, RTL looks like Assembly code BUT IT ISN’T. it is more like architcture independent assembly. Code optimization is done in this stage, eliminating dead code – code can’t be executed – replacing some segements of code – the RTL – with faster segments and so on.

    INPUT : Abstract Syntax Tree (AST).

    OUTPUT: Register Transfer Language (RTL).

  3. The back-end:

    A Language-neutral, yet Architecture-specific layer that generates the assembly code for the target architecture using the RTL representation -from the previous phase. the back-end stage has a description file for each hardware architecture that includes information about what’s available of the processor – the actual registers and so on. these descriptions are used to map the RTL instructions to the actual and appropriate assembly segment. As you can see, this phase tells us why gnu compilera are flixible, efficient and portable. for each chip/family, you can have a description file that tells the compiler WHAT availbale and how to use it. So, the compiler generates a very efficient assembly code for each processor chip.

    INPUT : the RTL

    OUTPUT: the Object file – the executable file

the following figure explains the output of each component :

the output of gcc stages

the output of each compoenet of the gcc : 1)AST 2)RTL 3)Object Code

Written by topquarck

February 14, 2009 at 2:38 pm

Posted in c++, compiler, open source

The Great Amarok !

leave a comment »

Among all the media player i have used in both Linux and Windows, Amarok is my Number one Music player. I really like its interface and ease of use.

the new amarok 2 which comes with the new KDE 4 desktop environment makes my experience even more exciting.

the main features i like most about amarok are:

  • Last.fm integration : i can listen to last.fm online music without having to use my browser, I just have to insert my login info Only ONCE to amarok, and Amarok will login automatically every time i use my last.fm playlist, import my favourites and play them. I can also through amarok, ban unwanted tracks, mark others as my favourites and even skip other songs.
amarok - last.fm integration

amarok - last.fm integration

  • System Tray control : this feature is common in all the media players that are part of the KDE4 desktop, if you want to jump to the next Track, and the player is Docked to the system tray, just RIGHT click amarok’s system tray icon, and you will find the shortcuts you just need : play/pause, net track previous track … etc

    amarok - System tray Shortcuts

    amarok - System tray Shortcuts

  • The Lyrics applet : Yes, you can view the lyrics of the track while it is playing , when you run a track, Amarok will automatically fetch its lyrics from the internet for you!

    amarok lyrics applet

    amarok lyrics applet

  • The Wikipedia applet : WoW ! while you are listening to anoe track, again Amarok, the Great will go to wikipedia and fetch the wiki page of the songer/band of the song !!!!!

    amarok wikipedia applet

    amarok wikipedia applet

  • The script Manager: Amarok was built to support plugins < the same idea of firefox, you can extend, enhance and add new third party features to Amarok > . Amarok script manager allows you to activate/deactivate scripts/applets < like the lyrics applet we just talked about > install/uninstall scriprs and download new ones.

Don’t You Agree with me that Amarok is a GREAT audio player ??? So, I must say I LOVE KDE4 !!

Written by topquarck

February 5, 2009 at 9:19 pm

Posted in misc

Tagged with ,

Hello world!

leave a comment »

hello there !!!

welcome to my new WordPress blog

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Written by topquarck

February 5, 2009 at 1:25 pm

Posted in Uncategorized