Sunday, September 25, 2011

Factorial in Python:
f = lambda x: x and x * f(x - 1) or 1

Thursday, August 4, 2011

Semicolon cancer

You know that in many programming languages semicolon indicate the end of a line but not everybody knows that imposition of this requirement is more related to hardware than software. Early programming languages were line-oriented. In FORTRAN, for example, various parts of the statement had specific columns or fields that they had to appear in. Since some statements were too long for one line, the "continuation card" mechanism wasprovided to let the compiler know that a given card was stillpart of the previous line. The mechanism survives to this day, even though punched cards are now things of the distant past.

via Let's build a compiler

Tuesday, June 28, 2011

How to set alarm for console task

ASCII table has some nonprintable characters. One of them is 07 - Bell. It is a device control code originally sent to ring a small electromechanical bell on printers and teletypewriters to alert operators at the other end of the line, often of an incoming message. In unix you can input this character by pressing type it with Ctrl + V and then Ctrl + G which will be showed as ^G.

To set alarm for end of a task just put echo ^G after the command, for example try the following line in your terminal:
sleep 2; echo ^G
Similar technique works with the cat command.

Wednesday, May 25, 2011

Integer.valueOf(1) != 1

Assume you have the following snippet:
public class Bar {

static {
// ...
}

public static final Integer DEFINITELY_ONE = 1;

public static void main(String[] args) {
int zero = DEFINITELY_ONE;
System.out.println(one == 1);
}

}

Should be true, right? Not exactly, depends on what you have in the static block. Try to place this code for example:
try {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
field.setInt(Integer.valueOf(1), 0);
} catch (Exception t) {
//...
}

Now because of autoboxing and integer cache we get false as Integer.valueOf(1) now returns zero.

Wednesday, April 27, 2011

Does overriding violate Liskov substitution principle?

Overriding breaks Liskov Substitution Principle (LSP) if you change any behavior defined by a base method. Which means that:

1. The weakest precondition for a child method should be not stronger than for the base method.

2. A postcondition for the child method implies a postcondition for the parent method. Where a postcondition is formed by: a) all side effects caused by a method execution and b) type and value of a returned expression.

From these two requirements you can imply that any new functionality in a child method that does not affect what is expected from a super method does not violate the principle. These conditions allow you to use a subclass instance where a superclass instance is required.

If these rules are not obeyed a class violates LSP. A classic example is when you have the following hierarchy: class Point(x,y), class ColoredPoint(x,y,color) that extends Point(x,y) and overridden method equals(obj) in ColoredPoint that reflects equality by color. Now if one have an instance of Set<Point> he can assume that two points with the same coordinates are equal in this set, which is not the case with the overridden method equals. Actually, there is just no way to extend an instantiable class and add an aspect used in equals/hashCode methods without breaking LSP.

Thus every time you break the principle you implicitly introduce a potential bug that reveals when invariant for a parent class that is expected by a client code is not satisfied. However, in real world often there is no obvious design solution that does not violate LSP, so one can use @ViolatesLSP annotation to warn a client that it is unsafe to use class instances in a polymorphic set or in any other cases that rely on the Liskov substitution principle.

Monday, March 21, 2011

Scala for Java developers

I noticed that while migrating to Scala I often tend to write a code in old Java style. For example I write loops when map-like functions are more appropriate or excessively use exceptions. Other common mistakes that I can mention are:

  • Using own getters/setters instead of methods kindly generated by Scala
  • Using null instead of Option
  • For me it is easier to follow functional programming style encouraged by Scala when functions return non-Unit type
  • It is also a good practice to use var only when it is really needed, for example for counters or some other store of the current program state
  • Finally, Vector in Scala is not an outdated class as java.collections.Vector is, but a powerful Scala collection with "effectively" random access time and "effectively" constant time for insert/delete operations

Friday, March 4, 2011

In my opinion, a responsibility of exceptions handling is a part of a business logic and enforcing a developer to process them on each layer adds inevitable problems that decrease a value gained from using exceptions. So to move an exception handling from a time when the exception occurred to a point where we need to extract a value Scala developers often use Option or Either classes instead of try/catch block. It unburdens unrelated intermediate methods from dealing with an exception and make it possible to pass such functions without any additional notations. However, this classes do not reflect the usage intention, so I propose a solution which will be more readable and at the same time less verbose.



object Exceptionable {

sealed abstract class Exceptionable[+A, +E] {

def isSuccess = this match {
case Success(_) => true
case Failure(_) => false
}

def isFailure = !isSuccess

def success = this match {
case Success(a) => Some(a)
case Failure(_) => None
}

def failure = this match {
case Success(_) => None
case Failure(e) => Some(e)
}

}

implicit def resultToSuccess[A](result: A) = Success(result)

final case class Success[A, E](a: A) extends Exceptionable[A, E]
final case class Failure[A, E](e: E) extends Exceptionable[A, E]
}

Demo:

import Exceptionable._

def divide(a: Int, b: Int): Exceptionable[Int, String] = {
if (b != 0) a/b else Failure("Negative value")
}

def main(args: Array[String]) = {
divide(10, 4) match {
case Success(a) => ...
case Failure(message) => ...
}
}