Programming – my passion

Mon, 2 February, 2009

Multiple inheritance

Filed under: Programming — Tags: , — TPJ @ 8:36

Recently, I found the question “Why there is no multiple inheritance in Java?”. It was a newbie question, so I thought for a while and I wrote the answer: “Because the Java creators don’t like multiple inheritance.”. I also mentioned, that the dispute on the multiple vs. single inheritance topic might be further investigated in the web.

I decided to take a look at Wikipedia. What can be found on this topic there?

“Criticisms [of the multiple inheritance] includes:

  • Increased complexity
  • Semantic ambiguity often summarized as the diamond problem.
  • Not being able to explicitly inherit multiple times from a single class
  • Order of inheritance changing class semantics.”

Increased complexity? Well, yes, multiple inheritance is much more complex than single inheritance. And my modern PC computer is much more complex than my old Atari 800 XL (an 8-bit computer). Should I say that my modern PC is worse than Atari 800 XL just because it’s more complex?

Semantic ambiguity… Yes, it’s true, that using of multiple inheritance might lead to the diamond problem. But I really doubt it’s a real problem. Why? Think about it. Using knives also might lead to cut somebody’s throat, yet no one says that no knives should be thus used. No one says that, because it would be stupid to say so, just as it’s stupid to say that multiple inheritance is bad because it might lead to the diamond problem. Hey, people, don’t use C, because it might cause some problems related to pointers! (Please tell it Linux kernel developers.)

And it’s true, that the order of inheritance changes class semantics. But why on Earth is it considered a drawback of multiple inheritance??? It’s one of its biggest advantages! Just think of it: you can influence the class semantics just by changing the order of inheritance… I have used this feature and I find it very useful.

After reading this article on Wikipedia, I have to say that the arguments of multiple inheritance opponents are very weak. It would be better, if they just said they don’t like it, don’t want to use it, and don’t want it to be present in the languages they design (and/or use). That’s OK. That’s just their choice, their taste.

Please, don’t get me wrong. I’m not saying that multiple inheritance should be present in all OO languages, since it doesn’t have to be used. In fact, I’m far from it. If some feature is present in a programming language, usually you have to make use of it even if you don’t want to. It’s because you use other people’s code, and those people use this feature. It’s inevitable.

So, the choice is simple. If you don’t want to use multiple inheritance, choose a language that doesn’t have this feature. But be honest: choose this language and say that you’ve done it because you don’t like multiple inheritance, not because multiple inheritance is a bad thing.

Mon, 15 September, 2008

Java vs. Python: The Readability Myth

Filed under: Programming — Tags: , — TPJ @ 9:16

One of the well-known truths about programming is that the readability of the code is one of the most important factors. Everybody knows that the longest part of every software life cycle is its maintenance, and the more readable code, the easier to maintain it is.

While comparing Python with Java, some common “truths” can also be spotted. One of them is the “fact”, that Python code is more readable than Java code. This thesis originates from an other one: the Java code is more verbose than the Python code. How could’ve someone suspect, that the more verbose code could be easier to read?

Well, I have no doubt that Java is more verbose than Python. The question is: can we assume that verbosity is the exact opposition of readability? Because if this assumption is false, then the thesis of Python code being more readable than Java code also might be false.

In my personal opinion, code verbosity is something quite different than code readability. Moreover, I think that Java code is easier to read than its Python equivalent, and it’s due to the fact, that Python uses dynamic typing, and thus hides (sometimes essential) information from programmer. In order to prove it, I’ll analyse some simple examples of Python and Java code.

The Python examples

The first example is a very simple Python code:


class SomeClass:
  def someMethod( someArg ):
    (some stuff here)

class SomeBaseClass:
  (some stuff here)

class SomeOtherClass( SomeBaseClass ):
  (some stuff here)

What can we say about it? Not too much. The used classes and methods names are horrible: they don’t say anything about their purpose. All we can say about the code presented above is that this SomeOtherClass is based on the SomeBaseClass. Such a code is very hard to read and understand.

So, let’s try to make this code easier:


class Forest:
  def getTree( treeID ):
    (some stuff here)

class Tree:
  (some stuff here)

class Oak( Tree ):
  (some stuff here)

That’s much better. Now we can see that the second and the third classes are related to the first one. We can also suspect that the getTree method returns a Tree object, according to the given treeID.

So far, all I showed is the fact, that using meaningful names for classes, objects, methods and variables might make code more readable. This is a common-known truth, though, and it applies not only to Python, but to any programming language.

The Java examples

Now, let’s take a look at the first example in Java:


public class SomeClass
{
  public SomeBaseInterface someMethod( SomeType someArg )
  {
    (some stuff here)
  }
}

public interface SomeBaseInterface
{
  (some stuff here)
}

public class SomeOtherClass implements SomeBaseInterface
{
  (some stuff here)
}

This is the equivalent for the first example of Python code. What can we say about it? The code is more verbose, of course. We have to write more lines of code in Java than in Python. But there is something more: although the used names are still horrible, we are able to notice a relationship between all the three classes: the someMethod method returns an object of the SomeOtherClass class. That’s more than we could say about the Python code.

That’s not all, though. We can say that the SomeBaseInterface is an interface. Thus we can say something about the analysed API design.

Let’s get to the second Java example, which is the Java equivalent for the Python second example:


public class Forest
{
  public Tree getTree( int treeID )
  {
    (some stuff here)
  }
}

public interface Tree
{
  (some stuff here)
}

public class Oak implements Tree
{
  (some stuff here)
}

Here, almost everything is clear. We can get all the information we could get in the first example, and also we can say that a Tree object identifier is an integer value.

What does it mean?

After the examples have been shown, it’s time for some conclusions.

We can safely assume that code in practise is like from the second example. In general, programmers tend to use meaningful names, because it makes their work easier. So, let’s focus on the two second examples first.

Although the Python code is less verbose, it hides one information: what is this treeID? It’s some kind of Tree identifier, of course, but what exactly is it? An integer value, a string, or something else? We don’t know it. So even using meaningful names in Python code won’t give us the information we get easily reading Java code.

Of course, one could argue that such information could be in the code docs. Yes, that’s right. But it would make Python code more verbose, and it makes programmer to document even trivial functions/methods. In the Java code no documentation is needed in order to find out what the Tree identifier is. Therefore I find the Java code more readable.

And when we take a look at the both first examples, and start an academic discussion, we can see that the Java code contains much more information than its Python equivalent, and thus we can say it’s more readable, even being more verbose.

The conclusion

Of course, it’s the well-known dynamic vs. static typing debate. Personally I’m all for static typing, provided that I have to write more than 100 lines of code. In another words: Python is better while writing small scripts, while Java takes its ground in more complex projects. It’s one of the reasons for which I decided to switch from Python to Java, although I prefer higher-level programming over lower-level one.

In my opinion, programming in Python might lead to writing less lines of code, using a higher level of abstractions, and thus completing projects faster, than programming in Java. But it all comes with some price, and this price is code readability. For me, Java code is more readable, because it shows more details about itself, and thus makes the analysis easier. And I know it not from my theoretical assumptions, but from practical experiences. Java code written by someone else is much easier for me to read, than Python code written by someone else.

Tue, 10 June, 2008

Keep It Configurable, Stupid!

Filed under: Software — Tags: , — TPJ @ 12:30

Just a short note today (I’m still very busy getting ready to my doctoral dissertation defence).

I have read this text today. It’s about another great/wonderful/etc. source editor for developers. The editor was commercial, but now it’s free. Free as in beer.

I have read all the text and I was even impressed with the editor’s features. A nice tool, I thought, perhaps I should try it. And so I did. I downloaded it, and installed it.

The first flaw: I have chosen it to install into a specific directory, but it installed also into a directory created in my home. Without my permission, of course. I hate it!

The second flaw: I wasn’t able to set my own fonts in this editor. Since I hate looking at small fonts, I didn’t like the editor. Sorry.

And in such a way my adventure with this great/wonderful/etc. tool ended.

The conclusion: you might put much work into a piece of software. You might think your software is really great in comparison with your competition. But if you target at developers, you should give them ability to fully configure the software. If you fail in doing this, they won’t like it. Despite all the great/wonderful/etc. features your software already has.

This is the lesson to learn!

Fri, 11 April, 2008

Programming Paradigms Are Something Good

Filed under: Programming — Tags: — TPJ @ 11:55

Every programmer has some limited abilities to solve problems, and to maintain code. Although I don’t find it precise, these abilities might be expressed as number of lines of code. The more lines of code a programmer is able to maintain, the better.

Problems can be solved in various ways. Let’s take a QuickSort algorithm as an example. It can be solved in a few lines in Haskell, while solving the same problem in C leads to much more verbose code. Although both solutions are correct, the former is much easier to maintain.

So, it might be stated that the less verbose code is easier to maintain, provided that it is more readable. If we want to extend programmers abilities to maintain code, we should seek for solutions which lead to less verbose and more readable code. Simple, isn’t it? Yes, it is simple – and it’s not a great discovery.

Let’s take a closer look at this problem. Provided that we should seek for solutions which lead to less verbose and more readable code, can we stick to just one programming paradigm? For example: should we solve every problem using OOP?

The answer might seem to be obvious: no. If some another programming paradigm leads to less verbose and more readable solution of some problem, it should be used instead of OOP. And I think it is that simple. It’s like cracking a nut: if I can do it easily with a hammer, why should I bother myself using a knife?

It’s more general problem, though. It’s a question regarding technology: if there are two technologies, and one of them is better in solving some problems than the other one, should we use that other one? Absolutely no; in fact, we shouldn’t even think of using the other technology! We should follow the simple rule: always use the best tool available.

Despite all these facts mentioned above, programmers often act opposite. There are many programmers convinced they should use just one tool to solve all the problems. Nevertheless what the tool is (often it’s Java or C++), it’s the best tool to solve everything. Indeed, everything can be solved with it. But the question is not “can everything be solved (…)?”, but “is it efficient to solve everything with the same tool?”.

As I have already mentioned, solving some problems using FP leads to less verbose and more readable code in comparison to solving the same problems using SP (or OOP). Therefore if we constraint ourselves to just one programming paradigm we will condemn ourselves to write worse code: more verbose and less readable. As a result we will have to maintain more and worse-written code; it leads directly to constraint ourselves in our ability to solve more complex problems.

I find OOP very useful. It allows me to solve many complex problems with fewer lines of code, by using OOP abstractions. My personal ability to solve complex problems might be expressed in numbers of lines of code (LOCs). I think I can easily handle, say, tens of thousands of LOCs. Using OOP abstractions allows me to make a good use of these lines; I doubt I would have been able to solve the same problems just with SP in the same amount of LOCs.

But sometimes I just need other abstractions. I need first-class functions, closures, currying and tail-recursion. They all are just some concepts, and I could replace them with features available in SP or OOP, but it would lead to more verbose and less readable code… So I don’t want to do this. I have only my tens of thousands of LOCs to solve my problems, and I think I have to use them right. I have to choose the best technology I can.

Therefore I find using many programming paradigms so useful. Especially when I can use them in just one programming language.

Mon, 7 April, 2008

Currying in Scala

Filed under: Programming — Tags: — TPJ @ 9:37

Fed up with Java I started to learn Scala. It’s a language that seems to solve almost all problems I spotted in Java. I started with a tutorial; it’s definitelly not a very good-written one (comparing to, say, Java Tutorials or Python Tutorial), but it’s also the best I have found so far.

One of the Java disadvantages that Scala solves is support for functional programming. While programming in Java I often miss functional features, especially closures and first-class function/method objects, but higher-order functions and currying can be also very useful in solving some problems. After reading the 4th and 5th chapter of the mentioned tutorial, I learned how to use those functional features in Scala.

I have to say that Scala is not as functional as, for instance, OCaml is. Let’s analyze the following, simple example of OCaml code, making use of currying:


let f a b = a + b;;
let g b = f 3 b;;

f 3 2;; // 5
g 2;;   // 5

The equivalent code in Scala looks as follows:


def f(a:int)(b:int) : int = a + b;
val g = f 3 _

f(3)(2) // 5
g(2)    // 5

Let’s take a closer look at differences between the two examples.

In OCaml, each function is curryable by default, without any additional effort. If a function is called with less parameters given than needed, the result always is a function. It’s a simple rule.

Things are different in Scala. If function should be curryable, it has to be properly declared. Each “currying point” is denoted in parenthesis: in the analyzed example this is only one such point (after the first parameter). Moreover, each parameter that could be curried has to be given in its own parenthesis. Well, perhaps it doesn’t look so bad, but let’s suppose we have a function with N parameters (N>0). While the OCaml code is simple:


let f a1 a2 ... aN = ...;;
let g a1 a2 ... aK = f a1 a2 ... aK;;  // K < N

f 1 2 ... N;;
g K+1 K+2 ... N;;

the Scala code becomes more verbose:


def f(a1:int)(a2:int)(a3:int)...(aN:int) : int = ... ;
val g = f a1 a2 ... aK _

f(1)(2)...(N)
g(K+1)(K+2)...(N)

Of course the same function can be written in a simpler form, but with the price of being not curryable:


def f(a1:int, a2:int, ..., aN:int) : int = ...;

f(1,2,...,N)

As we can see, there is a clear distinction between curryable and not curryable functions in Scala. The difference is in function declaration, as well as in function calls. This difference makes use currying in Scala a slightly less convenient than in functional languages (like OCaml).

One question comes to mind here: is it a serious Scala disadvantage? Well, everything has its price. As far as I know Scala was meant to be a language which solves many problems of Java, and so far I think it is successful in this field. The example with function taking N paramaters is rather an academical one; it’s a case I proposed to show the fact that currying in Scala is not so convenient as currying in OCaml (and, probably, in other functional languages as well). I doubt I would ever write a fully curryable function of more than 3-4 parameters in Scala, so the “disadvantage” discussed here is rather a small problem in practice…

However, there’s alway the other side. Scala creators seem to focus on functional programming aspects of Scala; these features are the ones which are exposed and emphasized (at least I have such an impression). So if we take a closer look at what they have already done: a programming language with support for functional programming, with not-so-convenient currying… It might seem a little weird.

Anyway, Scala is an interesting language. I’m going to keep learning it further.

Thu, 27 March, 2008

How to get all Java class members using NB API

Filed under: Programming — Tags: , — TPJ @ 12:59

All right, I have finally done it. Just to find out that I can do what I need to be done without getting all of this stuff, but that’s another story…

Here you can read about getting all the members of a Java class. This information is usefull, but if you have no experience with Compiler Tree API, like I did, you probably will spend a few days trying things to do just what you want them to do. Therefore I’m going to show the code you can use to obtain information about class members (just methods, but obtainig information about constructors and fields should be similar) using NetBeans API.

First you should get access to the following docs:

  • Compiler Tree API (it isn’t included in the standard Java docs!)
  • javax.lang.model (it is…)
  • NetBeans JavaSource API (the one is not distributed with all of NB 6.0 docs; I have downloaded it directly from the web)
  • This guide is also very, very helpful! In fact, this text is its extension (is it the right word? I’m not a native English speaker…).

    The first lesson: if you want to get to Java class information, you need get to some CompilationInfo instance.

    As far as I know, the only way to do it is to write a Task:

    
    class MyTask implements Task<CompilationController>
    {
      public void run( CompilationController compContr ) throws Exception
      {
          // get to the right compilation phase, so all the information we need
          // are available
        compContr.toPhase(Phase.ELEMENTS_RESOLVED);
    
          // run the scanner
        new MemberVisitor(compContr).scan(compContr.getCompilationUnit(), null);
      }
    
    }
    

    Once you’re in <? implements Task<CompilationController>> run method, you have the CompilationController instance you need. Simple, isn’t it?

    This instance is needed to do one thing only: to wait until the Java source file is compilled (or parsed? I don’t know and I don’t care), so all the information about classes declared in this file is known. And once this information is available, you can pass it to the scanner, whose job is to extract all the information you need.

    The second lesson: things are easier if you use a scanner.

    The scanner is the place when all the magic is performed. The class is quite simple (and can be found in one of the documents I gave links to):

    
    class MemberVisitor extends TreePathScanner
    {
    
      private CompilationInfo info;
    
      public MemberVisitor( CompilationInfo info )
      {
        this.info = info;
      }
    
      @Override
      public Void visitClass(ClassTree t, Void v)
      {
    
          // get the class element from the compilation tree (or something?)
        Element el = info.getTrees().getElement(getCurrentPath());
    
        if (el == null)
        {
          // the class cannot be resolved
          ...
        }
        else
        {
            // cast the element to TypeElement class, which describes a class
          TypeElement te = (TypeElement) el;
    
            // get the name of the class
          debug.println( "Class name: " + te.getSimpleName().toString() );
    
            // get all the elements in the class - constructors, methods and fields
          List lstElements = te.getEnclosedElements();
    
            // get information about methods
          getMethods(lstElements);
        }
        return null;
      }
    
      (...)
    }
    

    The constructor above is needed only to store the CompilationInfo instance (yes, it’s a real treasure ;-) ). The most important method is visitClass, which is called for… each class found in the Java source file. Without using scanner we would have to “dig” to the class element “by hand”…

    And once you have the class Element, you can get all the class members with the method getEnclosedElements(). All the mentioned class members are Elements which are enclosed by their class Element. Simple, isn’t it?

    (And, BTW, the debug.println method is a fictional one, which just prints out the given string.)

    So far so good, but now comes the most difficult part: getting the information about class members. The documents I gave links to lack this part.

    Lesson three: what are ExecutableElements for.

    We have the list of class members elements… These elements stand for all class members: constructors, methods and fields. Let’s suppose we are interested in methods. The first thing to do is to filter out all the elements we are not interested in:

    
      private void getMethods( List lstElements )
      {
          // we got the list of all the elements in the class, but we are
          // interested in methods only
        List list = ElementFilter.methodsIn( lstElements );
        getMethodData( list );
      }
    

    So far, so simple. Let’s get further then:

    
      private void getMethodData( List lstElements )
      {
        for ( ExecutableElement el : lstElements )
        {
            // get the name
          debug.println( "Method name: " + el.getSimpleName().toString() );
    
            // get all the modifiers
          getModifiers( el );
    
            // get all the parameters
          getParameters( el );
    
            // get the return type
          debug.println( " : " + el.getReturnType().toString() );
        }
      }
    

    Getting method name is simple, and needs no extra discussion. So is getting the return type of the method. The rest of the code is meant to be as readable as possible. Let’s take a look at the getModifiers method now:

    
      private void getModifiers( ExecutableElement el )
      {
        Set setMods = el.getModifiers();
        for ( Modifier mod : setMods )
        {
          debug.println( mod.toString() );
        }
      }
    

    The code should be quite obvious: we get all the modifiers of the given ExecutableElement (which can be method or constructor) and we just print them out, one by one.

    The code of getParameters method is also simple:

    
      private void getParameters( ExecutableElement el )
      {
          // get the list of parameters
        List lstParam = el.getParameters();
        for ( VariableElement parEl : lstParam )
        {
            // get the parameter type
          debug.println( "Parameter type: " + parEl.asType().toString() );
    
            // get the parameter name
          debug.println( parEl.getSimpleName().toString() );
        }
      }
    

    Conclusion

    Now it should be clear how to obtain information about class members. The code is simple, once you know how it works (and which APIs it uses). I hope this text will be helpful for other developers interested in writing NetBeans modules.

    My next goal is to learn how can I programatically modify Java source file, in particular adding fields and methods.

    Tue, 25 March, 2008

    Studying NB docs

    Filed under: Programming — Tags: , — TPJ @ 6:45

    Today just a short note.

    During the last few days I spent a couple of hours getting familiar with NB platform docs, tutorials, NB wiki and mailing lists archives. With almost no results.

    My second impression (my first one was a few days ago, when I took the first look at these docs) is that all of these docs focus on implementing something new, on extending NB platform with some new features. If I wanted to create something that the current version of NB is missing (e.g. handling my new file type), I would find any information I needed. But extending something that already exists in the platform remains a mystery.

    Of course it might be just because I’m a newbie to NB platform. The software is very complex and I need more time to get familiar with all of these docs, APIs and glossary.

    My studies hasn’t been completely fruitless though. I have found some interesting information and my concept of the software I’m going to write become clearer. Now I know I have to add some features to File Members and File Hierarchy windows. All I need to find out is the sources of these windows, I think.

    So, I’m going to ask some questions on dev@openide.netbeans.org or nbdev@netbeans.org. Well, perhaps I’ll check this site first, but I don’t suppose I’ll find any answers to my questions there.

    Fri, 21 March, 2008

    My First Approach to NB Platform: Getting Docs

    Filed under: Programming — Tags: , — TPJ @ 9:05

    There are two essential reasons for which I find NetBeans better than Eclipse:

    1) After installing NB, I get all I need: a good editor, a profiler (that works), a debugger, a unit tests module. And I get it all out of the box.

    2) I don’t have to worry about ant scripts. NB takes care.

    There are also other advantages of using NB over Eclipse, but they are minor ones and I won’t write about them here.

    Recently I decided to get familiar with NetBeans platform. I’d like to use it for my applications, and also I’d like to write some modules for NB. This is not as easy though, as I thought…

    First of all, I need to have javadocs for all NB APIs. Tutorials are important, Wiki is important, but without documentation I would be just blind.

    Fortunatelly, NB allows anyone to download javadocs in zip format. Unfortunatelly, some NB APIs from the NB 6.0 release are not documented there… I have tried to build them from NB sources, but I failed.

    So I decided to download all the docs directly from the web, using wget. This method worked, at least.

    I want to modify a given Java source file (create a new class/file, add a method, a field, rename a method, etc.), so I will probably use Java Source API and run some Tasks. But for now I need to know all the methods and fields in this given Java source file… In the following days I’ll try to figure out how I can obtain such information.

    Anyway, I think it would be nice if all the NB APIs used in NB 6.0 were included in javadocs for this version available for download. It’s confusing to discover the fact, that not all is included there.

    Blog at WordPress.com.