I don't KISS, but I like to keep it DRY.

If you didn't get past the disgusting interpretation of that title, then you probably shouldn't be reading this blog ;)
I make elephants out flies and flies out of elephants, after-all, the human genetic code is 40% bananas!

Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Monday, June 7, 2010

Latter optional arguments evaluating to values of former arguments

Code series: This series has to do with the day-to-day ideas that come up as I code. It is often the case that these ideas are already implemented in a language other then the one used, and sometimes it is even the case that the idea comes from my lack of knowledge or oversight of some feature in a programming language. If you notice such subtleties, please comment, I'm more happy to learn from my mistakes than to keep following false, or already implemented ideas.

I've come across this issue several times, but this is probably the first time I've had the time to formalize it. Sometimes in a function definition you make use optional arguments with default values. In essence I find this to be a shorthand to overloading the function with another signature, and calling that base function from there, however, that is apparently not the case in any known to me implementation of a programming language that actually supports optional arguments in function signatures.

You almost always are able to evaluate some expression as the default value, and while code-blocks would certainly make things look even more complex, I think they should be allowed if one wishes to use them, but that is rarely needed, it just so happens that default values are more often than rather simple to compute. It is therefore sometimes pleasant that one can do the following in e.g. Python:

def nice(a, b = 1 + 2):

My problem lies with the scope, consider this Python code:

def nice (a, b = a)

Unfortunately this is not allowed, yielding the error:

NameError: name 'a' is not defined

From which I deduce that the scope is local to each variable, I wander why this is? As I've most certainly seen uses of the latter case but never the former? 

Would've sure be nice for those variables to be evaluated within the same scope.

Monday, May 31, 2010

Good idea

Pattern-matching always makes me happy :)
http://billmill.org/pygenerics.html

Monday, February 8, 2010

Labeling revisited

While I, in one of my older blog-posts, brought up the idea of killing redundancy in code through extensive labeling, or tree-structuring, of the code itself, and not just of block statements, one of the ideas that followed, I was pleased to find redundant to some C++ syntax.

For the past week I've been looking into C++ through the eyes of Accelerated C++, and must say I am quite impressed, and find C++ very interesting, and my time to turn to it to be no less than perfect! I seem to have, at the very least, a basic idea of all the concepts that I have, so far, seen to make up C++, and so it is pretty easy to get going with it! However, back to the theme of the post, I've recently got past the part about the process of building classes and structs in C++, and found the following property rather pleasing:

In a struct the default protection level is public, until otherwise specified, while in a class the default protection level is private, but again, until otherwise specified. Now, that statement might not explain enough why I'm happy to know this, so let me show you an example:

class myclass {
  std::string name;
  //many many more private members
  public:
    double nice() const;
    //many many more public members

is equivalent to

struct mystruct {
  double nice() const;
  //many many more public members
  private:
    std::string name;
    //many many more private members

Of course, if the const memeber function uses name, or any other of the private members(which is most likely) then (I think) that will cause an outright compilation error, in which case we must rewrite it as follows:

struct mystruct {
  private:
    std::string name;
    //many many more private members
  public:
    double nice() const;
    //many many more public members

Again, this outlines how these protection labels work - there's a default one, which can be overridden by a number of subsequent such labels, each time canceling out the previous one. I guess this is also the reason structs are more usually used for open/simple data-structures, where private members are analytically trivial.

Basically, this is awesome syntax!

P.S. Sorry Python, I'm having an affair with C++.

Tuesday, January 26, 2010

Tab-completion(A small case on IDEs continued)

So I noticed the same problem today in a simple prompt, where tab-completion also looks backwards, but never forwards. Here's an example:

I accidentally select the wrong file to print:

.. abc.pdf ..

So, again, being the cautious user that I am, I don't delete the .pdf, put the cursor before the dot, delete abc and aim to replace it with def, which I know can be tab completed, as a result we get this:

.. def.pdf.pdf ..

A bit stupid, isn't it? And this is a fairly simple thing to do.

Monday, January 25, 2010

do{}finally{}

So I was minding my own business writing a simple patching(merging) tool for a certain XML format and came across a certain aspect that surprised me. Take a look at this code-snippet:
if comment.text.startswith('[/'+name+']'):      
      siblings.remove(comment)
      return
else:
      siblings.remove(comment)
      return self.removesequence(siblings, name)
The function itself is a part of the removesequence, which hence is a recursive function that removes certain elements from a list, including the outer bound of that slice to be removed. The system is akin to HTML. Suppose we have a series of nodes to be merged across several XML files, the beginning node gets a [tag] and the closing node gets a [/tag] attribute. Then we merge by deleting the nodes in between, and including, the bounding nodes, and then inserting the new nodes(with the new bounding nodes) in the exact same spot where the node with the attribute [tag] once stood.

Never-the-less, the point of this code is beyond the scope of this post! The idea is simple, it's that I have to remove the element in scope(comment) in either outcome of the boolean expression, however, what is in question is whether to continue to the next node or to stop at this one. Clearly I cannot delete the code before the boolean expression, rendering it invalid, so the only real choice I have is to repeat myself, now isn't that a bugger!

There are of course ways around this, but they're not too pretty, such as cloning the comment.text string(or well, that's probably as pretty as it gets), or adding a conditional immediate return at the top of the method, such that if it got None values it would return, resulting in an extra function call and more code!

This code-snippet reminds me of the reasoning behind the finally clause in a regular try-catch block in both C#, Java, and a few other languages. Thus the immediate idea is to introduce a type of if-then-else-finally block, however why stop there? Why not just abstract the finally concept into something by itself. I mean, the Java language prioritizes finally over return already, however, the question remains why this is solely a luxury for the anyways ludicrous try-catch blocks?

So, what about a do{}finally{}?

Updated
Scratch that, my bad, and I am somewhat ashamed of myself, this Java doc states the following:

"But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated."

So the concept is certainly there and it's called a try{}finally{} in Java. Question then remains whether the unpleasant overhead of a try-catch is spared. As far as I can see from this blog post by Alan Keefer, it isn't.

Also, this python doc tells me the equivalent is also true for python:

"The try statement specifies exception handlers and/or cleanup code for a group of statements"

Thus, I can reorganize the aforementioned code-snippet as follows:
try:
   if comment.text.startswith('[/'+name+']'):      
      return
   else:
      return self.removesequence(siblings, name)
finally:
   siblings.remove(comment)

A small case on IDEs

Upper class 3rd-generation programming language frameworks, such as Java and .NET make it impossible to code anything beyond a simple algorithm in a simple text editor. One may even think that these languages were designed to make us use IDEs, but that would probably be an overstatement. So, there exist various IDEs to make our jobs as coders for these frameworks much less of a burden, and oh my do they do a great job! I'm sure, those of you familiar with such coding, won't object me too much when I say that code-completion in Visual Studio, Eclipse, Netbeans, and so on, probably makes all the difference in the world!

Recently, from a bit of over-coding in Java I've noticed a pattern, or rather an itch that I've had for while, with all of these big IDEs. The thing is that they do a great job at analyzing the code standing before the cursor, and in other functions and classes, but there seems to be no analysis of the code between the position of the cursor and the end of the current line of code! Let me give you an example:

Assume that I make the novice mistake of using
m.group(1) == "maze";
instead of the built in equals(Object anObject) method in the String class.

So I decide to correct that. Being the cautious user that I rarely am, I decide not to erase "maze", but rather change the code around it. So I move the cursor to the closing ", and put a ):
m.group(1) == "maze");
Then I move the cursor to the opening ", delete until, but excluding, the closing ), and putting a . right next to it:
m.group(1)."maze");
This causes my IDE to pop-up a smart auto-completion box with all the available to me fields, properties & methods of the String class. I genuinely type a few of the first letters of the word equals, until it is the only method present, and in desperation hit TAB to autocomplete. The dumb thing is that this results in:
m.group(1).equals(anObject)"zoom");
A totally unusuable peace of code. Thus, I end up doing more work cleaning this up, than I would've originally, if I simply decided to delete the intere == "zoom" sequence, and write it all over again. Sadly, sometimes the line to keep is long, and the change in comparison is subtle, which begs for copy/paste, but how irritating is it to have to resort to selecting code when coding!

So, my dear IDE, will you please learn look not only behind, but also ahead when you autocomplete?

P.S. I didn't include screen-shots to emphasize this goes for any IDE I've ever used, but correct me if I'm wrong of course :) Oh and I'm open to suggestions on how to fix this, if such a feature comes built in. I know that Eclipse is open-source so don't tell me that ;)