问:
Are there any programming fonts with oldstyle figures?
I find that oldstyle (or text) figures are much easier to read in any context outside of simple assignment. Are there any low-ambiguity fonts, monospaced or proportional, that have text figures and other programming-friendly features, such as marked zeroes; aligned braces, operations, and other symbols; and bold and italic forms with identical width to regular?

Note. Old-style figures are numerals which are drawn with variable ascent and descent. Typically, for example, a "0" will be slightly larger than a lowercase "o"; the "6" and "9" will have have circles that are sized and placed similar to a "0", with flags extending up and down from that.

In general, if one is trying to examine numbers as numbers (e.g. parse "8675309" as "eight six seven five three oh ni-y-ine"), the "lining" forms with unified ascent and descent are easier to read. On the other hand, multi-digit numbers written with old-style numerals have different shapes. If one is comparing columns of figures, a number like "1265" will look very different from "1285", since the former will have a flag on the "6" that sticks up far above any feature of the latter.

Tabular figures are figures spaced with equal width; they may be lining or oldstyle. So all monospaced fonts have tabular figures, but most proportional fonts do not.

答:
In most IDEs, you may choose whatever font you like. If you find an oldstyle font more readable, pick it.

Note that all (nearly all?) oldstyle fonts are proportional, while proportional fonts have some issues when using them in programming context.

Aside that, let's test and compare some oldstyle fonts to the fonts usually used in IDEs. I have only Windows environment for tests; if anyone could add illustrations for fonts used in MacOS or Linux, feel free to edit the answer.

There are multiple oldstyle fonts installed by default in Windows/Microsoft Office:

In order to avoid duplicates and shorten the answer, I take only three oldstyle fonts: Georgia, Corbel and Gabriola and three classical fonts: Courier New, Lucida Console and Consolas.

Courier New

Simple to use, but hard to make the difference between the digit "0" and the capital "O". The text is too light, which would make it difficult to read on a black background with light text.

Lucida Console

Same problem with digit "0" and capital "O", but compared to Courier New, the text is easy to read even on black background.

Consolas

The recent Consolas font was specifically created to use in IDEs and other source code-related contexts and to replace the former Courier New. It totally removes the ambiguity between the letter "O" and the digit "0" by using slashed zero character.

It remains very readable for both large and small sizes and for both light text on dark background and dark text on light background contexts. If you use ClearType, Consolas is an excellent choice.

Georgia

This is a nice font, but was rather designed for print. On an LCD screen, small text has some glitches with whitespace which feels not very uniform (as you can see on the screenshot).

The largest issue is that there is nearly no way to make the difference between the small letter "o" and the digit "0". Seriously, is it CoordinatesOfo or CoordinatesOf0? This sole issue is a deal breaker for an IDE.

Corbel

The font is very readable, even with a small size text. Due to oldstyle, numbers are very easy to read too.

On the other hand, this font suffers the same issue that Garamond: no clear difference between the small letter "o" and the digit "0". This sole issue is a deal breaker for an IDE.

Gabriola

As you can see, the font is impossible to use, unless you set a very large size in your IDE. This font is for happy new year cards, not for programming.

In conclusion, most oldstyle fonts suffer from the similarity between the small letter "o" and the digit "0", and in many cases, there is no way at all to make the difference between the two. See for example Gabriola or High Tower Text: those two characters seem identical.

Solutions

If you're in love with oldstyle figures, there are two other solutions.

1. OpenType oldstyle

Actually, OpenType has an oldstyle feature for some non-oldstyle fonts. For example, Consolas font has this feature. I can't find neither how you can turn this feature on in Visual Studio, nor even how to do it in Microsoft Word 2007, but you may deep more in this direction if oldstyle is something you really need, but can't afford losing the strong points of monospace fonts.

Microsoft Word 2010 seems to support old-style option for OpenType fonts, but I don't have Office 2010 to actually test it.

Visual Studio 2010 may also be able to support it through an addin which changes the WPF options of the editor, since the oldstyle option exists in XAML and Visual Studio 2010 and later uses WPF.

2. Syntax highlight

Another solution is to use a real oldstyle font, but with syntax highlighting for digits:

Personally, I don't know any IDE which would support that. Visual Studio, for example, let you personalize the color of numbers (for example "123D" in var a = 123D;), but not digits (for example '5' in this.label5.Text = "Hello";). But there is probably a way to write an addin for an IDE to change the syntax highlighting.


问:
What is a "template" in Perl?
I can find all sorts of weird information about templates in Perl, but nothing about what they actually are.

Are they generic types like in C++?  Is it a class-like structure?  Or maybe something else?

答:
You don't link to any of the 'weird information' you found, but there is no language construct in Perl called 'templates'.

Generally, I expect the subject of any article on Perl and templating to be about text output; a template to generate HTML, or an email, for example. The Text::Template and HTML::Template modules being canonical examples.

ContentLicense: CC BY-SA 3.0

Title: What is a "template" in Perl?


答:
I used to be a big fan of the proggy fonts, they are fixed width, very clear and distinguish 0/O 1/I very well.

But with the better fonts (eg consolas) in VS2010 and now that truetype finally works properly I don't use them as much.

Title: Are there any programming fonts with oldstyle figures?

Body:
I find that oldstyle (or text) figures are much easier to read in any context outside of simple assignment. Are there any low-ambiguity fonts, monospaced or proportional, that have text figures and other programming-friendly features, such as marked zeroes; aligned braces, operations, and other symbols; and bold and italic forms with identical width to regular?

Note. Old-style figures are numerals which are drawn with variable ascent and descent. Typically, for example, a "0" will be slightly larger than a lowercase "o"; the "6" and "9" will have have circles that are sized and placed similar to a "0", with flags extending up and down from that.

In general, if one is trying to examine numbers as numbers (e.g. parse "8675309" as "eight six seven five three oh ni-y-ine"), the "lining" forms with unified ascent and descent are easier to read. On the other hand, multi-digit numbers written with old-style numerals have different shapes. If one is comparing columns of figures, a number like "1265" will look very different from "1285", since the former will have a flag on the "6" that sticks up far above any feature of the latter.

Tabular figures are figures spaced with equal width; they may be lining or oldstyle. So all monospaced fonts have tabular figures, but most proportional fonts do not.


问:
Analyzing Memory Usage: Java vs C++ Negligible?
How does the memory usage of an integer object written in Java compare\contrast with the memory usage of a integer object written in C++? Is the difference negligible? No difference? A big difference? I'm guessing it's the same because an int is an int regardless of the language (?)

The reason why I asked this is because I was reading about the importance of knowing when a program's memory requirements will prevent the programmer from solving a given problem.

What fascinated me is the amount of memory required for creating a single Java object. Take for example, an integer object. Correct me if I'm wrong but a Java integer object requires 24 bytes of memory:

4 bytes for its int instance variable

16 bytes of overhead (reference to the object's class, garbage collection info & synchronization info)

4 bytes of padding

As another example, a Java array (which is implemented as an object) requires 48+bytes:

24 bytes of header info

16 bytes of object overhead

4 bytes for length

4 bytes for padding

plus the memory needed to store the values

How do these memory usages compare with the same code written in C++?

I used to be oblivious about the memory usage of the C++ and Java programs I wrote, but now that I'm beginning to learn about algorithms, I'm having a greater appreciation for the computer's resources.

答:
Most the answers seem to be ignoring a couple of fairly major points.

First, in an awful lot of Java, you virtually never see a raw int -- nearly all use is of Integer, so the fact that an int could be (about) the same size as an int in C or C++ is almost irrelevant, except for that (in my experience, small) percentage of code that only uses int instead of Integer.

Second, the sizes of individual objects has almost nothing to do with the memory footprint of a program as a whole. In Java, the memory footprint of the program relates primarily to how the garbage collector has been tuned. In most cases, the GC is tuned to maximize speed, which (largely) means running the GC as infrequently as possible.

I don't have a link handy at the moment, but there have been some tests showing that Java can run around the same speed as C, but to do so you have to run the GC rarely enough that it uses around 7 times as much memory. That's not because individual objects are 7 times as big, but because GC can get pretty expensive if you do it too often. Worse, GC can only release memory when it can "prove" that there's no longer any way to access an object, rather than simply when you know you're done using it. This means that even if you run the GC a lot more often to minimize memory usage, you can probably still plan on a typical program have a memory footprint that's larger. In a case like this, you might reduce the factor to 2 or 3 instead of 7. Even if you go drastically overboard, however, don't expect the two to be within, say, 10 or 20% of the same memory usage, even if the number and size of objects you've allocated are both identical1.

Depending on the situation, there's another factor that may or may not be significant: the memory occupied by the JVM itself. This is more or less fixed, so as a percentage it may be huge if the app doesn't need much storage of its own, or it may be minuscule if the app needs to store a lot. At least on my machine, even the most trivial Java app seems to occupy something like 20-25 megabytes (could be over 1000x for trivlal programs, or almost immeasurably tiny for big ones).

1 That's not to say that nobody could possibly manage to write Java with a footprint that close to what you'd get with C++. It's only to say that just having the same number/size of objects, and running the GC really frequently won't get you there as a rule.


问:
Advantages of object-oriented programming
Note: this question is an edited excerpt from a blog posting I wrote a few months ago.  After placing a link to the blog in a comment on Programmers.SE someone requested that I post a question here so that they could answer it.  This posting is my most popular, as people seem to type "I don't get object-oriented programming" into Google a lot.  Feel free to answer here, or in a comment at Wordpress.

What is object-oriented programming?
  No one has given me a satisfactory
  answer.  I feel like you will not get
  a good definition from someone who
  goes around saying “object” and
  “object-oriented” with his nose in the
  air. Nor will you get a good
  definition from someone who has done
  nothing but object-oriented
  programming. No one who understands
  both procedural and object-oriented
  programming has ever given me a
  consistent idea of what an
  object-oriented program actually does.

Can someone please give me their ideas of the advantages of object-oriented programming?

答:
OOP = data structures + message passing + inheritance, all of which are logical evolutions in programming models.

OOP can be understood (by programmers) in about 90 seconds (see my profile for a link). The concepts are very simple.

How to apply it is another matter. Just because you know how to swing a hammer doesn't mean you know how to design and build a house. ;-)

ContentLicense: CC BY-SA 2.5


问:
How can we protect the namespace of an object in Javascript?
Continuing from my previous question: Javascript simple code to understand prototype-based OOP basics
Let's say we run into console this two separate objects(even if they are called child and parent there is no inheritance between them):

```<code>var parent = {
    name: "parent",
    print: function(){
       console.log("Hello, "+this.name);
    }
};

var child = {
    name: "child",
    print: function(){
       console.log("Hi, "+this.name);
    }
};

parent.print()
// This will print: Hello, parent
child.print()
// This will print: Hi, child

temp =parent;
parent = child;
child = temp;

parent.print()
// This will now print: Hi, child
child.print()
// This will now print: Hello, parent
</code>```

Now suppose that parent is a library, as a HTML5 application in a browser this cannot do much harm because is practically running sandboxed, but now with the advent of the ChromeOS, FirefoxOS and other [Browser] OS they will also be linked to a native API, that would be a head out of the „sandbox”. Now if someone changes the namespace it would be harder for a code reviewer (either automated or not ) to spot an incorrect use if the namespaces changes.

My question would be: Are there many ways in which the above situation can be done and what can be done to protect this namespaces? (Either in the javascript itself or by some static code analysis tool)

答:
There is really very little you can do (in all browsers) to protect global variables.

However a common (good) practice is to encapsulate all of your scripts in (IIFE) functional closures.

```<code>(function() {
    var parent = {
        name: "parent",
        print: function(){
           console.log("Hello, "+this.name);
        }
    };

    var child = {
        name: "child",
        print: function(){
           console.log("Hi, "+this.name);
        }
    };

    parent.print()
    // This will print: Hello, parent
    child.print()
    // This will print: Hi, child
})();
</code>```

This means that you may only use parent and child inside the scope of that function. While that is limiting, it is also protecting. If you needed them globally, one option would be maintain a namespace object:

```<code>var myGlobals = {};

(function( global ) {
    global.parent = {
        name: "parent",
        print: function(){
           console.log("Hello, "+this.name);
        }
    };

    global.child = {
        name: "child",
        print: function(){
           console.log("Hi, "+this.name);
        }
    };

    global.parent.print()
    // This will print: Hello, parent
    global.child.print()
    // This will print: Hi, child
})(myGlobals);
</code>```

Or if you really needed them as individual globals, you could just do:

```<code>(function() {
    window.parent = {
        name: "parent",
        print: function(){
           console.log("Hello, "+this.name);
        }
    };

    window.child = {
        name: "child",
        print: function(){
           console.log("Hi, "+this.name);
        }
    };

    parent.print()
    // This will print: Hello, parent
    child.print()
    // This will print: Hi, child
})();
</code>```

But that leaves you back at square one. In this case you would need to make sure that you do something to protect those variables at the time of shuffling. Instead of writing:

```<code>temp =parent;
parent = child;
child = temp;
</code>```

You may write:

```<code>(function( parent, child ) {

    // Do some stuff.

    // Note: parent and child are references,
    // although they are switched, something like:
    //    child.hello = "hello";
    // will still edit the `parent` object in the outer scope

})(child, parent); // Pass them in swapped.
</code>```

Freeze and Seal (two new JS Object methods) are worth noting in this thread despite not exactly solving your problem nor having cross-browser support yet.

Body:
There is really very little you can do (in all browsers) to protect global variables.

However a common (good) practice is to encapsulate all of your scripts in (IIFE) functional closures.

(function() {
    var parent = {
        name: "parent",
        print: function(){
           console.log("Hello, "+this.name);
        }
    };

    var child = {
        name: "child",
        print: function(){
           console.log("Hi, "+this.name);
        }
    };

    parent.print()
    // This will print: Hello, parent
    child.print()
    // This will print: Hi, child
})();

This means that you may only use parent and child inside the scope of that function. While that is limiting, it is also protecting. If you needed them globally, one option would be maintain a namespace object:

var myGlobals = {};

(function( global ) {
    global.parent = {
        name: "parent",
        print: function(){
           console.log("Hello, "+this.name);
        }
    };

    global.child = {
        name: "child",
        print: function(){
           console.log("Hi, "+this.name);
        }
    };

    global.parent.print()
    // This will print: Hello, parent
    global.child.print()
    // This will print: Hi, child
})(myGlobals);

Or if you really needed them as individual globals, you could just do:

(function() {
    window.parent = {
        name: "parent",
        print: function(){
           console.log("Hello, "+this.name);
        }
    };

    window.child = {
        name: "child",
        print: function(){
           console.log("Hi, "+this.name);
        }
    };

    parent.print()
    // This will print: Hello, parent
    child.print()
    // This will print: Hi, child
})();

But that leaves you back at square one. In this case you would need to make sure that you do something to protect those variables at the time of shuffling. Instead of writing:

temp =parent;
parent = child;
child = temp;

You may write:

(function( parent, child ) {

    // Do some stuff.

    // Note: parent and child are references,
    // although they are switched, something like:
    //    child.hello = "hello";
    // will still edit the `parent` object in the outer scope

})(child, parent); // Pass them in swapped.

Freeze and Seal (two new JS Object methods) are worth noting in this thread despite not exactly solving your problem nor having cross-browser support yet.


问:
best way to do the compile and check cycle
I am trying to learn lua and am experimenting on my linux machine. I am not a programmer, so I am looking for your help to give me some suggestions.

What I want to accomplish is making my compile-rewrite-recompile cycle as efficient as possible.

Here is what I do.

I am using vim in one window to program. I have a shell open in another window. When I want to check my progress, I save the code in vim, switch to my shell, then execute the code.

However, this is still kind of tedious, I was there was a faster, more elegant way. Any ideas? How do you go about this problem?

答: I use emacs for the whole cycle.  You can compile a program such that the compiler messages are written to another buffer.  Click on any compiler error message and emacs will take you to the file and line that caused the error.</p>


问:
Different ways to see a monad
While learning Haskell I have faced a lot of tutorials trying to explain what are monads and why monads are important in Haskell. Each of them used analogies so it would be easier to catch the meaning.
At the end of the day, I have end up with 3 differents view of what a monad is:

View 1: Monad as a label

Sometimes I think that a monad as a label to a specific type.
For example, a function of type:

```<code>myfunction :: IO Int
</code>```

myfunction is a function that whenever is performed it will yield an Int value.
The type of the result is not Int but IO Int. So, IO is a label of the Int value warning the user to know that the Int value is the result of a process where a IO action has been made.

Consequently, this Int value has been marked as value that came from a process with IO therefore this value is "dirty". Your process is not pure anymore.

View 2: Monad as a private space where nasty things can happen.

In a system where all the process are pure and strict sometimes you need to have side-effects. So, a monad is just a little space that is allow to you for doing nasty side-effects.
In this space your are allow to escape the pure world, go the impure, make your process and then come back with a value.

View 3: Monad as in category theory

This is the view that I don't fully understand.
A monad is just a functor to the same category or a sub-category.
For example, you have the Int values and as a subcategory IO Int, that are the Int values generated after a IO process.

Are these views correct? Which is more accurate?

答:
Views #1 and #2 are incorrect in general.

Any data-type of kind * -> * can work as a label, monads are much more than that.

(With the exception of the IO monad) computations within a monad are not impure. They simply represent computations that we perceive as having side effects, but they're pure.

Both these misunderstandings come from focusing on the IO monad, which is actually a bit special.

I'll try to elaborate on #3 a bit, without getting into category theory if possible.

Standard computations

All computations in a functional programming language can be viewed as functions with a source type and a target type: f :: a -> b. If a function has more than one argument, we can convert it to an one-argument function by currying (see also Haskell wiki). And if we have just a value x :: a (a function with 0 arguments), we can convert it into a function that takes an argument of the unit type: (\_ -> x) :: () -> a.

We can build more complex programs form simpler ones by composing such functions using the . operator. For example, if we have f :: a -> b and g :: b -> c we get g . f :: a -> c. Note that this works for our converted values too: If we have x :: a and convert it into our representation, we get f . ((\_ -> x) :: () -> a) :: () -> b.

This representation has some very important properties, namely:

We have a very special function - the identity function id :: a -> a for each type a. It is an identity element  with respect to .: f is equal both to f . id and to id . f.

The function composition operator . is associative.

Monadic computations

Suppose we want to select and work with some special category of computations, whose result contains something more than just the single return value. We don't want to specify what "something more" means, we want to keep things as general as possible. The most general way to represent "something more" is representing it as a type function - a type m of kind * -> * (i.e. it converts one type to another). So for each category of computations we want to work with, we'll have some type function m :: * -> *. (In Haskell, m is [], IO, Maybe, etc.) And the category will contains all functions of types a -> m b.

Now we would like to work with the functions in such a category in the same way as in the basic case. We want to be able to compose these functions, we want the composition to be associative, and we want to have an identity. We need:

To have an operator (let's call it <=<) that composes functions f :: a -> m b and g :: b -> m c into something as g <=< f :: a -> m c. And, it must be associative.

To have some identity function for each type, let's call it return. We also want that f <=< return is the same as f and the same as return <=< f.

Any m :: * -> * for which we have such functions return and <=< is called a monad. It allows us to create complex computations from simpler ones, just as in the basic case, but now the types of return values are tranformed by m.

(Actually, I slightly abused the term category here. In the category-theory sense we can call our construction a category only after we know it obeys these laws.)

Monads in Haskell

In Haskell (and other functional languages) we mostly work with values, not with functions of types () -> a. So instead of defining <=< for each monad, we define a function (>>=) :: m a -> (a -> m b) -> m b. Such an alternative definition is equivalent, we can express >>= using <=< and vice versa (try as an exercise, or see the sources). The principle is less obvious now, but it remains the same: Our results are always of types m a and we compose functions of types a -> m b.

For each monad we create, we must not forget to check that return and <=< have the properties we required: associativity and left/right identity. Expressed using return and >>= they are called the monad laws.

An example - lists

If we choose m to be [], we get a category of functions of types a -> [b]. Such functions represent non-deterministic computations, whose results could be one or more values, but also no values. This gives rise to the so-called list monad. The composition of f :: a -> [b] and g :: b -> [c] works as follows: g <=< f :: a -> [c] means to compute all possible results of type [b], apply g to each of them, and collect all the results in a single list. Expressed in Haskell

```<code>return :: a -> [a]
return x = [x]
(<=<) :: (b -> [c]) -> (a -> [b]) -> (a -> [c])
g (<=<) f  = concat . map g . f
</code>```

or using >>=

```<code>(>>=) :: [a] -> (a -> [b]) -> [b]
x >>= f  = concat (map f x)
</code>```

Note that in this example the return types were [a] so it was possible that they didn't contain any value of type a. Indeed, there is no such requirement for a monad that the return type should have such values. Some monads always have (like IO or State), but some don't, like [] or Maybe.

The IO monad

As I mentioned, the IO monad is somewhat special. A value of type IO a means a value of type a constructed by interacting with the program's environment. So (unlike all the other monads), we cannot describe a value of type IO a using some pure construction. Here IO is simply a tag or a label that distinguishes computations that interact with the environment. This is (the only case) where the views #1 and #2 are correct.

For the IO monad:

Composition of f :: a -> IO b and g :: b -> IO c means: Compute f that interacts with the environment, and then compute g that uses the value and computes the result interacting with the environment.

return just adds the IO "tag" to the value (we simply "compute" the result by keeping the environment intact).

The monad laws (associativity, identity) are guaranteed by the compiler.

Some notes:

Since monadic computations always have the result type of m a, there is no way how to "escape" from the IO monad. The meaning is: Once a computation interacts with the environment, you cannot construct a computation from it that doesn't.

When a functional programmer doesn't know how to make something in a pure way, (s)he can (as the last resort) program the task by some stateful computation within the IO monad. This is why IO is often called a programmer's sin bin.

Notice that in an impure world (in the sense of functional programming) reading a value can change the environment too (like consume user's input). That's why functions like getChar must have a result type of IO something.

Title: Different ways to see a monad

Body:
Views #1 and #2 are incorrect in general.

Any data-type of kind * -> * can work as a label, monads are much more than that.

(With the exception of the IO monad) computations within a monad are not impure. They simply represent computations that we perceive as having side effects, but they're pure.

Both these misunderstandings come from focusing on the IO monad, which is actually a bit special.

I'll try to elaborate on #3 a bit, without getting into category theory if possible.

Standard computations

All computations in a functional programming language can be viewed as functions with a source type and a target type: f :: a -> b. If a function has more than one argument, we can convert it to an one-argument function by currying (see also Haskell wiki). And if we have just a value x :: a (a function with 0 arguments), we can convert it into a function that takes an argument of the unit type: (\_ -> x) :: () -> a.

We can build more complex programs form simpler ones by composing such functions using the . operator. For example, if we have f :: a -> b and g :: b -> c we get g . f :: a -> c. Note that this works for our converted values too: If we have x :: a and convert it into our representation, we get f . ((\_ -> x) :: () -> a) :: () -> b.

This representation has some very important properties, namely:

We have a very special function - the identity function id :: a -> a for each type a. It is an identity element  with respect to .: f is equal both to f . id and to id . f.

The function composition operator . is associative.

Monadic computations

Suppose we want to select and work with some special category of computations, whose result contains something more than just the single return value. We don't want to specify what "something more" means, we want to keep things as general as possible. The most general way to represent "something more" is representing it as a type function - a type m of kind * -> * (i.e. it converts one type to another). So for each category of computations we want to work with, we'll have some type function m :: * -> *. (In Haskell, m is [], IO, Maybe, etc.) And the category will contains all functions of types a -> m b.

Now we would like to work with the functions in such a category in the same way as in the basic case. We want to be able to compose these functions, we want the composition to be associative, and we want to have an identity. We need:

To have an operator (let's call it <=<) that composes functions f :: a -> m b and g :: b -> m c into something as g <=< f :: a -> m c. And, it must be associative.

To have some identity function for each type, let's call it return. We also want that f <=< return is the same as f and the same as return <=< f.

Any m :: * -> * for which we have such functions return and <=< is called a monad. It allows us to create complex computations from simpler ones, just as in the basic case, but now the types of return values are tranformed by m.

(Actually, I slightly abused the term category here. In the category-theory sense we can call our construction a category only after we know it obeys these laws.)

Monads in Haskell

In Haskell (and other functional languages) we mostly work with values, not with functions of types () -> a. So instead of defining <=< for each monad, we define a function (>>=) :: m a -> (a -> m b) -> m b. Such an alternative definition is equivalent, we can express >>= using <=< and vice versa (try as an exercise, or see the sources). The principle is less obvious now, but it remains the same: Our results are always of types m a and we compose functions of types a -> m b.

For each monad we create, we must not forget to check that return and <=< have the properties we required: associativity and left/right identity. Expressed using return and >>= they are called the monad laws.

An example - lists

If we choose m to be [], we get a category of functions of types a -> [b]. Such functions represent non-deterministic computations, whose results could be one or more values, but also no values. This gives rise to the so-called list monad. The composition of f :: a -> [b] and g :: b -> [c] works as follows: g <=< f :: a -> [c] means to compute all possible results of type [b], apply g to each of them, and collect all the results in a single list. Expressed in Haskell

return :: a -> [a]
return x = [x]
(<=<) :: (b -> [c]) -> (a -> [b]) -> (a -> [c])
g (<=<) f  = concat . map g . f

or using >>=

(>>=) :: [a] -> (a -> [b]) -> [b]
x >>= f  = concat (map f x)

Note that in this example the return types were [a] so it was possible that they didn't contain any value of type a. Indeed, there is no such requirement for a monad that the return type should have such values. Some monads always have (like IO or State), but some don't, like [] or Maybe.

The IO monad

As I mentioned, the IO monad is somewhat special. A value of type IO a means a value of type a constructed by interacting with the program's environment. So (unlike all the other monads), we cannot describe a value of type IO a using some pure construction. Here IO is simply a tag or a label that distinguishes computations that interact with the environment. This is (the only case) where the views #1 and #2 are correct.

For the IO monad:

Composition of f :: a -> IO b and g :: b -> IO c means: Compute f that interacts with the environment, and then compute g that uses the value and computes the result interacting with the environment.

return just adds the IO "tag" to the value (we simply "compute" the result by keeping the environment intact).

The monad laws (associativity, identity) are guaranteed by the compiler.

Some notes:

Since monadic computations always have the result type of m a, there is no way how to "escape" from the IO monad. The meaning is: Once a computation interacts with the environment, you cannot construct a computation from it that doesn't.

When a functional programmer doesn't know how to make something in a pure way, (s)he can (as the last resort) program the task by some stateful computation within the IO monad. This is why IO is often called a programmer's sin bin.

Notice that in an impure world (in the sense of functional programming) reading a value can change the environment too (like consume user's input). That's why functions like getChar must have a result type of IO something.


答: EDIT :: Oh wait, here is exactly what you are looking for! It is a plugin which allows you to run your Lua code from the editor. Also, here is a convenience plugin for editing Lua in VIM. Hope that helps.</p>

Title: best way to do the compile and check cycle

Body:
I am trying to learn lua and am experimenting on my linux machine. I am not a programmer, so I am looking for your help to give me some suggestions.

What I want to accomplish is making my compile-rewrite-recompile cycle as efficient as possible.

Here is what I do.

I am using vim in one window to program. I have a shell open in another window. When I want to check my progress, I save the code in vim, switch to my shell, then execute the code.

However, this is still kind of tedious, I was there was a faster, more elegant way. Any ideas? How do you go about this problem?


问:
When do we need to apply a software development methodology?
There are many software development methodologies - SCRUM, agile, XP, etc. - and they all have there advantages and disadvantages I suppose.

But when do we really need to apply them? Surely they are not necessary for small 1-man projects, but for large 50+ teams you can most certainly not go about ad-hoc:ing the whole thing.

So what's the line for when to use and when to not use such a methodology, if there indeed is one?

答:
Always

"no methodology" is still a methodology, just not a very good (repeatable, predictable, improvable) one


问:
How can I get more programming experience
I am going to be a third year computer science student and I have read Head first Java, Head First C, and I am currently reading C++ which is the language that I like the most since it has a good teaching style for people with experience. I am planning to either learn to make software with QT, learn objective-C(for iphone), or read Effective C++.

How can I get experience as a programmer? Do I have the skills to join an open source project or do I need to learn php, mySQL or any other language. I love programming and computer science in general although some classes can be extremely hard (theoretical computer science). I also plan to become a guru in c++ but that's not going to be anytime soon.

答:
I'd suggest you train yourself by effectively writing functional programs. Take a bigger project once you think you've got the basics. Learn the qt framework for software development and keep practicing. The best way to learn to program is by actually writing code.

I'd say reading also plays an important role, you could look for a team of developers who are hosting an open source project (Look for one on github, or other similar sites) because they could offer you valuable team development experience.


答:
ABC - ALWAYS BE CODING. It's really that simple. One of my favorite ways of getting to know a language is to write a toy interpreter for a subset of the language in the language itself or if that's not your thing then maybe a ray tracer or something else that's just big enough to be non-trivial but not so big that it can't be finished in a month or so. The point is to work on something that will force you to look at the standard library and the data abstraction facilities that the language offers. Sometimes the project is a success sometimes it's not but at the end of it I know enough about a language to know what its strengths and weaknesses are and whether I want to continue learning more. If it turns out that I like the language then every time I read an interesting paper or blog post I try to start a project in which I implement some of the ideas that were presented in the paper or the blog post. This way I'm always getting practice and learning new ideas so it sort of becomes a virtuous cycle.

Some projects that have worked really well for me in the past : interpreter for a subset of  some language, ray tracer, PEG parser generator, HTTP header parser, simple echo client/server, twitter bot for automatically posting tweets from a queue, amazon product scraper to look for deals.

Title: How can I get more programming experience

Body:
I am going to be a third year computer science student and I have read Head first Java, Head First C, and I am currently reading C++ which is the language that I like the most since it has a good teaching style for people with experience. I am planning to either learn to make software with QT, learn objective-C(for iphone), or read Effective C++.

How can I get experience as a programmer? Do I have the skills to join an open source project or do I need to learn php, mySQL or any other language. I love programming and computer science in general although some classes can be extremely hard (theoretical computer science). I also plan to become a guru in c++ but that's not going to be anytime soon.


问:
Different kinds of safety
Programming languages and programs (as wells as individual functions, objects, etc.) are often described as being "safe" in one way or another. For example, they could be "type safe", "memory safe", "exception safe", "thread safe" - even "reentrant". Each of these concepts is about preventing erroneous or damaging code from executing, which makes them pretty important considerations in language and program design.

So if I wanted to be super-pedantic about safety, what are all the different kinds of safety I could consider? Or could there be any number of them, leaving me to hope that I know all the ones which could be important for me?

The context of the question involves comparing languages like Haskell to languages like C++: pure Haskell is great if you want to guarantee type, memory and thread safety. In C++, we can circumvent any of these. So I was thinking: "If we wanted to make a perfectly safe language, what are all the kinds of 'safety' that we could consider?"

答:
Safety in all cases is about avoiding ambiguous state. If it's memory it's a question of "For a given unit of memory, what is stored there? How can one be sure?" Same with types. "For a given arbitrary piece of code, what rules does this code follow?"

The base idea is that you always want to be able to predict what output you will get, given a particular input.

Title: Different kinds of safety


问:
Bump version number in commercial software development?
Who is responsible for bumping version number in commercial software development?
How to setup policies for that?

1) for small team

2) for medium team

It is important not to forget to change the version number that self-describes that output file.

Such as AssemblyInfo.cs / resource.rc / AndroidManifest.xml

答: Version numbers are a product management / release management responsibility. It is not a developer choice. You should setup your build environment to easily allow version numbers to change. I would go as far as saying the whole build environment and build system can be setup to allow the PM or RM to set it to whatever they want. And the developer doesn't care.</p>


答:
If the version number is visible by the user, it's a public relation decision. I've seen the major number be modified as there was a user change deemed important by the marketing department but with little impact on the code, as well as big code reorganization but with few user visible change resulting in the smallest possible change in the numbering in order not to hinder upgrades.

Not that is true for commercial software as well as open source one. There is often no marketing department for later, but the rationale for the decision will be public relationship quite rapidly after the software has success. Or it will be used as way to get renewed attention or to delay that attention until one is ready.

Title: Bump version number in commercial software development?

Body:
Who is responsible for bumping version number in commercial software development?
How to setup policies for that?

1) for small team

2) for medium team

It is important not to forget to change the version number that self-describes that output file.

Such as AssemblyInfo.cs / resource.rc / AndroidManifest.xml


答:
Sometimes places like sourceforge are a bit daunting at first. A really nice way to find something to do, is trawl through the issue trackers of projects and find a bug/issue you like the sound of fixing.

On some small scale github projects this becomes much more accessible. You effectively have a direction and a purpose in trying to grok the code, instead of wading through it blindly.


答:
Assuming you have your shell pane to the right of your Vim pane, and you want to use F6 as tdammers suggested, try this mapping: map <F6> :make <Bar> silent !tmux select-pane -R<CR><C-l>. That way the shell pane is selected after make is run. You'll have to use regular tmux commands to switch back to Vim, of course.

EDIT: The <C-l> in the above mapping (which redraws the Vim screen, which is necessary as a side effect of using silent to bypass the need for pressing Enter) clears the errorlist line, which would show the first error if there was one. The mapping map <F6> :make<Bar>silent !tmux select-pane -R<CR><C-l>:cc<CR> redisplays it, but has the side effect of showing the first compilation line executed by make, if there was no error; this compilation line often takes up multiple screen lines, so you still have to hit Enter to continue.


答:
As nicely explained in Teach Yourself Programming in Ten Years, you should follow next steps :

Get interested in programming, and do some because it is fun. Make
sure that it keeps being enough fun so that you will be willing to
put in your ten years/10,000 hours.

Program. The best kind of learning is learning by doing. To put it
more technically, "the maximal level of performance for individuals
in a given domain is not attained automatically as a function of
extended experience, but the level of performance can be increased
even by highly experienced individuals as a result of deliberate
efforts to improve." (p. 366) and "the most effective learning
requires a well-defined task with an appropriate difficulty level for
the particular individual, informative feedback, and opportunities
for repetition and corrections of errors." (p. 20-21) The book
Cognition in Practice: Mind, Mathematics, and Culture in Everyday
Life is an interesting reference for this viewpoint.

Talk with other programmers; read other programs. This is more
important than any book or training course.

If you want, put in four years at a college (or more at a graduate
school). This will give you access to some jobs that require
credentials, and it will give you a deeper understanding of the
field, but if you don't enjoy school, you can (with some dedication)
get similar experience on your own or on the job. In any case, book
learning alone won't be enough. "Computer science education cannot
make anybody an expert programmer any more than studying brushes and
pigment can make somebody an expert painter" says Eric Raymond,
author of The New Hacker's Dictionary. One of the best programmers I
ever hired had only a High School degree; he's produced a lot of
great software, has his own news group, and made enough in stock
options to buy his own nightclub.

Work on projects with other programmers. Be the best programmer on
some projects; be the worst on some others. When you're the best, you
get to test your abilities to lead a project, and to inspire others
with your vision. When you're the worst, you learn what the masters
do, and you learn what they don't like to do (because they make you
do it for them).

Work on projects after other programmers. Understand a program
written by someone else. See what it takes to understand and fix it
when the original programmers are not around. Think about how to
design your programs to make it easier for those who will maintain
them after you.

Learn at least a half dozen programming languages. Include one
language that supports class abstractions (like Java or C++), one
that supports functional abstraction (like Lisp or ML), one that
supports syntactic abstraction (like Lisp), one that supports
declarative specifications (like Prolog or C++ templates), one that
supports coroutines (like Icon or Scheme), and one that supports
parallelism (like Sisal).

Remember that there is a "computer" in "computer science". Know how
long it takes your computer to execute an instruction, fetch a word
from memory (with and without a cache miss), read consecutive words
from disk, and seek to a new location on disk. (Answers here.)

Get involved in a language standardization effort. It could be the
ANSI C++ committee, or it could be deciding if your local coding
style will have 2 or 4 space indentation levels. Either way, you
learn about what other people like in a language, how deeply they
feel so, and perhaps even a little about why they feel so.

Have the good sense to get off the language standardization effort as
quickly as possible.


问:
How can we make software development best practices more interesting to people without a software background?
Where I work there are a few experienced software developers with a software background, but the majority of developers are physicists or chemists with excellent domain knowledge but limited experience when it comes to developing high quality, maintainable software.  To address this we have started running regular talks and workshops.

What topics do you think we should discuss to help make these people more effective software developers?

In particular we are struggling to gain enthusiasm for these talks as many developers do not see software as an interesting subject.  How could we make these more interesting to people without a software background?

Thanks

答: show them the benefits to them. otherwise, why should they care?


问:
How do I read API documentation?
I've been trying to read through the RoR API to try to learn things that the tutorial missed, and I haven't been able to follow it at all. The only time I've read documentation was when I needed to look up a Python module, and that was easy to understand, but I can't understand the docs for Rails. How do I read through API documentation?</p>

答:
For a start, you don't learn a language (or how to use a library) from a reference pages. That what the tutorials are for starters.

For more advanced topics, if tutorials are missing, find good blogs, or a good book.

Having said that, reference pages are there to see details of a function (for example parameters and their types).

Title: How do I read API documentation?


问:
Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?
In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements.  The result was spaghetti code and the solution was structured programming.

Similarly, pointers can have difficult to control characteristics in our programs.  C++ started with plenty of pointers, but use of references are recommended.  Libraries like STL can reduce some of our dependency.  There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code.

Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions).  Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements.

In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores.  Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use?

For example, a specific example of a system for multithread programming with multicore processors is OpenMP.  It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment.

```<code>th_id = omp_get_thread_num();
#pragma omp critical
{
  cout << "Hello World from thread " << th_id << '\n';
}
</code>```

This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP

Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this:

```<code>wait(sem);
th_id = get_thread_num();
cout << "Hello World from thread " << th_id << '\n';
signal(sem);
</code>```

In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided.  But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads.  The consequences of creating deadlock or failing to make things thread safe can be hard to manage.

Do these systems like OpenMP eliminate the problems with semaphores?

Do they move the problem somewhere else?

How do I transform my favorite semaphore using algorithm to not use semaphores anymore?

答:
Are there concurrent programming techniques and practices that one should no longer use? I'd say yes.

One early concurrent programming technique that seems rare nowadays is interrupt-driven programming. This is how UNIX worked in the 1970s. See the Lions Commentary on UNIX or Bach's Design of the UNIX Operating System. Briefly, the technique is to suspend interrupts temporarily while manipulating a data structure, and then to restore interrupts afterward. The BSD spl(9) man page has an example of this style of coding. Note that the interrupts are hardware-oriented, and the code embodies an implicit relationship between the kind of hardware interrupt and the data structures associated with that hardware. For example, code that manipulates disk I/O buffers needs to suspend interrupts from disk controller hardware while working with those buffers.

This style of programming was employed by operating systems on uniprocessor hardware. It was much rarer for applications to deal with interrupts. Some OSes had software interrupts, and I think people tried to build threading or coroutine systems on top of them, but this wasn't very widespread. (Certainly not in the UNIX world.) I suspect that interrupt-style programming is confined today to small embedded systems or real-time systems.

Semaphores are an advance over interrupts because they are software constructs (not related to hardware), they provide abstractions over hardware facilities, and they enable multithreading and multiprocessing. The main problem is that they are unstructured. The programmer is responsible for maintaining the relationship between each semaphore and the data structures it protects, globally across the entire program. For this reason I think bare semaphores are rarely used today.

Another small step forward is a monitor, which encapsulates concurrency control mechanisms (locks and conditions) with the data being protected. This was carried over into  the Mesa (alternate link) system and from there into Java. (If you read this Mesa paper, you can see that Java's monitor locks and conditions are copied almost verbatim from Mesa.) Monitors are helpful in that a sufficiently careful and diligent programmer can write concurrent programs safely using only local reasoning about the code and data within the monitor.

There are additional library constructs, such as those in Java's java.util.concurrent package, which includes a variety of highly concurrent data structures and thread pooling constructs. These can be combined with additional techniques such as thread confinement and effective immutability. See Java Concurrency In Practice by Goetz et. al. for further discussion. Unfortunately, many programmers are still rolling their own data structures with locks and conditions, when they really ought to just be using something like ConcurrentHashMap where the heavy lifting has already been done by the library authors.

Everything above shares some significant characteristics: they have multiple threads of control that interact over globally shared, mutable state. The problem is that programming in this style is still highly error-prone. It's quite easy for a small mistake to go unnoticed, resulting in misbehavior that is hard to reproduce and diagnose. It may be that no programmer is "sufficiently careful and diligent" to develop large systems in this fashion. At least, very few are. So, I'd say that multi-threaded programming with shared, mutable state should be avoided if at all possible.

Unfortunately it's not entirely clear whether it can be avoided in all cases. A lot of programming is still done in this fashion. It would be nice to see this supplanted by something else. Answers from Jarrod Roberson and davidk01 point to techniques such as immutable data, functional programming, STM, and message-passing. There is much to recommend them, and all are being actively developed. But I don't think they've fully replaced good old-fashioned shared mutable state just yet.

EDIT: here's my response to the specific questions at the end.

I don't know much about OpenMP. My impression is that it can be very effective for highly parallel problems such as numeric simulations. But it doesn't seem general-purpose. The semaphore constructs seem pretty low-level and require the programmer to maintain the relationship between semaphores and shared data structures, with all the problems I described above.

If you have a parallel algorithm that uses semaphores, I don't know of any general techniques to transform it. You might be able to refactor it into objects and then build some abstractions around it. But if you want to use something like message-passing, I think you really need to reconceptualize the entire problem.


答:
The samples in the books or the assignments at the university are good starting points to understand how the programming works and they show the possibilities for your future projects.

Work on real projects

But without a real project experience, you tend to forget the things you learned.

Problems are opportunities to show what you can

Additionally you see in are real project how complex the requirements can be and you expreince hard to knock problems. These Problems are opportunities to show what you can. You can see your weak sides that you should improve.


问:
A study shows that lines_written/time is language-independent for most programmers. Where can it be found?
A study shows that lines_written/time is language-independent and application-independent for most programmers. If this were true it would imply that the most terse a language is, the more productive a programmer can be on it.

Where can this study be found?

答:
Well top result of web search for "lines written time is programming language independent" led me to an article that attributes this to "The Mythical Man-Month" by Brooks:

Brooks is generally credited with the assertion that annual lines-of-code programmer productivity is constant,
  independent of programming language. In making this assertion, Brooks cites multiple authors including [7] and [8]. Brooks states, “Productivity seems constant in terms of elementary statements, a conclusion that is reasonable in terms of the thought a statement requires and the errors it may include.” [1] (p. 94)...

[1] F. P. Brooks. The Mythical Man-Month: Essays on Software Engineering.

  Addison Wesley, Boston, MA, 1995.

  ...

  [7] W. M. Taliaffero. Modularity. the key to system growth potential.

  IEEE Software, 1(3):245–257, July 1971.

  [8] R. W. Wolverton. The cost of developing largescale software.

  IEEE Transactions on Computers, C-23(6):615–636, June 1974.

Article quoted above is "Do Programming Languages Affect Productivity? A Case Study Using Data from Open Source Projects" by D. Delorey, C. Knutson, S. Chun.

For the sake of completeness note that article authors are skeptical about mentioned assumption:

This statement, as well as the works it cites... appears to be based primarily on anecdotal evidence.

Quite the opposite, they claim:

We examine data collected from the CVS repositories of 9,999 open source projects hosted on SourceForge.net to test this assumption for 10 of the most popular programming languages in use in the open source community. We find that for 24 of the 45 pairwise comparisons, the programming language is a significant factor in determining the rate at which source code is written, even after accounting for variations between programmers and projects


问:
Use cases for "private" interfaces?
I was wondering if there was a valid use case for being able to properly define the specific internal properties and functions of a class in a way similar to how an interface defines the public properties and functions of a class.

Imagine the task that you have to build a class that describes a human being.

Obviously, each human is a humanoid creature but not every humanoid creature is a human so you'd probably have an interface IHumanoid with functions like these (since it isn't useful to hardcode the body plan into the class):

```<code>public interface IHumanoid {
    function get head():IHead;
    function get torso():ITorso;
    function get leftArm():IArm;
    function get rightArm():IArm;
    function get leftLeg():ILeg;
    function get rightLeg():ILeg;
}
</code>```

Further and also obviously, each human is a mammal but not every mammal is a human, so there's probably another interface IMammal with two definitions for males and females floating around somewhere:

```<code>public interface IMammal {
    function procreate(partner:IMammal):void;
}

public interface IMaleMammal extends IMammal {
    function inseminate(female:IFemaleMammal):void;
}

public interface IFemaleMammal extends IMammal {
    function conceive(partner:IMaleMammal):Boolean;
    function giveBirth():IMammal;
    function nurse(offspring:IMammal):void;
}
</code>```

Thus our class probably looks something like this now:

```<code>public class Human implements IHumanoid, IMammal {
    private var _head:IHead;
    private var _torso:ITorso;
    private var _leftArm:IArm;
    private var _rightArm:IArm;
    private var _leftLeg:ILeg;
    private var _rightLeg:ILeg;

    public function Human() {
        // ctor...
    }

    public function get head():IHead {
        return _head;
    }

    public function get torso():ITorso {
        return _torso;
    }

    public function get leftArm():IArm {
        return _leftArm;
    }

    public function get rightArm():IArm {
        return _rightArm;
    }

    public function get leftLeg():ILeg {
        return _leftLeg;
    }

    public function get rightLeg():ILeg {
        return _rightLeg;
    }

    public function procreate(partner:IMammal):void {
        // "abstract" function
    }
}

public class MaleHuman extends Human implements IMaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IFemaleMammal) {
            inseminate(partner);
        }
    }

    public function inseminate(female:IFemaleMammal):void {
        female.conceive(this);
    }
}

public class FemaleHuman extends Human implements IFemaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IMaleMammal) {
            conceive(partner);
        }
    }

    public function conceive(partner:IMaleMammal):Boolean {
        // ...
    }

    public function giveBirth():IMammal {
        // ...
    }

    public function nurse(offspring:IMammal):void {
        // ...
    }
}
</code>```

From this we can implement our classes further and everything's working nice and fine until we get the task to use the existing interfaces to implement some other classes. Perhaps a gorilla, an orca and a platypus.

Ignoring the massive issue the platypus will pose to our current interface structure (*cough* egg  laying mammal *cough*), we have the "problem" that nothing prevents us from giving the gorilla 2 brains, the orca 8 lungs and the platypus half a dozen livers. And while we might be disciplined enough to follow the structure mammals typically have we cannot guarantee the same if we open the API for other developers who might code some seriously screwed up things which still look okay to the outside world.

Therefore I was wondering if there was a valid use case to create something like a "private interface" which defines non-public functions and properties. Perhaps something along these lines:

```<code>public structure SMammal {
    function get brain():IBrain;
    function get liver():ILiver;
    function get leftLung():ILung;
    function get rightLung():ILung;
    function get leftKidney():IKidney;
    function get rightKidney():IKidney;
}

public class Human implements IHumanoid, IMammal follows SMammal {
    private function get brain():IBrain {
        // ...
    }

    private function get liver():ILiver {
        // ...
    }

    // etc. etc.
}
</code>```

Does such a feature exist in any programming language? Can abstract classes be used to solve this? Or shouldn't we care about this at all as long as the public interface somehow works as expected?

答:
As an interface type is by default a public member everything within it should be public but I have seen this:

https://stackoverflow.com/questions/792908/what-is-a-private-interface

from msdn:

Interfaces consist of methods, properties, events, indexers, or any
  combination of those four member types. An interface cannot contain
  constants, fields, operators, instance constructors, destructors, or
  types. It cannot contain static members. Interfaces members are
  automatically public, and they cannot include any access modifiers.

http://msdn.microsoft.com/en-us/library/ms173156.aspx

Title: Use cases for "private" interfaces?


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
You're getting good answers here. I would only caution - people think abstraction is somehow this wonderful thing that needs to be put on a pedestal, and that you can't get enough of. It is not. It is just common sense. It is just recognizing the similarities between things, so you can apply a problem solution to a range of problems.

Permit me a peeve...

High on my list of annoyances is when people speak of "layers of abstraction" as if that's a good thing. They make "wrappers" around classes or routines they don't like, and call them "more abstract", as if that will make them better. Remember the fable of the "Princess and the Pea"? The princess was so delicate that if there was a pea under her mattress she wouldn't be able to sleep, and adding more layers of mattresses would not help. The idea that adding more layers of "abstraction" will help is just like that - usually it doesn't. It just means that any change to the base entity has to be rippled through multiple layers of code.

Title: What is abstraction?


问:
Why are errors named as "Exception" but not as "Error" in programming languages?
I've been thinking about that for quite a while actually. I am not a native English speaker myself but still, I have years of programming experience and I always asked myself this. Why is it named as Exception but not Error since they are errors?

It could be PageNotFoundError instead of PageNotFoundException!

答:
Commonly Exception is used to name an event which is not correct but can be recovered from, like an out_of_range exception in C++, which is thrown when accessing an element in a vector or array that doesn't exist. Clearly such an event is not correct, but it happening shouldn't mean your whole program crashes.

On the other hand errors are usually used to name something that should crash everything, something like a stack overflow is an example of an event that should terminate the program as the program can't handle it internally. In other words: an error is major, while an exception is comparatively minor.

ContentLicense: CC BY-SA 4.0


答:
When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error. Once thrown, an exception is handled by the application or by the default exception handler.

An error thows an exception that details the error, so not everything is an error that is an exception if that makes sense ;), for instance an noneimplemetedexception shouldnt be an error but thows an exception.

http://msdn.microsoft.com/en-us/library/system.exception.aspx

Title: Why are errors named as "Exception" but not as "Error" in programming languages?

Body:
I've been thinking about that for quite a while actually. I am not a native English speaker myself but still, I have years of programming experience and I always asked myself this. Why is it named as Exception but not Error since they are errors?

It could be PageNotFoundError instead of PageNotFoundException!


答:
They don't need to be errors at all.  The fact that the page is not there may be just an interesting fact rather than an actual error.  They seem to get used as errors almost all the time, I admit.  But sometimes they're used to break out of loops, or let you know that a string is not a valid number.  They can be used to hold and return vast amounts of useful data--as part of a fairly normal return.  (Some languages are a bit slow with their exceptions, in that case throwing them frequently is a bad idea.)  In theory anyway, an exception merely means "don't do a normal return, go up the call stack until you find someone interested in this."

Even a null pointer exception might not mean much to you.  You call someone else's code, and then catch a null pointer exception because you know it's apt to blow up, print a message saying whose fault it is, and carry on and get your job done.


答:
Here are the references I know of:

“An Empirical Comparison of Seven Programming Languages” by Lutz Prechlt, University of Karlsruhe. http://www.openfoundry.org/of/download/pyzope/1.0.0/article.pdf

1968, referenced in Mythical Man-Month: PL/I lines/year comparable to Assembler words/year

1971, referenced in Mythical Man-Month: Assembler, Fortran, Cobol: roughly equal

1981: “Amount of effort per source statement was highly independent of language level”  (Barry W. Boehm’s “Software Engineering Economics” p. 477)

1970: High level languages 3 times as productive as Assembler

Walston-Felix, 1977 "A method of programming measurement and estimation", IBM Syst. J., 16, 1, 1977, pp. 54-73.

Nelson, 1978 "Software data collection and analysis", Rome Air Development Center, Rome, NY, September, 1978

References found in:

Chapter 8 of “The Mythical Man-Month” by Fred Brooks

Barry W. Boehm’s “Software Engineering Economics” p. 477

Title: A study shows that lines_written/time is language-independent for most programmers. Where can it be found?

Body:
A study shows that lines_written/time is language-independent and application-independent for most programmers. If this were true it would imply that the most terse a language is, the more productive a programmer can be on it.

Where can this study be found?


答:
The mechanism of exceptions is not always used to signal errors. Exceptions are thrown in out of the ordinary situations that require a separate code path to process, including errors. For example, a user providing a name of a file that does not exist, or entering a letter instead of a digit in a numeric field, are exceptional situations requiring special handling, but these are not errors.

In some programming environments, such as Java, special Error objects are provided to report "true errors", situations that a reasonable application should not attempt to handle. These objects are delivered using the same mechanism that is used for delivering exceptions, but they have a special meaning of signals of unrecoverable situations.


答:
View 1: Monad as a label

"Consequently, this Int value has been marked as value that came from a process with IO therefore this value is "dirty"."

"IO Int" is not in general a Int value (although it may be in some cases such as "return 3"). It is a procedure which outputs some Int value. Different executions of this "procedure" may yield different Int values.

A monad m, is an embedded (imperative) "programming language": within this language it is possible to define some "procedures". A monadic value (of type m a), is a procedure in this "programming language" which outputs a value of type a.

For example:

```<code>foo :: IO Int
</code>```

is some procedure which outputs a value of type Int.

Then:

```<code>bar :: IO (Int, Int)
bar = do
  a <- foo
  b <- foo
  return (a,b)
</code>```

is some procedure which outputs two (possibly different) Ints.

Every such "language" supports some operations:

two procedures (ma and mb) may be "concatenated": you can creates a a larger procedure (ma >> mb) made of the first one then the second one;

what's more the output (a) of the first one may affect the second one (ma >>= \a -> ...);

a procedure (return x) may yield some constant value (x).

The different embedded programming languages differ on the kind things they support such as:

yielding random values;

"forking" (the [] monad);

exceptions (throw/catch) (The Either e monad);

explicit continuation/callcc support;

sending/receiving messages to other "agents";

create, set and read variables (local to this programming language) (the ST monad).

Title: Different ways to see a monad

Body:
While learning Haskell I have faced a lot of tutorials trying to explain what are monads and why monads are important in Haskell. Each of them used analogies so it would be easier to catch the meaning.
At the end of the day, I have end up with 3 differents view of what a monad is:

View 1: Monad as a label

Sometimes I think that a monad as a label to a specific type.
For example, a function of type:

```<code>myfunction :: IO Int
</code>```

myfunction is a function that whenever is performed it will yield an Int value.
The type of the result is not Int but IO Int. So, IO is a label of the Int value warning the user to know that the Int value is the result of a process where a IO action has been made.

Consequently, this Int value has been marked as value that came from a process with IO therefore this value is "dirty". Your process is not pure anymore.

View 2: Monad as a private space where nasty things can happen.

In a system where all the process are pure and strict sometimes you need to have side-effects. So, a monad is just a little space that is allow to you for doing nasty side-effects.
In this space your are allow to escape the pure world, go the impure, make your process and then come back with a value.

View 3: Monad as in category theory

This is the view that I don't fully understand.
A monad is just a functor to the same category or a sub-category.
For example, you have the Int values and as a subcategory IO Int, that are the Int values generated after a IO process.

Are these views correct? Which is more accurate?

Body:
View 1: Monad as a label

"Consequently, this Int value has been marked as value that came from a process with IO therefore this value is "dirty"."

"IO Int" is not in general a Int value (although it may be in some cases such as "return 3"). It is a procedure which outputs some Int value. Different executions of this "procedure" may yield different Int values.

A monad m, is an embedded (imperative) "programming language": within this language it is possible to define some "procedures". A monadic value (of type m a), is a procedure in this "programming language" which outputs a value of type a.

For example:

foo :: IO Int

is some procedure which outputs a value of type Int.

Then:

bar :: IO (Int, Int)
bar = do
  a <- foo
  b <- foo
  return (a,b)

is some procedure which outputs two (possibly different) Ints.

Every such "language" supports some operations:

two procedures (ma and mb) may be "concatenated": you can creates a a larger procedure (ma >> mb) made of the first one then the second one;

what's more the output (a) of the first one may affect the second one (ma >>= \a -> ...);

a procedure (return x) may yield some constant value (x).

The different embedded programming languages differ on the kind things they support such as:

yielding random values;

"forking" (the [] monad);

exceptions (throw/catch) (The Either e monad);

explicit continuation/callcc support;

sending/receiving messages to other "agents";

create, set and read variables (local to this programming language) (the ST monad).


答:
I don't have an etymological research about the origins of that, but I can understand that using the term "Error" may not be precise in all situations; also as almostSharepointMaster mentioned, it is better to think of the error and the exception thrown as separated entities.

When you're in a high-level programing language, it makes sense to assume that an exception is always caused by an error, although I agree also with dasblinkenlight that even then an exception not always is the consequence of an error. I, for instance, use exceptions to terminate threads collaboratively.

The first time I saw the term "exception" was in the 80386 Assembly manual. I remember that when I saw it looked instantly natural to me. To call that an error would not be correct, because there are no errors in Assembly; there are simply conditions the processor can't deal with (if that's an error - from the programmer, the user or the system - well, the processor is completely agnostic to that). I don't know if Intel really originated the term or not, but maybe...


答:
do I need to learn php, mySQL or any other language.

Yes sir, please consider the languages of the world wide web.
HTML5, CSS3, and JavaScript.

Here is why:

They are quick to learn, and increasingly rich to implement.

They no longer just write web, but os, server and, database as well.

Most Importantly *

They are now being used to re-define Computer Science 101 - by the creator of jQuery, John Resig.

Don't shoot the messenger, just check this link to khan school academy.

c/c++/c# design patterns transfer to JS there.

Hope that helps.


问:
Javascript simple code to understand prototype-based OOP basics
I know Javascript for some time, although I am not a heavy user, I know it the first from the time when Netscape was my browser. I pretty much understand the main things, but since JavaScript approach to OOP is prototypical I have some problem grasping it.

One problem to add to this it seems that things can be done in more than one way, and here is where books don't help much because they put all the examples on the table making it hard to keep the pace.

What I need for start is only one way of doing it, if someone can help me with the simplest code possible an example where I can see how the prototypal OOP model works?

To be helpful the code should have an inherited object, to access a parent's property and its inherited properties and a parent's function, to overwrite a parent's function and and have an instance of a multiple inheritance where an object inherits two other objects.

答:
The hilarious expert @venkat_s shares an analogy to grasp prototypal inheritance.

Here is a sample of his humor, "The thing about JavaScript is, it doesn't yell at you. It is your friend. It wont tell you when something is wrong, it will just stop working. Stop calling you"

For inheritance he continued, "The prototype is like a backpack - to the object. For everything in JavaScript that is an object - it has a backpack, and you can put stuff in it. And all your objects can access it."

Hope that helps.


答: The way to do it, if you insist on pulling info from the API w/o using as what it really is - a reference manual - would be to come up with a small program for each item in the reference/API docs and actually create code for it.  In other words, to learn code, you must code, end of the day, that's the only real solution.</p>

Title: How do I read API documentation?

Body: I've been trying to read through the RoR API to try to learn things that the tutorial missed, and I haven't been able to follow it at all. The only time I've read documentation was when I needed to look up a Python module, and that was easy to understand, but I can't understand the docs for Rails. How do I read through API documentation?</p>


答:
Does such a feature exist in any programming language? Can abstract classes be used to solve this? Or shouldn't we care about this at all as long as the public interface somehow works as expected?

It sure does. Pretty much any feature exists in some language.

For example, in Objective-C++ (iOS/Mac programming) it's standard procedure for a class to have at least two interfaces. On that is public, and one that is private. Sometimes they'll also have extra interfaces that are defined elsewhere (eg, the low level string class has an interface for performing GUI screen drawing operations on the string, which is defined in a completely separate framework/library from the one that defines the string class).

Basically the way I treat public/private is simple:

Public interface elements can never be changed. Whenever you refactor or improve your code, the public interface still needs to behave exactly the same as before.

Private interfaces on the other hand, can be changed or completely removed whenever you want. As long as you update all the code in the class to understand the new behaviour, you're fine. Often the public interface will be full of one or two line methods that hand the actual work over to the private interface.

Objective-C++ also has the concept of "protected" in the interface, where something is available to subclasses but not external classes.

Usually my code is split about half and half between public and private. I don't use protected much at all, though it does come in handy once in a while.

Title: Use cases for "private" interfaces?

Body:
I was wondering if there was a valid use case for being able to properly define the specific internal properties and functions of a class in a way similar to how an interface defines the public properties and functions of a class.

Imagine the task that you have to build a class that describes a human being.

Obviously, each human is a humanoid creature but not every humanoid creature is a human so you'd probably have an interface IHumanoid with functions like these (since it isn't useful to hardcode the body plan into the class):

```<code>public interface IHumanoid {
    function get head():IHead;
    function get torso():ITorso;
    function get leftArm():IArm;
    function get rightArm():IArm;
    function get leftLeg():ILeg;
    function get rightLeg():ILeg;
}
</code>```

Further and also obviously, each human is a mammal but not every mammal is a human, so there's probably another interface IMammal with two definitions for males and females floating around somewhere:

```<code>public interface IMammal {
    function procreate(partner:IMammal):void;
}

public interface IMaleMammal extends IMammal {
    function inseminate(female:IFemaleMammal):void;
}

public interface IFemaleMammal extends IMammal {
    function conceive(partner:IMaleMammal):Boolean;
    function giveBirth():IMammal;
    function nurse(offspring:IMammal):void;
}
</code>```

Thus our class probably looks something like this now:

```<code>public class Human implements IHumanoid, IMammal {
    private var _head:IHead;
    private var _torso:ITorso;
    private var _leftArm:IArm;
    private var _rightArm:IArm;
    private var _leftLeg:ILeg;
    private var _rightLeg:ILeg;

    public function Human() {
        // ctor...
    }

    public function get head():IHead {
        return _head;
    }

    public function get torso():ITorso {
        return _torso;
    }

    public function get leftArm():IArm {
        return _leftArm;
    }

    public function get rightArm():IArm {
        return _rightArm;
    }

    public function get leftLeg():ILeg {
        return _leftLeg;
    }

    public function get rightLeg():ILeg {
        return _rightLeg;
    }

    public function procreate(partner:IMammal):void {
        // "abstract" function
    }
}

public class MaleHuman extends Human implements IMaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IFemaleMammal) {
            inseminate(partner);
        }
    }

    public function inseminate(female:IFemaleMammal):void {
        female.conceive(this);
    }
}

public class FemaleHuman extends Human implements IFemaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IMaleMammal) {
            conceive(partner);
        }
    }

    public function conceive(partner:IMaleMammal):Boolean {
        // ...
    }

    public function giveBirth():IMammal {
        // ...
    }

    public function nurse(offspring:IMammal):void {
        // ...
    }
}
</code>```

From this we can implement our classes further and everything's working nice and fine until we get the task to use the existing interfaces to implement some other classes. Perhaps a gorilla, an orca and a platypus.

Ignoring the massive issue the platypus will pose to our current interface structure (*cough* egg  laying mammal *cough*), we have the "problem" that nothing prevents us from giving the gorilla 2 brains, the orca 8 lungs and the platypus half a dozen livers. And while we might be disciplined enough to follow the structure mammals typically have we cannot guarantee the same if we open the API for other developers who might code some seriously screwed up things which still look okay to the outside world.

Therefore I was wondering if there was a valid use case to create something like a "private interface" which defines non-public functions and properties. Perhaps something along these lines:

```<code>public structure SMammal {
    function get brain():IBrain;
    function get liver():ILiver;
    function get leftLung():ILung;
    function get rightLung():ILung;
    function get leftKidney():IKidney;
    function get rightKidney():IKidney;
}

public class Human implements IHumanoid, IMammal follows SMammal {
    private function get brain():IBrain {
        // ...
    }

    private function get liver():ILiver {
        // ...
    }

    // etc. etc.
}
</code>```

Does such a feature exist in any programming language? Can abstract classes be used to solve this? Or shouldn't we care about this at all as long as the public interface somehow works as expected?


答:
In Python, they are named as ABCError
Eg: KeyError, IndexError

http://docs.python.org/library/exceptions.html

So I think it depends on language that you use.


答:
In iOS/Mac programming, we have both Exceptions and Errors in a single language.

At least in that environment an exception is "non-recoverable", while an error is "recoverable".

For example:

if you have an array with 10 items, and you try to access the item at index 30 - that will be an exception. You made a mistake in your programming.

if you try to download a URL but there is no internet connection, that is to be expected and you should present some kind of message to the user.

Exceptions typically crash your app, while errors typically return nil and an error object (returned as a by reference method parameter). You can catch exceptions with a try/catch/finally block but it's recommended never to use this language feature - if it is possible to recover from an exception in any way, then you shouldn't be throwing an exception at all (you should return an error object instead).


问:
Some questions about ClearCase
I am a mercurial person. I even use it as an incremental backup tool. I used to use SVN and CVS.

In a recent project, I had to to use clearcase and encountered lots of issues with it. For example, I could not figure out how to recursively include a whole tree of code without writing a script or using awk or find. Is there a way to accomplish this easier?

I also believe (but not sure) that clearcase integrates issue/bug management with the code. I would not like to have the managing of my code revisioning tightly encumbered with the issues, any suggestions?

My further questions are:

Is clearcase in obsolence as a version control env? Is it likely that in the project I am working compelling me to use clearcase simply because it is a legacy project?

It gives me an impression that it is obsolete, over-engineered and should be phased out. Is that the current situation with clearcase among programmers?

Are there compelling reasons/features/functionality in clearcase that it is preferred over SVN, GIT or Mercurial?

Perhaps, there is a whole ecosphere of reasons why the project is using clearcase and that I need to drop my mercurial mentality and spend time getting immersed in the clearcase ecosphere I have yet to discover?

Is the lack of features in clearcase the reason for the lack of features in the clearcase GUIs?

答:
Is clearcase in obsolence as a version control env? Is the project I am working compelling me to use clearcase simply because it is a legacy project?

Yes. It is the evolution of an old SCM started with Atria Software in 1992.

There is no reason to use it except because of "group policy" (IBM Rational ClearCase can be part, for instance, an IBM license/materiel contract and package which includes much more than just that product).

It gives me an impression that it is obsolete, over-engineered and should be phased out. Is that the current situation with clearcase among programmers?

Yes. Its main issue is its scalability: when you merge thousands of files or do anything involving a large number of (UCM activity, UCM baselines, ...), it is just too slow.

I have seen merges (UCM deliver mainly) which took hours, even a full day, even for a trivial merge.

Git or Mercurial would have merged the same number of files within seconds.

I currently phase out that software for others (free like Git, or not free like Rational Team Concert, which is much better than ClearCase, has private commits like DVCS have, and has merges which takes seconds, not hours)

Are there compelling reasons/features/functionality in clearcase that it is preferred over SVN, GIT or Mercurial?

As I explain in "Choosing between UCM and base ClearCase" and "ClearCase UCM - best practices using components", its UCM methodology (shipped with ClearCase) is full of good idea, and its branch/merge model is quite clear, well received by developers.

Its implementation (of UCM, or of merging) is terrible (because it doesn't scale well when the numbers of files increases)

It is different from a DVCS (Git, Mercurial): see "What are the basic clearcase concepts every developer should know?" for a comparison.

Perhaps, there is a whole ecosphere of reasons why the project is using clearcase and that I need to drop my mercurial mentality and spend time getting immersed in the clearcase ecosphere I have yet to discover.

Errr no. There is a large base of ClearCase licenses still active, which is why the product is still supported.

So, the unusability of clearcase to me certainly has a lot to do with the lack of GUI features. Is the drought of features in clearcase the reason for the drought of features in the clearcase GUIs?

The GUI is a shame, completely synchronous, which means you have to wait after each click for ClearCase to query and get back all the (elements, UCM activities, streams, ...).

Title: Some questions about ClearCase


问:
Company PC refresh, laptop or desktop?
My company is getting PC refreshes with a choice of to have a desktop or laptop.  Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time?

I'm not asking what would be better for coding, but more for convenience and productivity.  I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.

答:
Both

Don't be cheap. If you have to work away from your desk, a laptop is required. If you have serious work to do at your desk, a desktop (with dual monitors, if not three) is far faster for less money.

Title: Company PC refresh, laptop or desktop?


问:
What is the best approach to getting to know a big system like a CMS or forum system which has no documentation?
My problem is the following; I need to get to know a totally new system, for example Wordpress, Drupal, or a framework like Symfony, or maybe a big forum system like PhpBB.

Let's suppose it has no documentation at all, but the code is good.

What I end up doing is that I start at index.php and click the first include, so this takes me to the next file. But then it requests another file and that file request another, so at the end I even forget where I started and have no clue which was the previous request.

So my question is, is there a good way to do this ? Like drawing a chart of the application flow or something. When I want to get to know a new system, at first I would like to get the "big picture" about what comes after what, and what files do what part of the system, what function get called when, things like these.

Basically all I want to do is able to write an Application flow like this when I start with a new system.

Is there a nice way tot do this without taking too much time and confusion?

Are there any software or debugging tools for this?

Are there any chart types for this situation which I can apply here?

Can you suggest small tricks or tips how you get to know big systems and what are you looking first without digging into the code too deeply wasting too much time on not-really-important-parts?

答:
This question is very broad, so just some general advice.

Is there a nice way tot do this without taking too much time and confusion ?

I know only one: ask the authors of the system if they can give you some explanation. If you cannot grasp any of the authors, you will have to start reengineering - no shortcut.

Are there any softwares or debugging tools for this ?

Just the same tools you use to debug your own programs. If the system is written mostly in PHP, for example, use your favorite PHP debugger.

Are there any chart types for this situation which I can apply here ?

You already suggested flow charts by yourself. Actually, if there is an underlying database, I would add an ER model (or utilize an UML class diagram as ERM replacement).

Can you suggest small tricks or tips how you get to know big systems and what are you
  looking first without digging into the code too deeply wasting too much time on
  not-really-important-parts ?

The only general hint I can give you here: start to analyse the data model (and whatever technology is used to store persistent data). But honestly, the right thing to do depends heavily on the system, and what you are trying to accomplish.


问:
In what language should I name my business classes?
I'm requesting best practice with this question. This is only an issue if the customer company is strictly national has a native language other than English, I think.

If the customer has a lot of mainly very domain specific (say, German) expressions, mixed with some lesser domain specific namings. The language of our code comments, class/method/variable names is English. Would you translate all domain specific names?

答:
I'm working in Germany and I prefer to pick English.

Sometimes e.g. domain specific things like creating an module to "DATEV" (german invoice/billing software) I do use German names. Some German words cannot be translated properly, e.g. "Referenzbuchungsnummer" (ReferenceBookingNum?) or "Sachkontenlaenge" (..?). Also I do think that domain specific things would be ending in maintenance horror. Maybe you would remember that ReferenceBookingNum would relate to "Referenzbuchungsnummer", but what about your co-workers? They have to study internal documentation about naming, if documentation exists. They won't be very familiar with the module without having proper names. It's an unnecessary complexity if all other developer are German too. But "CakeFactory" sounds much better than "KeksFabrik" ;)

So it all depends.


答:
I think this has more to do with "evolution" of error handling. With C/C++ (before exception handling was added) languages, if a function failed, the only way to tell was through the return value (e.g. HRESULT in win32). So typically you ended up catching exit codes of each function call and do a check. This approach makes code messier. And lot of times developers will just avoid adding these checks out of laziness.

With the introduction of exception handling, developers now had two options to raise an  error. So the "exception" word was used to distinguish errors from "exit status" errors. After a period of time, exception handling has become a popular way to propagate errors because code is much easier to read, maintain and there can be a single place where you can have error handling logic.


答:
You will find it differntly interpreted in different programming language implementations. As dasblinkenlight said that's a java point of view of having a demarcation between Error and Exception. In many programming languages exceptions are violations which can be handled or allowed to be bubbled up to pass on to the highest possible code module.
Errors generally are situations where your language's runtime container handles (and many cases just halt the execution).</p>