Posts tagged with "programming"


Java enhanced for loops for UTS peeps

A very good friend of mine at UTS and on The Twitters asked about enhanced for loops in Java. I think he understands what's going on now, but just in case I'm putting an example up here!

Caveats

  • In the real world, we don't really use primitive arrays in Java anymore, but given UTS still teaches them for some reason, they'll do for our example here!

  • For some reason I got into the habit of including the above picture from Railgun into my programming posts. Presumably because there's a laptop involved, and I can't stand dry posts without pictures! But I digress.

Regular for loops

Say we wanted to create an application that stores a list of moeblob character names into an array, then print each name out to the screen.

public class EnhancedForLoop
{
  public static void main(String[] args)
  {
    String[] keion = new String[3];
    keion[0] = "Mugi";
    keion[1] = "Yui";
    keion[2] = "Azusa";
 
    for (int count = 0; count < keion.length; count++)
    {
      System.out.println(keion[count]);
    }
  }
}

As you can see, we created an array and populated it with character names. We then used a for loop and printed each character by referencing them one by one.

There's a simpler way!

There are circumstances where a traditional for loop would be preferred (and needed!), but if all you want to do is traverse an array one by one, there's a simpler way!

for (String name : keion)
{
  System.out.println(name);
}

In this loop, instead of referencing each array element by a number, it traverses the array one by one for us, and stores the current element in a temporary variable. In this case, each element in our "keion" array gets put into our temporary "String name" variable! :D

As you can probably tell, for going through an array one by one, an enhanced for loop is:

  • shorter and easier to write
  • the statements in the loop are easier to read, make more sense
  • you don't need to know how many elements there are
  • you don't need to do any maths!

These kinds of loops are common

I'm not sure if you've done any scripting, but enhanced for loops are huge in languages like Perl, Ruby and Python. My personal favourite is the former ^_^

#!/usr/bin/perl -w

use strict;

my @keion = qw/Mugi Yui Azusa/;

foreach my $name (@keion) {
    print("$name\n");
}

A legitimate software question from my sister

Icon from the Tango Desktop Project

ARGH! Why can't the same software run on everything?!

Of course as developers we know why (the lowest common denominator problem, patents, turf wars), and can point out failed attempts to change this (*cough* Java), but sometimes it helps to see a less technically proficient user's take on what we've developed as software folk.

I suppose that's where web applications have the potential to shine, provided we move enough people onto standards compliant browsers. I very much doubt we'll ever have a consensus on a standardised desktop API, though I suppose Win32 came awfully close with a de facto one ;).


Oniguruma for Ruby 1.8.x

The Ruby Programming Language

Want Ruby 1.9's default regular expression library in your existing Ruby 1.8.x series code?

# gem install -r oniguruma

According to the project's site, its mature. Wish I was.

s/Ruben is super witty/Ruben probably isn't/


Perl 6 Rakudo Star

So it looks as though Perl 6 might be coming soon... again!

#!/usr/bin/env perl -wT
use strict;

&sayWooHoo("again");

sub sayWooHoo {
    print ("Hey, 6 might be coming soon, $_[0]!");
}

My first job out of high school was writing Perl programs. Was the happiest time of my life, because university hadn't crushed my spirit yet. Perl is awesome. CPAN is awesome! And don't believe what they say, it is possible to write Perl programs that you and others can understand later, provided you follow the conventions :).


My latest project worked!

Icon from the Tango Desktop Project

With my dad, sis and I moving internationally again and with this latest project, I haven't had much time for blogging or tweeting these last few days. I'm really excited though, because I just finished a really unconventional project for a client and it worked beautifully!

I'm not allowed to discuss the Five W's, but suffice to say it used a lot of a certain flavour of Java and a really ancient database. I'm talking stone tablet ancient. And it worked! Yays! Alas for the sake of my anemic public resume/portfolio, this will be yet another thing I can't add to it for NDA-like reasons. Oh well, I learned a heck of a lot and got lots of experience.

Now I'll be taking a small sabbatical and helping my dad and sis move in and organise whatnot. Will be nice ToLiveWithoutLongCamelCase and dusty old manuals with yellowing pages that made me sneeze for a while ;).


Investigating Python 3 support in Fedora

height:260px; width:420px;

Having got used to Python 3.0 development on my Mac through MacPorts, I was a little surprised to find it currently unavailable for Fedora, at least in Constantine (Fedora 12, the current stable release) without any third party RPM sources.

I suspected it may have had something to do with many of Fedora's tools depending on Python 2.x, so one solution would be to do what the MacPorts folks did and implement them as separate ports, or RPMs. I'm still getting used to the lingo ;).

According to the Fedora Wiki for Fedora 13, that seems to be their intention. From the Benefits to Fedora subheading:

Fedora has long been a great platform for doing Python 2 development, but we don't yet have Python 3. Having Python 3 available via rpms will extend our Python coverage.

Note also:

  • Python 3.0 was released almost 10 months ago, on 2008-12-03, and the latest release of the 3.* branch is 3.1.1, released on 2009-08-17.
  • Other distros have python 3, though not necessarily with anything "on top" resembling the full python 2 stack.
  • We have a working, valuable python 2 stack, which is used by critical system components (yum and anaconda): we must not destabilize the python 2 stack.
  • Python 3 is sufficiently different from python 2 that we need them to be independent software stacks.
  • The Spanish Inquisition. Spam spam spam. The knights who say... the soft cushions! The comfy chair!

I can live with that. As far as Linux distributions go, I like how transparent the decision making process is in Fedora and enjoy reading their discussions, even if in this case they seem to be a bit behind.

As for me, Django still uses Python 2.x but I'd started moving some of my personal projects over to 3.x. I suppose I can keep using the -3 flag with the Python 2.6.x interpreter to warn me of any deprecated features I may be inadvertently using.


The Reinvigorated Programmer by Mike Taylor

Mike Taylor

Longer time readers of my blog here would have read my lamentations about the fall of really high quality personal blogs and the rise of homogeneous, interchangeable blog networks with hundreds of writers, so when I find an amazing personal blog I have to share it!

The Reinvigorated Programmer is written by Mike Taylor, an intensely fascinating 41 year old developer and palaeontologist, what a combination! He has a real flair for writing and an obvious passion for what he does which makes his posts even more enjoyable to read; as opposed to the posts I write here which are usually quite terrible. Admit it! :)

The bottom line here is that writing is an art. You can hack your way through to producing tolerable text without being an artist, just as an uninspired programmer can bash his way through to wiring together an uninspired web application. But just as it takes a Ken Thompson to invent and write UNIX, and a Dennis Ritchie to invent C and write the initial compiler, so it takes a Brian Kernighan to write The C Programming Language.

And it takes Mike Taylor to write The Reinvigorated Programmer. :) His blog covers programming ranging from classic and fully working BASIC applications for the Commodore VIC-20/VC-20 to C, Perl, Java and Ruby along with some of his other interests including (but not limited to) Buffy the Vampire Slayer and the latest Doctor Who. That reminds me, I need to check that out. I really liked Tennant, but people say the Eleventh Doctor is pretty good too.

As I've said about Jim Kloss, the lead developer and guru over at Whole Wheat Radio, if I turned out to be even half as interesting, intelligent and friendly as people like Mike Taylor I know my life would be set. People like Bill Gates and Larry Ellison aren't my heroes and idols, they're people like Mike.

By the way, the photo above is of Mike and his three sons sitting in front of... a whale skull. Amazing!


Dr Karl answers your programming questions

Dr Karl

One of the world's best dressed and most friendly scientists, Dr Karl answered a question about muscle exhaustion.

Why do arm muscles get tired? @maxiewawa Mmm. Ca++ exhaustion, glucose exhaustion, lactic acid overload, neurotransmitter exhaustion, etc.

I can relate, whenever I write C++ code I get severe muscle exhaustion in my fingers and brain ;-).

By contrast, Java shifts some of that mental exhaustion from the brain to the fingers WithItsExcessiveCamelCaseMethods. I think wrapper methods saved me from serious finger ligament damage and carpel tunnel syndrome.

This post that I constructed entirely out of an intentionally misread quote was brought to you by a Grilled Cheese Sandwich.


Main methods in Python, Ruby, Java stuff

Main Street

I've decided to put my code snippets blog idea on hold because I don't have time to be maintaining a separate blog right now. Had I started it, this would have gone there.

Not having main methods never used to worry me, but since studying Java again I really like being able to have an application kick into action without having to create an instance of it manually.

To illustrate what I mean, here's a crappy Java application that I merely have to execute from the command line for it to display Bender's favourite words.

MainInJava.java:
public class MainInJava
{
  public static void main(String[] args)
  {
    System.out.println("Kiss my shiny metal arse");
  }
}

Now here are roughly equivalent applications written in Ruby (my formerly favourite scripting language) and Python (my formerly favourite scripting language, and now my favourite scripting language again!):

MainInRuby.rb:
#!/usr/bin/env ruby -w

class MainInRuby
  def initialize()
    puts("Hello, world!")
  end
end

MainInPython.py:
#!/usr/bin/env python -3t

class MainInPython:
    def __main__(self):
        print("Hello, world!")

If you were to run either of these example applications, nothing would happen. The initialize and __main__ methods aren't run because merely running the application doesn't do any instantiation. Ruby and Python expect you to create and run an instance of the application in the source.

The proposed workarounds if you really want Java-ish main method equivalents in these languages are to write these lines of boilerplate outside the class.

MainInRuby.rb:
if __FILE__ == $PROGRAM_NAME
  # Put "main" code here
end

MainInPython.py:
if __name__ == "__main__":
    main()

I understand what these functions do, but for scripting languages that pride themselves on making life easier compared to heavy languages like Java, these don't seem all that intuitive or elegant.

I suppose one could argue that I've been corrupted into thinking I need a main method and that I haven't bothered to learn the Ruby or Python way of doing things. They may be onto something ^_^.

__EXIT__


Launching my code snippet site... maybe...

Icon from the Tango Desktop ProjectIcon from the Tango Desktop Project

Given it's my birthday and all that, I thought I'd use the time to announce an announcement: I [might be] starting a new blog thingy for code snippets!

Here's what I was thinking

When I'm stuck on a problem often it isn't the huge projects people have made public online that help me, they're little code snippets that show how to do something, how something works, or that elegantly demonstrate a concept. Other times I discover or learn how to do something myself and I make a note of it. These go for programming languages, package managers, resource and configuration files, how to talk to girls... wait, scratch that last one.

Over the years I've hoarded a ton of these gems, and it occurred to me: why not make them public? I already blog way too much here, so I figured I could start a new blog where each post is just a snippet, and each will be tagged with the platform and language. Kinda like my current dotfiles folder on RubenSchade.com but with links. No extra fluff.

I'm aware of a ton of sites that let you share code snippets, but I'd prefer to keep things in house. I already import my tweets each day because the idea of having my data on a server I don't control worries me. Plus it'll be more fun :).

I'm thinking of resurrecting my old Perl FastCGI script from the old days this blog back when it was on the RubenerdShow.com domain, I wrote it to be fast and it used more crypto than a nuclear submarine, plus it works on an SQLite database which kept things simple. Come to think of it, I forget why I moved off it in the first place.

Anyway stay tuned!