All-powerful Java code snippet

26 02 2009

As a joke (but not really), I was terribly annoyed at Java today, and wrote this Java code in a few minutes.  It’s (not surprisingly) capable of accomplishing *anything*.  Give it a shot.

ProjectAttempt project = new Project();
try {
    attempt = project.codeWith(Java);
    if(   attempt.results == tooRigid
            ||
          attempt.developmentTime > acceptableThreshold) {
        // since the above condition is usually true,
        // we should expect this next line to happen frequently

        throw ExceptionallyNotGoodEnoughException;
    }
} catch (ExceptionallyNotGoodEnoughException e) {
    System.out.println(" ERROR: Java is too rigid!");
    System.out.println("Rigid:");
    System.out.println("1 a: deficient in or devoid of " +
        "flexibility <rigid price controls> <a rigid bar of metal> ");
    System.out.println(" b: appearing stiff and unyielding <his face rigid with pain>");
    // Don't bother with another try/catch block,
    // since it's impossible for the next line to fail.

    attempt = project.codeWith(Python);
    // Should always read "Impressive"
    System.out.println("Development time: " + attempt.developmentTime);
}

Smart-alec replies are welcome, but you won’t change my opinion on the matter 🙂

Advertisements




Modern Programming: Leaving Java – Part 2

16 02 2009

So, part 1 was all about our current circumstance in the world, with Java being a bit “dusty” (to use the term I used in the part 1 post) when held in comparison to the ideas backing new languages.

To recap the most important idea from part 1:  Java was a great step forward for its time, but there is of course the possibility of a better idea than Java.

Was the original brick cell phone the end-all solution for cell phones?  Heck no.  Was Compaq’s first laptop the best design, just because it was the first of its kind?  Absolutely not.

Just so, C and Java are not necessarily the best end-all solution, no matter how good you feel either of those languages is.

As I pointed out in part 1, there is a good legitimate use for (almost) every language, regardless of anything I say against any language.  Thus, Java will never *actually* disappear, just like C will never actually disappear.  I’m okay with that, but I wish to bring a better understanding to those of you who code in Java who would like to crucify people like me for suggesting that Java isn’t the best solution.

Part 2: Something of a Design Flaw

We all hate that diabolical moment when the sudden realization hits us: there’s a design flaw, and a project redesign is needed in order to accomplish the necessary task.  And it’s either a redesign, or you’ll be forced into more countless hours of trying to code your way around the design flaw, thus the code becomes convoluted, and making it impossible for the next guy to easily grasp what’s going on.

Part 1 was clean of any significant reference to other languages.  Part 2 is not.  You’ve been warned.  I’ve established the foundation of my case in Part 1, and so from this point of view, read the rest of Part 2  in conceptual terms.

If I get any replies on how to better code a Java example, then those persons have entirely and utterly missed the point of what is being presented (again).  If you are one of those persons, then I cry for you and your blindness to outside ideas.

Java’s core development effectively stopped the day the JVM was completed;  “That’s it, that’s all” (as the french Québecois say.. in english).  Once the JVM was made, the Java platform allowed for pretty much any package to be developed.  The JVM has all of its nasty internals tucked out of sight, and coders are free to make whatever code they want, and it’ll run on top of the JVM.  Yes, the JVM is probably tweaked frequently, but huge additions aren’t really in Java’s script (‘script’ as in playwrite).  Therefore, you have to “code around” the design in order to accomplish modern operations on Java’s data types.

This is generally the pattern of most languages: initial core development exits stage right, package development takes the spotlight.  So this being the case, we can’t really expect any overhaul to the JVM and how it works.  Therefore, I present to you concepts.

Programming is becoming more and more “object-oriented”, and rightfully so.  The goal therefore, is to make the code modular.  The goal of modular code is easy deployment/use all over the project’s code.  You change something in one main source file, and the changes are reflected everywhere.

Java (like a few other languages) has saturated (super-saturated?) itself with packages which define hundreds of specialized data structures for certain tasks.  This is great if you understand the fine nuances between their uses.  But frankly, naming two Classes “HashMap” and “HashTable” doesn’t clear anything up for me.  What’s the difference?  (Readers, don’t answer; it’s rhetorical.)

Python’s idea is a bit different: of course it provides certain data structures for you to use, but it decided to circumvent some of this madness.

So here’s the bottom line:  Java says “Pick your card”.  Python says “Write you own card”.

That’s probably a terrifying thought for you Java peoples.  “What?  No Hash generalization to plug into a [Concurrent]Map/Table/AttributeSet/Set ???!!?” And the same applies to Tree stuctures and the whole gang.

No, Python’s job is not to baffle you with finely-tuned data structures that you’ll never master.  Instead, Python’s “Write your own card” approach is used, and it’s surprisingly simple:  You’re going to write what you need to use, but we’re going to make it easy to do that.

Let’s start with something *extremely* simple.  My argument has more weight than this, but you’ll begin to understand soon.  Java did away with simple integer values casting into booleans for use in IF constructs.  Reasoning probably had to do with ambiguity between a ‘1’ and a ‘true’.  To avoid this, Java doesn’t cast ints into booleans.  Fair enough.  But then we explore the rest of how Java compares values.  To test the “value” of an variable, we’re used to using the ‘==’ sign.  The problem with dynamic object is that everything is pointers.  This means that if you ask if Object1 == Object2, you’re comparing their memory addresses which each pointers points toward.  That’s not what you want.  So by necessity, Java provides dozens of methods on each object’s base class called ‘equals’.  And so Java typically tests value by the ‘.equals()’ method.  This sort of removes the ‘==’ from its most common use!  ‘==’ is left only for FOR constructs and simple primitive tests.

Python, and a few other more forward-thinking languages, have added a reserved word called ‘is’.  This solves the issue noted above.  When you want to compare the ‘value’ of two objects, you use ‘==’, but when you want to test the ‘identity’ of two objects, you use the word ‘is’.

The point here is that if you say Object1==Object2, you’re comparing values (the most common case, you might argue), but when you want to ask if Object1 literally IS Object2 (ie, their pointers are the same), Python just makes you compare as Object1 is Object2.

Example follows. Note that in Python, examples are provided with “>>>” prefixing lines that you would type in an interactive console session. Lines without the “>>>” are things returned to you by the Python Interpreter.
# Python
>>> myInt = 1
>>> myBoolean = True
>>> print myInt == myBoolean
True
>>> print myInt is True
False

Very simply, the ‘==’ operator is used to ask the integer and boolean values if they “boil down” to the same thing. This is True. But if you ask the integer if it IS the boolean value True, then it returns False, because an integer simple ‘is’ not a boolean.

This is the kind of new stuff that Python (and other languages) are offering to the world. Java is sort of half stuck in this world of mixing the meaning of the ‘==’. If used with primitives, you test by value. If you test with any object at all, you test by memory address, and are thus forced to use Object1.equals(Object2) to test value.

Integrating custom objects in Python into standard Python syntax is amazingly easy.  By contrast, Java rather frequently forces you into writing goofy class methods to perform your tests.

Consider this example of array indexing.  The following seems natural:
// Java
String[] myArray = new String[]{"1", "2", "3"};
String myVar = myArray[0]

But if you write your own object, you can’t ever use indexing notation, to get or set items as the indexed position.  You have to use custom class methods instead.  But in Python, you can integrate with the language by defining methods on your object.  Thus, I can actually tell Python what myCustomObject[0] or even myCustomObject[“sectionName”] means:
# Python
>>> myCustomObject["mainSection"] = "hello world"
>>> print myCustomObject["mainSection"]
'hello world'

In effect, you can have your custom object manage the values however you want; that is up to you.  It abstracts the implementation so that if it ever changes, code other people have written won’t deprecate so easily, because they access the data via standard Python syntax.

 

 

Further, you can actually iterate over a custom object in your own custom way.  You can pick what “iterating over” the object means.  You have complete power. Assuming you had several “positions” in your custom object, example code might look like the following:
# Python
>>> for i in myCustomObject:
...     print i, ":", myCustomObject[i]
'mainSection' : 'hello world'
'another' : 'foobars are healthy'

Can you see the power in this?  You have the amazing ability to tell the language how to integrate very simply with the standard language syntax.

 

 

Lots of “advanced” object functionality is available to Python’s objects by default.  There’s no need to dig out obscure utility functions to get efficient functionality.  A popular thing about arrays these days are “array slices”.  Simply, this means that you can access several indexes of an array at a time. In Python, your typical idea of an ‘array’ is implemented as a data type called a “list”. This is built into Python automatically. There’s no need to import any goofy package first.
# Python
>>> myList = ["a", "b", "c", "d"]
>>> myList[0]
'a'
>>> myList[0:3]
['a', 'b', 'c']
# You can also imply the beginning or end of the list:
>>> myList[:3]
['a', 'b', 'c']
>>> myList[1:]
['b', 'c', 'd']
# Or, you can go backwards:
>>> myList[-1]
'd'

See how easy this is?  Say goodbye to excessive myArray[myArray.length – 1] calls.  Lists support pushing, popping, removing specific items, and queries to find out if an element exists in the list:
# Python
>>> myList = ["a", "b", "c", "d"]
>>> myList.append('e')
>>> myList
['a', 'b', 'c', 'd', 'e']
>>> poppedValue = myList.pop()
>>> poppedValue
'e'
# Pop from an index:
>>> poppedValue = myList.pop(0)
>>> poppedValue
'a'
# Append lists together:
>>> myList.extend(['1', '2', '3'])
>>> myList
['b', 'c', 'd', '1', '2', '3']
>>> "b" in myList
True
>>> "z" not in myList
True
# As a side note, you can do the same to any iterable object, including strings or custom objects!
>>> myString = "12345"
>>> myString[2:4]
'34'
>>> myCustomObject[1:]
['foobars are healthy']

Much more is possible, but this is good enough to start with.  Just understand how amazing simply Python has made this.  Java is a nightmare compared to this.  It might all seem trivial to you, but Python has decided what the most effective way to perform these operations is simply built in.  Anybody caught using any loops in Python to do these things should be arrested.  Anybody caught using loops in Java to do these things is doing it because they have no choice.

 

 

These examples only touch the surface of the differences.  These differences are exactly what makes modern programming languages so powerful.  Yes, there’s a speed trade off, but the productivity to be gained is incredible.  The “scaffolding” of Java and C is overdone.  It is not as needed as it once was.  Python’s clean appearance is easy to read, easy to maintain, and easy to extend.  Python is fully object oriented, and supports multiple class inheritance.  Complex tasks are easier, and you’ll find that you don’t need to code with your browser open to the current JavaDocs.  Python’s just easier.  I’d love to expound on more features of Python which further enhance productivity, so I’ll probably write a Part 3, for those curious to have it explained.

The point is not comparing speeds.  The charts often prove that Java can outrun Python in many tasks.  But as you look at the code to power the Java part of the test, and then compare it to the Python equivalent, you’ll be shocked at how little effort is required to achieve the same behavior.  And with those clock cycles lost in the Python code are more than made up in productivity, allowing you to simply accomplish MORE.  Certain tasks will still require C, regardless of how good Java is.  Nobody seems to complain between the slowness of Java compared to C.  Thus, it’s not a big step to move on to Python.  Modernize.  Get more done.

Until part 3.





Python, MySQL, and a dictionary

19 12 2008

Here is a line in python that should be recorded for posterity…

Some background.  I have a multilingual database where several tables exist.  Each table is named after a particular “vocabulary” for my website.  For instance, there’s a “forums” table for all the terms that are used for pages related to the forums.  The purpose of having this table is so that I have all the needed terms very isolated into a nice hierarchy.  The SELECT * sql would look like this.. (pardon the fake spanish translations)

mysql> SELECT * FROM forum;
+---------------------+----------------------------+------------------------------+
| ID                  | enUS                       | es                           |
+---------------------+----------------------------+------------------------------+
| Audio Review        | Audio Review               | [Audio Review]               |
| by                  | by                         | [by]                         |
| complete            | completed                  | [completed]                  |
| current             | current                    | [current projects]           |
| dropped             | abandoned                  | [dropped]                    |
| loading             | Loading...                 | [Loading...]                 |
| no                  | no                         | no                           |
+---------------------+----------------------------+------------------------------+

As you can see, there is a column “ID”, which is what I use site-wide to access a term, and I select only one other column, according to the language code the user has his/her preference set for.  Thus, a general select for such a thing is …

mysql> SELECT ID,enUS FROM forum;
+---------------------+----------------------------+
| ID                  | enUS                       |
+---------------------+----------------------------+
| Audio Review        | Audio Review               |
| by                  | by                         |

… etc, etc.  Then, I just used PHP to fetch these results into an associative array.  I would then have to loop through each record, saving whatever is in the $row[‘ID’] spot as a key to this array, and whatever is in the $row[currentLanguage] spot as the value to said key.

So anyway..  I was trying to achive this effect in python; a Dictionary-type object where I can simply index into it with the term that I want, in order to get the language-translated value represented by the term.  I knew there had to be a way to do a famous python one-liner, and since those one-liners typically clock much faster than manual loops..

resultSet = (map(None, row.values()) for row in rows)

Seems simple, but it’s a hassle to work it out when your data is a tuple of dictionaries 😛





Python basics

5 08 2008

Python‘s great, really. It takes a little bit of a mode-change before you get used to it, but I’m really quite taken with it. I’ve got experience with C/++, Java, Perl, PHP, Javascript, and a little in Ruby (and I can hammer things out in a number of others, but I wouldn’t claim to “know” the language), and I’m simply impressed with Python.One major plus: Python was built to be a command-line tool.  Thus, you can “run” Python and it will be in command-line form, where you can enter one line at a time.  Sounds rather daft until you’re sitting on a hard chair at 3am trying to guess at how a method behaves.  Python makes this sort of guesswork trivial, as you can just open the command prompt (or terminal, if you’re on some Unix-based system) and run “python”.  You have the ability to simply test a command several times over, to observe its behavior.This INVALUABLE to a person like myself.  There are times when (let’s face it), the online documentation is a bunch of crap, or (in my case), the documentation on the panda3d library’s methods is incomplete.  You have the power to just *do* the command and see for yourself, rather than trying to debug your current program for strange behavior, or trying to built a seperate program for the sole purpose of testing a function or method.  I’ll be honest, I usually have a Python process running in my command prompt while I program in my IDE off on the other monitor.

Some quick observations about Python: 

  • Global scoping can be weird.  Try to be as encapsulated as possible.  Python’s scoping is more like “static” (if you’re familiar with the C++ idea of that term).  There’s no cross-file variable/function/method sharing.
  • Functions” are created with the “def” keyword.
  • Any functions (“def”s) that are within a Class always take “self” as their first arguement, by convention.  When you call these functions/methods, they do NOT require that you pass an arguement to fill the “self” variable in your declaration’s arguement list.  This is resolved automatically.  It is like the “this” pointer of C++.  It’s a reference to the class object that the “def” belongs to.
  • Any variables that should be persistently available in a class should be accessed by the “self.myVar” syntax.
  • A method defined by “def __init__(self):” will act as the class’s constructor.
  • Triple-quoted strings (using three single quote or double quote characters in a row) can be used as something called a “docstring“, and should be placed directly under each class and def statement’s first line.  Triple-quoted strings are really just immune to linebreaks.  That’s all that’s special about  them.  They just happen to be used for this “docstring” very commonly.
  • There are no braces in Python code. Indentation is the way that Python knows what block you’re in.  All statements that should be within an “if” block should be indented the same amount–no more, no less.
  • General lines do not require a semicolon at the end. This is because Python was made for line-by-line console programming.  Making every line end with a “;” is a silly notion.  Just push “enter” on the prompt to finish the line.  However, including a “;” at the end allows you to execute multiple statements on a single line–functionality only really useful from the command prompt.
  • Blocked statements, like “if”, “else”, “elif”, “while”, “for”, “def”, “class”, etc, require a colon at the end. This seems utterly backwards to the normal programming standards out there, but again, on the console, it makes sense; this is how Python knows that you want to enter more information to be within the block that you’ve just tried to define.
  • Everything in Python is by reference. Sounds annoying at first, but it makes the programs a bit more lightweight on the memory footprint.  Variable assignment, if dealing with Objects, is by reference:
    >>> a = myClassObject()
    >>> b = a
    >>> b.setX(3)
    >>> a.getX()
    3.0
    >>>
  • Comments are made with a pound, or hash, sign “#”.  There are no multi-line comments.  You could, however, be a jacker and abuse the triple-quote string to get multi-line “comments” in your code.  It’s nicer just to put a “#” at the front of each line.  C’mon… how lazy ARE you?

And those are some of the basics.





Finite Dreams 0.1.23

5 08 2008

I’ve recently taken on some 3d programming with a set of libraries called “panda3d“.  They’re quite nice, and I’ve been impressed with it all so far.  The main interfacing language is Python, although many of the libraries themselves are written in C++, for speed’s sake.

Ever since (about) highschool, I had this vision of creating my own RPG.  Originally, my naive idea was to make a sequel to the beloved SNES game Chrono Trigger, but then it hit me one that day that…

A) I’d be an idiot for trying to make a “sequel” to a copyrighted video game produced by a largely successful company based out of Japan

B) I felt silly for trying to be “new” and “on the edge of discovery” while only (at best) attempting to extend the ideas of a genius other than I.

C) You don’t just “make a sequel” to your favorite video game.  That’s childish.

While all of the above sound pretty similar in nature, all three hit me differently, and I ultimately decided to completely redo the “story” that I had invented.  I had been drawing characters for use in the game for a long time, yet I still decided that even those needed a make over.

And over the next 3 years, the idea for Finite Dreams (FD) had been in the making.  (The name is kind of tentative, since I came up with it a while back, and I don’t think that I like it much anymore.)  Games from all over the spectrum (a few of the more relevant examples: Kingdom Hearts, Dark Cloud 2, and Final Fantasy XII) had developed ideas at the same time as myself, and I constantly found myself playing a brand new game that had come up with my ideas before I had.  *grr*

But now, I’m creating “my” game.  I’m not recreating someone else’s ideas, or implamenting them differently, or even doing them “better” than in some other game.  I’m making my own ideas, and it’s coming along nicely…  Unfortunately for me, I had to begin learning Python, but now I love it.  It makes me *hate* Java all the more.  *shudder*  ooooOoooOOOo, Java, how I loathe you.  But the guys at work hear me rant enough about Java, so I shan’t do it here.

I’ll be sure to post some actual content eventually.  For now, I’m getting the engine up and running.  While I’m a one-man team, I do hope to make some good progress, even if it takes me ages.  I’m an artist, muscian, programmer, modeler, and storywriter, all wrapped up into one.  I love every single one of those elements.  I can’t wait to hit every milestone along the way.