Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

29
Mar

inline bool isprime()

This is one of the more simple snippets I could actually write, and one of the best memorized pieces of code that I can actually write as the starting post of this blog. For interested bloggers who would want to be able to post their snippets here, contact me (Dean Michael Berris) through email (see page description for updated email information).

inline bool isprime(unsigned long int number)
{
  if (number <= 3)
    return true;

  if ((number % 2) == 0)
    return false;

  for (unsigned register int i = 5; i * i <= number; i+=2)
  {
    if ((number % i) == 0)
      return false;
  }
  return true;
}

Comments and optimizations most welcome.

creative commonsThis work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

Popularity: 6%

28
Mar

C++ and Java Context Switch

The past couple of days, I had been working on a project which requires me to write Java code. OK, I know, this is a C++ blog — this
is my blog after all — but there’s something I’ve picked up a couple of days that I would like to share. I found a few important hints as to
how maybe C++ can get a boost in popularity and usability (or market infiltration). I’ve compiled a short list:

  • Libraries!
    We need more libraries. Java thrives because of the libraries and frameworks, and packages, and middle-ware, and other things that make it very rich to use. It doesn’t even allow operator overloading, but writing classes day in and day out over and over again is not fun, which is why people actually pay for libraries and packages.
  • A really cool IDE!
    Java has IntelliJ and the Eclipse project which allows developers to write code easily. I believe it’s the age of the short-attention-span-developer (which I admit to being to some extent) where we want instant gratification. I love how ctrl+tab will move to the next word boundary instead of the next space: perhaps before `i’ in `some_idea’ instead of after the `a’. Code folding is great, especially if it’s automatically done for you (and automatic/assisted imports) with a key combination. I’d like to see something better than Microsoft’s Visual C++ IDE (haven’t used others yet, but they are just too expensive for a developer in the Philippines).
  • Cool marketing conventions! Java
    developers have more than one excuse to have their company pay for a convention somewhere because Java convention events happen everywhere! When will we have a C++Con, where we hype things up and have Intel, Microsoft, Adobe, (Google maybe?) and other C++ players where people would actually want to go to?
  • Teach C++! I’d love to teach high school students how to program in C++ — the same people who would someday want to write their games in C++. Teach the same people who will write the next operating system. Teach the same people who will shape the high performance computing systems and design the next killer application running on the new computer architecture.

These are not very technical issues that we C++ developers can do something about. I’m just personally tired of having to write in a language which I have long never liked because of the restrictions. Java is very rich and the developer community is very lively but I like my multi-paradigm programming because it just works right for my brain.

I learned Java before I even learned C++ — and I’ve never gone back on my preference, because I feel much more productive in C++ than in Java. Yes, demand is high for Java development and our company is filling a niche in the Philippines (high-level Java training and software architecture).

Having said how Java is very successful marketing wise, I guess there are some technical issues that seem to have merit based on the Java design. Here are a few things that other languages have that C++ don’t which might be very interesting to see in the future:

  • Portable Bytecode is a very interesting concept. Perhaps we can use a single bytecode compiler from standard C++ code and just "distill" that for the target platform. Nope, I don’t like the idea of the VM/Interpreter, but I like the idea of a common bytecode.
  • Standard ABI might be harder to pull off, but if Microsoft starts by implementing a single Application Binary Interface — they’ve already done this with .NET and CLR, but they still have an interpreter/runtime embedded in the OS — then perhaps other operating systems will follow suit. To simplify (which I think is bordering on another anti-trust lawsuit if MS does implement this): "your compiled code should only look like this so that it works with everything else".
  • Free Standard C++ Compiler which implements the whole standard and works on all supported platforms and produces a Portable Bytecode and implements the Standard ABI. This is what made Java successful, because in the beginning only one compiler and interpreter was available — which practically gave them complete control over the language. Perhaps if Microsoft implemented a C++ compiler on all imaginable platforms instead of just implementing for their platform, perhaps they’d have a control that Sun
    has on the Java language. Maybe the GNU C++ compiler might be a good candidate, but a lot of people (like me) get burnt on non-Linux/Unix platforms with it that it just doesn’t feel right to use them on other platforms aside from Linux/Unix.

Consider this a wish list, but it’s more a suggestion list — or a call to other developers who can do something about it — for the people in position who have the capability to do something about the C++ proliferation and C++ marketing. I feel passionate about this because I feel C++ has so much more to offer as a programming language than just the traditional object oriented C that people get taught and keep hearing about.

I hope someday I can do something about this in a bigger way.

by Dean Michael

creative commonsThis work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

Popularity: 5%

27
Feb

Composition Over Inheritance

Several Patterns books will always say that composition is preferred over inheritance, because it makes your code more reusable, and more flexible. Let’s see a usual example of this in C++, using pointers or references:

class my_object {
private:
  other_object * _p;
public:
  explicit my_object (other_object * p) : _p(p) { };
 
  void do_something() { _p->do_something() };
};

This allows the user to define the functionality of my_object’s do_something method during runtime by passing in a pointer to an object that’s of type other_object or an object that derives from (or inherits from) other_object.

Sounds like a disaster because in C and C++, you can cast a pointer to anything into a pointer of another type. Let’s see how someone might be able to try doing this:

int b;
my_object a((other_object *)&b);

Disaster! And not to mention, bad coding style… We can go about it by using a reference instead of a pointer to avoid this abuse:

 
class my_object {
private:
  other_object & _r;
public:
  explicit my_object (other_object & r) : _r(r) { };
  void do_something () { _r.do_something() };
};

This is still dangerous because someone can actually do something like this:

 
int b;
other_object * p = (other_object *) &b;
my_object ( *p );

Which will compile. What we want really, is to enforce that the implementation of do_something is passed on to a concrete implementation that actually *does something* (pardon the pun). How do we achieve that to prevent mis-use? We use templates:

 
template <typename>
class my_object {
private:
  do_trait _r;
public:
  explicit my_object ( ) : _r() { };
  void do_something () { _r.do_something() };
};

NOW, with this, the code will only compile if and only if the type defined for do_trait has a default constructor, and a method that implements do_something(). We then restrict the use of the object during compile time, such that we don’t need to pass the implementation during runtime — which is usually where the problems occur.

The only way we can use the object then, is to provide a conforming type for do_trait when we want an instance of my_object that has a do_something that behaves accordingly.

A sample of the use of the class above, is the following:

my_object<other_object> a;
my_object<my_other_object> b;

We can even make it a bit funkier this way:

 
struct my_object {
};
 
template <typename>
class my_object_templ : my_object {
 private:
   do_trait _r;
 public:
   explicit my_object_templ ( ) : _r() { };
   void do_something () { _r.do_something() };
};
 
//... somewhere in the code...
std::auto_ptr<my_object> a(new my_object_templ<other_type>() );
a.reset(new my_object_templ<my_other_type>() );

But then this still leads us to the same problems as before — though now, we have a re-usable composite implementation, which has a common interface to do_something(). That way, we can re-use this implementation wherever we might need a place where an object implements a do_something() method.

Makes sense? Questions and comments welcome. :)
by Dean Michael

creative commonsThis work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

Popularity: 6%

26
Feb

A Simple Timer…

I got inspired by an officemate’s suggestion (thanks sir Chie) to make a tool which allowed you to invoke a command and have it timed to the second. This is because we needed a tool which would run a script in a predetermined number of seconds, and cron was too clumsy to use. So with his idea, I came up with a piece of software (under the GPL) which allowed you to invoke any application (or command) every N number of seconds.

The application was pretty simple, but I am posting the code here for the general public to look at and use for their own purpose. (This application is under the GPL, and if you’re interested in using the application or getting the actual sources, email me to get the package.

I am still applying for space on sourceforge (or some other hosting maybe here in the Philippines for it). Enjoy!

/* timer — a timed command invocation tool. Copyright (C) 2005 Dean Michael C. Berris, et al This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
 
#define VERSION 0.1
 
void gnu_info() 
{        
  std::cerr << "timer version " << VERSION << ", Copyright (C) 2005 Dean Michael C. Berris et al\n";
  std::cerr << "timer comes with ABSOLUTELY NO WARRANTY; for details readthe file `COPYING'.\n";
  std::cerr << "This is free software, and you are welcome to redistribute it\nunder certain conditions; refer to `COPYING' for details.\n\n";
}
 
void usage(char * argv[]) 
{        
  std::cerr << "usage: " << argv[0] << " (time in seconds) (app to run)\n";
}
 
int main(int argc, char * argv[]) {        
  // run the argv[2] command every arv[1] seconds        
  gnu_info();        
  if (argc < 3) 
  {                
    usage(argv);                
    return (-1);        
  }        
  long time = strtol(argv[1], NULL, 10);        
  pid_t pid;        
  int status;        
  std::string command = argv[2];        
  for (register int i = 3; i < argc; i++) 
  {                
    command.push_back(' ');                
    command.append(argv[i]);        
  }        
  while (1) 
  {                
    pid = fork();                
    if (pid == 0) 
    { 
      // child                        
      int ret = system(command.c_str());                        
      exit(ret);                
    } 
    else 
    {                       
      sleep(time);                        
      wait(&status); 
      //wait for the child to die                
    }        
  }        
  return (0);
}

Comments and optimizations welcome.

by Dean Michael

download the above source code

creative commonsThis work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

Popularity: 4%