问:
How to write useful Java programs without using mutable variables
I was reading an article about functional programming where the writer states

```<code>(take 25 (squares-of (integers)))
</code>```

Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.

Is it possible to achieve this in Java? Supposing you are required to print the squares of first 15 integers, could you write a for or while loop without using variables?

Mod notice

This question is not a code golf contest. We are looking for answers that explain the concepts involved (ideally without repeating earlier answers), and not just for yet another piece of code.

答:
Short version:

In order to make single-assignment style work reliably in Java, you'd need (1) some kind of immutable-friendly infrastructure, and (2) compiler- or runtime-level support for tail-call elimination.

We can write much of the infrastructure, and we can arrange things to try to avoid filling the stack.  But as long as each call takes a stack frame, there will be a limit on how much recursion you can do.  Keep your iterables small and/or lazy, and you shouldn't have major issues.  At least most of the problems you'll run into don't require returning a million results at once.  :)

Also note, since the program has to actually effect visible changes in order to be worth running, you can't make everything immutable.  You can, however, keep the vast majority of your own stuff immutable, using a tiny subset of essential mutables (streams, for example) only at certain key points where the alternatives would be too onerous.

Long version:

Simply put, A Java program can not totally avoid variables if it wants to do anything worth doing.  You can contain them, and thus restrict mutability to a huge degree, but the very design of the language and API -- along with the need to eventually change the underlying system -- make total immutability infeasible.

Java was designed from the start as an imperative, object-oriented language.

Imperative languages nearly always depend on mutable variables of some kind.  They tend to favor iteration over recursion, for example, and nearly all iterative constructs -- even while (true) and for (;;)! -- are utterly dependent on a variable somewhere changing from iteration to iteration.

Object-oriented languages pretty much envision every program as a graph of objects sending messages to each other, and in nearly all cases, responding to those messages by mutating something.

The end result of those design decisions is that without mutable variables, Java has no way to change the state of anything -- even something as simple as printing "Hello world!" to the screen involves an output stream, which involves sticking bytes in a mutable buffer.

So, for all practical purposes, we're limited to banishing the variables from our own code.   OK, we can kinda do that.  Almost.  Basically what we'd need is to replace almost all iteration with recursion, and all mutations with recursive calls returning the changed value. like so...

```<code>class Ints {
     final int value;
     final Ints tail;

     public Ints(int value, Ints rest) {
         this.value = value;
         this.tail = rest;
     }
     public Ints next() { return this.tail; }
     public int value() { return this.value; }
}

public Ints take(int count, Ints input) {
    if (count == 0 || input == null) return null;
    return new Ints(input.value(), take(count - 1, input.next()));
}

public Ints squares_of(Ints input) {
    if (input == null) return null;
    int i = input.value();
    return new Ints(i * i, squares_of(input.next()));
}
</code>```

Basically, we build a linked list, where each node is a list in itself.  Each list has a "head" (the current value) and a "tail" (the remaining sublist).  Most functional languages do something akin to this, because it's very amenable to efficient immutability.  A "next" operation just returns the tail, which is typically passed to the next level in a stack of recursive calls.

Now, this is an extremely oversimplified version of this stuff.  But it's good enough to demonstrate a serious problem with this approach in Java.  Consider this code:

```<code>public function doStuff() {
    final Ints integers = ...somehow assemble list of 20 million ints...;
    final Ints result = take(25, squares_of(integers));
    ...
}
</code>```

Although we only need 25 ints for the result, squares_of doesn't know that.  It is going to return the square of every number in integers.  Recursion 20 million levels deep causes pretty big problems in Java.

See, the functional languages you'd typically do wackiness like this in, have a feature called "tail call elimination".  What that means is, when the compiler sees code's last act being to call itself (and return the result if the function's non-void), it uses the current call's stack frame instead of setting up a new one and does a "jump" instead of a "call" (so the stack space used remains constant).  In short, it goes about 90% of the way toward turning tail-recursion into iteration.  It could deal with those billion ints without overflowing the stack.  (It'd still eventually run out of memory, but assembling a list of a billion ints is going to mess you up memorywise anyway on a 32-bit system.)

Java doesn't do that, in most cases.  (It depends on the compiler and runtime, but Oracle's implementation doesn't do it.)  Each call to a recursive function eats up a stack frame's worth of memory.  Use up too much, and you get a stack overflow.  Overflowing the stack all but guarantees the death of the program.  So we have to make sure not to do that.

One semi-workaround...lazy evaluation.  We still have the stack limitations, but they can be tied to factors we have more control over.  We don't have to calculate a million ints just to return 25.  :)

So let's build us some lazy-evaluation infrastructure.  (This code was tested a while back, but i've modified it quite a bit since then; read the idea, not the syntax errors.  :))

```<code>// Represents something that can give us instances of OutType.
// We can basically treat this class like a list.
interface Source<OutType> {
     public Source<OutType> next();
     public OutType value();
}

// Represents an operation that turns an InType into an OutType.
// Note, these can be the same type.  We're just flexible like that.
interface Transform<InType, OutType> {
    public OutType appliedTo(InType input);
}

// Represents an action (as opposed to a function) that can run on
// every element of a sequence.
abstract class Action<InType> {
    abstract void doWith(final InType input);
    public void doWithEach(final Source<InType> input) {
        if (input == null) return;
        doWith(input.value());
        doWithEach(input.next());
    }
}

// A list of Integers.
class Ints implements Source<Integer> {
     final Integer value;
     final Ints tail;
     public Ints(Integer value, Ints rest) {
         this.value = value;
         this.tail = rest;
     }
     public Ints(Source<Integer> input) {
         this.value = input.value();
         this.tail = new Ints(input.next());
     }
     public Source<Integer> next() { return this.tail; }
     public Integer value() { return this.value; }
     public static Ints fromArray(Integer[] input) {
         return fromArray(input, 0, input.length);
     }
     public static Ints fromArray(Integer[] input, int start, int end) {
         if (end == start || input == null) return null;
         return new Ints(input[start], fromArray(input, start + 1, end));
     }
}

// An example of the spiff we get by splitting the "iterator" interface
// off.  These ints are effectively generated on the fly, as opposed to
// us having to build a huge list.  This saves huge amounts of memory
// and CPU time, for the rather common case where the whole sequence
// isn't needed.
class Range implements Source<Integer> {
    final int start, end;
    public Range(int start, int end) {
        this.start = start;
        this.end = end;
    }
    public Integer value() { return start; }
    public Source<Integer> next() {
        if (start >= end) return null;
        return new Range(start + 1, end);
    }
}

// This takes each InType of a sequence and turns it into an OutType.
// This *takes* a Transform, rather than just *implementing* Transform,
// because the transforms applied are likely to be specified inline.
// If we just let people override `value()`, we wouldn't easily know what type
// to return, and returning our own type would lose the transform method.
static class Mapper<InType, OutType> implements Source<OutType> {
    private final Source<InType> input;
    private final Transform<InType, OutType> transform;

    public Mapper(Transform<InType, OutType> transform, Source<InType> input) {
        this.transform = transform;
        this.input = input;
    }

    public Source<OutType> next() {
         return new Mapper<InType, OutType>(transform, input.next());
    }
    public OutType value() {
         return transform.appliedTo(input.value());
    }
}

// ...

public <T> Source<T> take(int count, Source<T> input) {
    if (count <= 0 || input == null) return null;
    return new Source<T>() {
        public T value() { return input.value(); }
        public Source<T> next() { return take(count - 1, input.next()); }
    };
}
</code>```

(Keep in mind that if this were actually viable in Java, code at least somewhat like the above would already be part of the API.)

Now, with an infrastructure in place, it's rather trivial to write code that doesn't need mutable variables and is at least stable for smaller amounts of input.

```<code>public Source<Integer> squares_of(Source<Integer> input) {
     final Transform<Integer, Integer> square = new Transform<Integer, Integer>() {
         public Integer appliedTo(final Integer i) { return i * i; }
     };
     return new Mapper<>(square, input);
}

public void example() {
    final Source<Integer> integers = new Range(0, 1000000000);

    // and, as for the author's "bet you can't do this"...
    final Source<Integer> squares = take(25, squares_of(integers));

    // Just to make sure we got it right :P
    final Action<Integer> printAction = new Action<Integer>() {
        public void doWith(Integer input) { System.out.println(input); }
    };
    printAction.doWithEach(squares);
}
</code>```

This mostly works, but it's still somewhat prone to stack overflows.  Try takeing 2 billion ints and doing some action on them.  :P  It will eventually throw an exception, at least until 64+ GB of RAM becomes standard.  Problem is, the amount of a program's memory that's reserved for its stack is not that big.  It's typically between 1 and 8 MiB.  (You can ask for bigger, but it doesn't matter all that much how much you ask for -- you call take(1000000000, someInfiniteSequence), you will get an exception.)  Fortunately, with lazy evaluation, the weak spot is in an area we can better control.  We just have to be careful about how much we take().

It'll still have lots of problems scaling up, because our stack usage increases linearly.  Each call handles one element and passes the rest off to another call.  Now that i think about it, though, there is one trick we can pull which might gain us quite a bit more headroom:  turn the chain of calls into a tree of calls.  Consider something more like this:

```<code>public <T> void doSomethingWith(T input) { /* magic happens here */ }
public <T> Source<T> workWith(Source<T> input, int count) {
    if (count < 0 || input == null) return null;
    if (count == 0) return input;
    if (count == 1) {
        doSomethingWith(input.value());
        return input.next();
    }
    return (workWith(workWith(input, count/2), count - count/2);
}
</code>```

workWith basically breaks up the work into two halves, and assigns each half to another call to itself.  Since each call reduces the size of the working list by half rather than by one, this should scale logarithmically rather than linearly.

Problem is, this function wants an input -- and with a linked list, getting the length requires traversing the whole list.  That's easily solved, though; simply don't care how many entries there are.  :)  The above code would work with something like Integer.MAX_VALUE as the count, since a null stops the processing anyway.  The count is mostly there so we have a solid base case.  If you anticipate having more than Integer.MAX_VALUE entries in a list, then you can check workWith's return value -- it should be null at the end.  Otherwise, recurse.

Keep in mind, this touches as many elements as you tell it to.  It's not lazy; it does its thing immediately.  You only want to do it for actions -- that is, thingies whose sole purpose is to apply itself to every element in a list.  As i'm thinking it over right now, it seems to me that sequences would be a lot less complicated if kept linear; shouldn't be a problem, since sequences don't call themselves anyway -- they just create objects that call them again.

Body:
Short version:

In order to make single-assignment style work reliably in Java, you'd need (1) some kind of immutable-friendly infrastructure, and (2) compiler- or runtime-level support for tail-call elimination.

We can write much of the infrastructure, and we can arrange things to try to avoid filling the stack.  But as long as each call takes a stack frame, there will be a limit on how much recursion you can do.  Keep your iterables small and/or lazy, and you shouldn't have major issues.  At least most of the problems you'll run into don't require returning a million results at once.  :)

Also note, since the program has to actually effect visible changes in order to be worth running, you can't make everything immutable.  You can, however, keep the vast majority of your own stuff immutable, using a tiny subset of essential mutables (streams, for example) only at certain key points where the alternatives would be too onerous.

Long version:

Simply put, A Java program can not totally avoid variables if it wants to do anything worth doing.  You can contain them, and thus restrict mutability to a huge degree, but the very design of the language and API -- along with the need to eventually change the underlying system -- make total immutability infeasible.

Java was designed from the start as an imperative, object-oriented language.

Imperative languages nearly always depend on mutable variables of some kind.  They tend to favor iteration over recursion, for example, and nearly all iterative constructs -- even while (true) and for (;;)! -- are utterly dependent on a variable somewhere changing from iteration to iteration.

Object-oriented languages pretty much envision every program as a graph of objects sending messages to each other, and in nearly all cases, responding to those messages by mutating something.

The end result of those design decisions is that without mutable variables, Java has no way to change the state of anything -- even something as simple as printing "Hello world!" to the screen involves an output stream, which involves sticking bytes in a mutable buffer.

So, for all practical purposes, we're limited to banishing the variables from our own code.   OK, we can kinda do that.  Almost.  Basically what we'd need is to replace almost all iteration with recursion, and all mutations with recursive calls returning the changed value. like so...

class Ints {
     final int value;
     final Ints tail;

     public Ints(int value, Ints rest) {
         this.value = value;
         this.tail = rest;
     }
     public Ints next() { return this.tail; }
     public int value() { return this.value; }
}

public Ints take(int count, Ints input) {
    if (count == 0 || input == null) return null;
    return new Ints(input.value(), take(count - 1, input.next()));
}

public Ints squares_of(Ints input) {
    if (input == null) return null;
    int i = input.value();
    return new Ints(i * i, squares_of(input.next()));
}

Basically, we build a linked list, where each node is a list in itself.  Each list has a "head" (the current value) and a "tail" (the remaining sublist).  Most functional languages do something akin to this, because it's very amenable to efficient immutability.  A "next" operation just returns the tail, which is typically passed to the next level in a stack of recursive calls.

Now, this is an extremely oversimplified version of this stuff.  But it's good enough to demonstrate a serious problem with this approach in Java.  Consider this code:

public function doStuff() {
    final Ints integers = ...somehow assemble list of 20 million ints...;
    final Ints result = take(25, squares_of(integers));
    ...
}

Although we only need 25 ints for the result, squares_of doesn't know that.  It is going to return the square of every number in integers.  Recursion 20 million levels deep causes pretty big problems in Java.

See, the functional languages you'd typically do wackiness like this in, have a feature called "tail call elimination".  What that means is, when the compiler sees code's last act being to call itself (and return the result if the function's non-void), it uses the current call's stack frame instead of setting up a new one and does a "jump" instead of a "call" (so the stack space used remains constant).  In short, it goes about 90% of the way toward turning tail-recursion into iteration.  It could deal with those billion ints without overflowing the stack.  (It'd still eventually run out of memory, but assembling a list of a billion ints is going to mess you up memorywise anyway on a 32-bit system.)

Java doesn't do that, in most cases.  (It depends on the compiler and runtime, but Oracle's implementation doesn't do it.)  Each call to a recursive function eats up a stack frame's worth of memory.  Use up too much, and you get a stack overflow.  Overflowing the stack all but guarantees the death of the program.  So we have to make sure not to do that.

One semi-workaround...lazy evaluation.  We still have the stack limitations, but they can be tied to factors we have more control over.  We don't have to calculate a million ints just to return 25.  :)

So let's build us some lazy-evaluation infrastructure.  (This code was tested a while back, but i've modified it quite a bit since then; read the idea, not the syntax errors.  :))

// Represents something that can give us instances of OutType.
// We can basically treat this class like a list.
interface Source<OutType> {
     public Source<OutType> next();
     public OutType value();
}

// Represents an operation that turns an InType into an OutType.
// Note, these can be the same type.  We're just flexible like that.
interface Transform<InType, OutType> {
    public OutType appliedTo(InType input);
}

// Represents an action (as opposed to a function) that can run on
// every element of a sequence.
abstract class Action<InType> {
    abstract void doWith(final InType input);
    public void doWithEach(final Source<InType> input) {
        if (input == null) return;
        doWith(input.value());
        doWithEach(input.next());
    }
}

// A list of Integers.
class Ints implements Source<Integer> {
     final Integer value;
     final Ints tail;
     public Ints(Integer value, Ints rest) {
         this.value = value;
         this.tail = rest;
     }
     public Ints(Source<Integer> input) {
         this.value = input.value();
         this.tail = new Ints(input.next());
     }
     public Source<Integer> next() { return this.tail; }
     public Integer value() { return this.value; }
     public static Ints fromArray(Integer[] input) {
         return fromArray(input, 0, input.length);
     }
     public static Ints fromArray(Integer[] input, int start, int end) {
         if (end == start || input == null) return null;
         return new Ints(input[start], fromArray(input, start + 1, end));
     }
}

// An example of the spiff we get by splitting the "iterator" interface
// off.  These ints are effectively generated on the fly, as opposed to
// us having to build a huge list.  This saves huge amounts of memory
// and CPU time, for the rather common case where the whole sequence
// isn't needed.
class Range implements Source<Integer> {
    final int start, end;
    public Range(int start, int end) {
        this.start = start;
        this.end = end;
    }
    public Integer value() { return start; }
    public Source<Integer> next() {
        if (start >= end) return null;
        return new Range(start + 1, end);
    }
}

// This takes each InType of a sequence and turns it into an OutType.
// This *takes* a Transform, rather than just *implementing* Transform,
// because the transforms applied are likely to be specified inline.
// If we just let people override `value()`, we wouldn't easily know what type
// to return, and returning our own type would lose the transform method.
static class Mapper<InType, OutType> implements Source<OutType> {
    private final Source<InType> input;
    private final Transform<InType, OutType> transform;

    public Mapper(Transform<InType, OutType> transform, Source<InType> input) {
        this.transform = transform;
        this.input = input;
    }

    public Source<OutType> next() {
         return new Mapper<InType, OutType>(transform, input.next());
    }
    public OutType value() {
         return transform.appliedTo(input.value());
    }
}

// ...

public <T> Source<T> take(int count, Source<T> input) {
    if (count <= 0 || input == null) return null;
    return new Source<T>() {
        public T value() { return input.value(); }
        public Source<T> next() { return take(count - 1, input.next()); }
    };
}

(Keep in mind that if this were actually viable in Java, code at least somewhat like the above would already be part of the API.)

Now, with an infrastructure in place, it's rather trivial to write code that doesn't need mutable variables and is at least stable for smaller amounts of input.

public Source<Integer> squares_of(Source<Integer> input) {
     final Transform<Integer, Integer> square = new Transform<Integer, Integer>() {
         public Integer appliedTo(final Integer i) { return i * i; }
     };
     return new Mapper<>(square, input);
}

public void example() {
    final Source<Integer> integers = new Range(0, 1000000000);

    // and, as for the author's "bet you can't do this"...
    final Source<Integer> squares = take(25, squares_of(integers));

    // Just to make sure we got it right :P
    final Action<Integer> printAction = new Action<Integer>() {
        public void doWith(Integer input) { System.out.println(input); }
    };
    printAction.doWithEach(squares);
}

This mostly works, but it's still somewhat prone to stack overflows.  Try takeing 2 billion ints and doing some action on them.  :P  It will eventually throw an exception, at least until 64+ GB of RAM becomes standard.  Problem is, the amount of a program's memory that's reserved for its stack is not that big.  It's typically between 1 and 8 MiB.  (You can ask for bigger, but it doesn't matter all that much how much you ask for -- you call take(1000000000, someInfiniteSequence), you will get an exception.)  Fortunately, with lazy evaluation, the weak spot is in an area we can better control.  We just have to be careful about how much we take().

It'll still have lots of problems scaling up, because our stack usage increases linearly.  Each call handles one element and passes the rest off to another call.  Now that i think about it, though, there is one trick we can pull which might gain us quite a bit more headroom:  turn the chain of calls into a tree of calls.  Consider something more like this:

public <T> void doSomethingWith(T input) { /* magic happens here */ }
public <T> Source<T> workWith(Source<T> input, int count) {
    if (count < 0 || input == null) return null;
    if (count == 0) return input;
    if (count == 1) {
        doSomethingWith(input.value());
        return input.next();
    }
    return (workWith(workWith(input, count/2), count - count/2);
}

workWith basically breaks up the work into two halves, and assigns each half to another call to itself.  Since each call reduces the size of the working list by half rather than by one, this should scale logarithmically rather than linearly.

Problem is, this function wants an input -- and with a linked list, getting the length requires traversing the whole list.  That's easily solved, though; simply don't care how many entries there are.  :)  The above code would work with something like Integer.MAX_VALUE as the count, since a null stops the processing anyway.  The count is mostly there so we have a solid base case.  If you anticipate having more than Integer.MAX_VALUE entries in a list, then you can check workWith's return value -- it should be null at the end.  Otherwise, recurse.

Keep in mind, this touches as many elements as you tell it to.  It's not lazy; it does its thing immediately.  You only want to do it for actions -- that is, thingies whose sole purpose is to apply itself to every element in a list.  As i'm thinking it over right now, it seems to me that sequences would be a lot less complicated if kept linear; shouldn't be a problem, since sequences don't call themselves anyway -- they just create objects that call them again.


问:
Making things just work and then improve them, or attempt to make them "perfect" from the beginning?
I don't have any experience working as a programmer - I just code as a hobby so far. Some years ago, I heard a programmer say that I should focus on making my code just work despite being slow (it was for a game, so it was more noticeable if my code was slow or not) and then I would spend my time improving it to make it fast and better.

I wonder how often is that advice applied in actual working environments. Do you make something that (barely) works and then spend the rest of the time improving it, or do you make it "perfect" (or acceptable) from the very beginning without looking back?

I'm assuming that the difference between these is that one is more about writing the first solution that comes to your mind, and the other is about carefully planning and thinking what you're going to write - supposing that the latter is, well, significantly slower than the former.

答:
Perfection costs a lot more money than "works", and all that money needs to be spent before the product is shipped to a customer. Many a perfect product has never been finished - never been used by real user to solve a real problem, because the developer lost interest of ran out of money before he got there. The other extreme -"make it just work" means you risk spending all your time fixing defects on a poorly structured ball of mud. Many a customer has found the developer has lost interest and/or run out of money fixing the ball of mud.

So the reality is a balance needs to be made. It needs to be good enough to be to reliable enough to be usable, and good enough to be maintainable, without being perfect. In my 30+ years experience, "perfection" is a bigger reason for product failure than "balls or mud".

Agile, TDD are considered modern methodologies that address the problem of finding that balance, by addressing the issue at the micro level (e,g, sprints), and stopping once a quality metric determines its "good enuf" and "fit for purpose" it is often assumed that the macro is also addressed (e.g. Shipping a new airline billing system). However, at the macro level, non technical (legal, business and other considerations) often prevent such an approach working as well as some evangelists promise.

ContentLicense: CC BY-SA 3.0


问:
Automatic programming: write code that writes code
After reading the book The Pragmatic Programmer, one of the arguments I found most interesting was "write code that writes code".

I tried searching over the net for some more explanations or articles about it, and while I found some good articles on the subject, I still haven't found any specific code implementation or good examples.

I feel it's still not a so common argument, something that lacks documentation or it's not embraced by so many people, and I would like to know more about it.

What do you think about the subject? Is it something that will really increase your productivity? What are some good resources on the subject, among books, blogs, slideshows, etc?

Some code examples would be greatly appreciated to allow me to better understand its implementation.

Here's the wiki page on the subject with various relevant programming techniques, like Meta Programming, Generative Programming and Code Generation.

答:
While many answers here refer to what is commonly known as meta programming, there was in fact a field associated to AI known as automatic programming that was about programs understanding or synthesizing programs [1].

Any compiler (or meta-program, code generator, translator, macro system, ...) work with transformations, generating an output from an input by carrying out its fixed algorithm of transformation. But a traditional compiler or meta-program does not, given a definition, description or example of what sorting a list is (eg. [5, 3, 9] => [3,5,9]), create a sorting algorithm. Such problems where of the interest of this "automatic programming" field.

[1] - Progress report on program-understanding systems
ftp://db.stanford.edu/pub/cstr/reports/cs/.../CS-TR-74-444.pdfShare


问:
Making the switch from MySQL to PostgreSQL?
I've spent the last year becoming really comfortable with MySQL, but due to its increasing trendiness and my desire to homogenize my web-apps with Heroku, I'd like to start using PostgreSQL for my web apps instead.  There are a resources out there for learning PostgreSQL, but I don't really want to have database concepts explained to me from scratch again, and I don't want to have to re-learn all the stuff that's pretty much the same.

What are the critical differences that I need to understand - syntactical and conceptual - between MySQL and PostgreSQL that will affect me on a day-to-day basis?

答:
What are the critical differences that I need to understand - syntactical and conceptual - between MySQL and PostgreSQL that will affect me on a day-to-day basis?

The biggest one is what the database is there for.  MySQL is built, essentially, to be an information store for your application.  PostgreSQL is there to be an information management solution for several applications hitting the same data.  This difference comes up in many different ways.  For example, MySQL lets applications set their own sql_mode which affects what data will be seen as valid.  PostgreSQL has no such option.  Consequently in MySQL, one is heavily encouraged to think of SQL as being an application-private API, while in PostgreSQL is is an API that can be safely shared between applications.  This leads to a lot of little differences.  MySQL is probably easier to port an application to, but PostgreSQL is probably easier to port a data environment to....

You may find the following to be of help: http://ledgersmbdev.blogspot.com/2012/09/or-modelling-interlude-postgresql-vs.html


问:
Established coding standards for pl/pgsql code
I need to standardize coding practices for project that compromises, among others, of pl/pgsql database, that has some amount of nontrivial code.

I look for:

Code formatting guidelines, especially inside procedures.

Guidelines on what constructs are considered unsafe (if any)

Naming conventions.

Code documentation conventions (if this is practiced)

Any hints to documents that define good practices in pl/pgsql code? If not I'm looking for
hints to practices that you consider good.

There is related question regarding TSQL: Can anyone recommend coding standards for TSQL?, which is relevant to psql as well, but I need more information on stored procedures.

Other related questions:

https://stackoverflow.com/questions/1070275/what-indenting-style-do-you-use-in-sql-server-stored-procedures

答:
A few points from our experience both in terms of maintainability and security.  A lot of things like code formatting are things that can be done any number of ways as long as you are consistent and you use white space appropriately.

As for what is unsafe from a security perspective the only thing that comes to mind is combining SECURITY DEFINER, EXECUTE, and string interpolation.  This leads to the possibility of SQL injection that will run as the owner of the function.  This is sometimes necessary (so use quote_ident and quote_literal as appropriate) but when it is, code needs to be additionally reviewed for weaknesses.  This comes up when executing DDL inside stored procs, particularly for user management.

One caution however is the possibility of search path playing issues with SECURITY DEFINER functions.  You may want to look at this particularly in cases where users are going to have the ability to create relations in other schemas (or even temporary relations).  See http://www.postgresql.org/docs/9.2/static/sql-createfunction.html#SQL-CREATEFUNCTION-SECURITY

A second thing I prefer to do is to add COMMENT ON FUNCTION .... after each function definition.  I think this is preferable to explanatory API comments at the top because it can be pulled up by automatic documentation tools.

A third thing I highly recommend is to try to keep PLPGSQL functions to be in the form of a main db query with small amounts of supporting procedural logic.  This helps with both clarity and debugging.  The more you can consolidate into a single query the faster the procedure as a whole can be debugged, because there are fewer possible places for any given error to lurk.

Finally one big trap that occurs with user defined functions being called by the application is that the functions often require fixed numbers of arguments, and this can be an issue in terms of maintainability. I would recommend reading this  http://ledgersmbdev.blogspot.com/2011/10/introduction-to-soda.html which is an attempt to apply what can be learned from web services to PostgreSQL stored procedures.

My blog, http://ledgersmbdev.blogspot.com, regularly features thoughts and experience on this issue so it may be helpful :-)


问:
Should you version web applications?
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers

答:
If your web application consists of multiple modules, both in client and server, each module should be versioned. And each combination of module versions on both client and server should be given an unique id, an id that should be present in all logging and error messages.

By using that convention, it will always be possible to recreate the state the web app was in at a given moment.

In my opinion, since webapps these days are built using dynamic languages on both sides, server and client, there shouldn't be any reason for reloading an updated web app unless the user restarts the browser or manually reloads the page.

Only the updated parts or modules in the web app should be reloaded without affecting the overall state of the application.

Why you might ask? Well, by enforcing that, the web app will by its design be more roboust, correct and probably easier to maintain. If the web app always require simultaneous server/client update then it probably is not build the right way.

ContentLicense: CC BY-SA 2.5

Title: Should you version web applications?


问:
Controller layer and 3-tier architecture
What is controller layer and where we put this in our 3-tier architecture?

```<code>1)UI
2)Business Logic Layer
3)Data Access Layer
</code>```

I search in net but unable to get exact ans.Any links or sample example helps to understand better.Thanks.

答:
The controller layer is at the UI. It is basically "controlling" what action should take place in your application. Since you tagged this with asp.net, you should consider looking at Microsoft's version of this structure (called MVC for Model, View, Controller) - ASP.NET MVC

Edit: Seeing your comment, I've never attempted to shoe-horn MVC into the old WebForms way of life, but it looks like others have - codeproject


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答: Code Complete . It covers most of the basic subjects you need to know as a programmer, and gives you directions to learn more about each of them. A very good first step in a learning path. Myself and lots of people I know, wish they read it earlier in their programmer life.</p>


问:
Better way of storing key-value pairs in the database?
I have a C#/SQL Server program that sometimes needs to store data. The data could be a response from a web service, a result of a database query, or any number of other things. There's no way of knowing before the data is stored how many fields it might have or what the data structure might be. We have this kind of painful table we're using for this... four columns and lots of rows. An example of the data might be easier than an explanation.

```<code>InstanceID RowID PropertyName PropertyValue
1          1     Property1    Value1
1          1     Property2    Value2
1          1     Property3    Value3
1          2     Property1    Value1
1          2     Property2    Value2
1          2     Property3    Value3
2          1     OtherProp1   Value1
2          1     OtherProp2   Value2
2          2     OtherProp1   Value1
2          2     OtherProp2   Value2
</code>```

These values will then be pulled back and fed into a dictionary object, which can be updated, then the fields will be fed back into the database. This can be painful to code against, and also requires a lot of inserts which can make it very slow.

I can't think of a better way of doing this, but I feel like there must be one. Any advice?

答:
I am going to second the xml solution.  I would also say that in LedgerSMB we are looking at doing JSON which is now natively supported under PostgreSQL for extended key/value pairs.  I would also point out that currently this can be done in SQL Server by creating some TSQL processing functions.  See http://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/

However, given the complexity using non-native JSON components, I would say use XML which is the next best thing.


问:
Legitimate reasons for circular references in C++
I have project written in C++ that I am working on which has a parent-child relationship where each child has only one parent. I had previously decided after looking at this post that I would make the children know nothing of their parents.

A little background on my project before I go into my question: The parents in this situation are objects representing a collection of interlinked computational "blocks". The parent (The "Model" class) takes in one or more input values, runs them through its blocks, and the blocks return back one or more output values. The child objects are the Blocks and a Block is owned by exactly one Model. The issue is that a certain kind of Block can contain a Model so that I can nest them and re-use models. Although most blocks know nothing of the Model class, the ModelBlock (inheriting Block) knows about Models and is allowed to encapsulate a Model.

The Question: The above seemed to be working pretty well, at least in the console version of my application. However, I need a GUI to be able to create any large Model without losing my mind and so I have started making one. The issue has reared its ugly head again when I realized that the Blocks in general need to know about their Model so that ModelBlocks can inform a Model when it is being used inside of another Model. This is so that I can easily find "orphaned" Models that are not the root model and not used in any other context (meaning they will never be run). I guess I could make it specific to ModelBlocks, but if I'm going to do something like that, why not make it apply to all the blocks?

In C#, its seemingly not a bad practice to use a circular reference to accomplish this (Entity Framework does it up the wazoo...it wreaks havoc with serializers). However, it seems very taboo in C++ to use circular references. So, I am wondering if the above is a legitimate use. Were I to do this, Blocks would be informed of their parent Model's destruction so that they know if they are orphans. Even if the above isn't, are the legitimate uses for circular references in C++ since they seem to be relatively common other languages (of course, that's assuming that those programs in those other languages using circular references don't have serious design issues)?

If I didn't explain my question well enough just let me know and I'll try to clarify.

EDIT: I should mention that the actual implementations are separate from all this since I am using interfaces (classes with all pure virtual functions) to define how a block looks or how a model looks.

Here is a partial class diagram with my proposed changes:

Here is the source: https://github.com/kcuzner/Simulate/tree/develop.
If you feel like building it, it depends on Qt >= 4.7, boost >= 1.52. The projects are Qt-Creator projects. Console and GUI depend on Engine.

答: There's nothing wrong with using a non-owning pointer to someone who points back to you. Just make sure it's not owning.

ContentLicense: CC BY-SA 4.0


答: You might want to use shared_ptr for owning links and weak_ptr for non owning links (child to parent). That way you can destroy the parent, and the child can check if parent exists.

Title: Legitimate reasons for circular references in C++

Body:
I have project written in C++ that I am working on which has a parent-child relationship where each child has only one parent. I had previously decided after looking at this post that I would make the children know nothing of their parents.

A little background on my project before I go into my question: The parents in this situation are objects representing a collection of interlinked computational "blocks". The parent (The "Model" class) takes in one or more input values, runs them through its blocks, and the blocks return back one or more output values. The child objects are the Blocks and a Block is owned by exactly one Model. The issue is that a certain kind of Block can contain a Model so that I can nest them and re-use models. Although most blocks know nothing of the Model class, the ModelBlock (inheriting Block) knows about Models and is allowed to encapsulate a Model.

The Question: The above seemed to be working pretty well, at least in the console version of my application. However, I need a GUI to be able to create any large Model without losing my mind and so I have started making one. The issue has reared its ugly head again when I realized that the Blocks in general need to know about their Model so that ModelBlocks can inform a Model when it is being used inside of another Model. This is so that I can easily find "orphaned" Models that are not the root model and not used in any other context (meaning they will never be run). I guess I could make it specific to ModelBlocks, but if I'm going to do something like that, why not make it apply to all the blocks?

In C#, its seemingly not a bad practice to use a circular reference to accomplish this (Entity Framework does it up the wazoo...it wreaks havoc with serializers). However, it seems very taboo in C++ to use circular references. So, I am wondering if the above is a legitimate use. Were I to do this, Blocks would be informed of their parent Model's destruction so that they know if they are orphans. Even if the above isn't, are the legitimate uses for circular references in C++ since they seem to be relatively common other languages (of course, that's assuming that those programs in those other languages using circular references don't have serious design issues)?

If I didn't explain my question well enough just let me know and I'll try to clarify.

EDIT: I should mention that the actual implementations are separate from all this since I am using interfaces (classes with all pure virtual functions) to define how a block looks or how a model looks.

Here is a partial class diagram with my proposed changes:

Here is the source: https://github.com/kcuzner/Simulate/tree/develop.
If you feel like building it, it depends on Qt >= 4.7, boost >= 1.52. The projects are Qt-Creator projects. Console and GUI depend on Engine.


问:
How do I learn algorithms and data structures?
This is in continuation to my previous question where I asked is it necessary to learn algorithms and data structures. I feel yes it is.

Now I work in an environment where I won't ever get the chance to learn it by experimenting or practically or in any assignment. What is the right approach like the right books, right kind of problems, right kind of resources that I can go through to give six months or a year or two to learn algorithms and data structures?  And also mold my mind in a way that it can relate problems to data structures and algorithms.

答:
Start working on solving classical problems on for example sphere online, the site might not look that fancy but boy, these are classical programming problems that require many of the important data structures and algorithms in use today.

Solutions can be submitted in a variety of programming languages from C/C++ to JavaScript, Lisp, Smalltalk, assembler + some 40 more. So you can focus entirely on solving the problem with whatever programming language you feel comfortable with.


问:
'import module' vs. 'from module import function'
I have always been using this method:

```<code>from sys import argv
</code>```

and use argv with just argv. But there is a convention of using this:

```<code>import sys
</code>```

and using the argv by sys.argv

The second method makes the code self documented and I (really) adhere to it. But the reason I prefer first method is it is fast because we are importing only the function that is needed rather than import the whole module (which contains more useless functions which python will waste time importing them). Note that I need just argv and all other functions from sys are useless to me.

So my questions are. Does the first method really makes the script fast? Which method is preferred most? Why?

答:
There are two reasons in favor of using import module rather than from module import function.

First is the namespace. Importing a function into the global namespace risks name collisions.

Second isn't that relevant to standard modules, but significant for you own modules,  especially during development. It's the option to reload() a module. Consider this:

```<code>from module import func
...
reload(module)
# func still points to the old code
</code>```

On the other hand

```<code>import module
...
reload(module)
# module.func points to the new code
</code>```

As for speed...

we are importing only the function that is needed rather than import
  the whole module (which contains more useless functions which python
  will waste time importing them)

Whether you import a module or import a function from a module, Python will parse the whole module. Either way the module is imported. "Importing a function" is nothing more than binding the function to a name. In fact import module is less work for interpreter than from module import func.

Body:
There are two reasons in favor of using import module rather than from module import function.

First is the namespace. Importing a function into the global namespace risks name collisions.

Second isn't that relevant to standard modules, but significant for you own modules,  especially during development. It's the option to reload() a module. Consider this:

from module import func
...
reload(module)
# func still points to the old code

On the other hand

import module
...
reload(module)
# module.func points to the new code

As for speed...

we are importing only the function that is needed rather than import
  the whole module (which contains more useless functions which python
  will waste time importing them)

Whether you import a module or import a function from a module, Python will parse the whole module. Either way the module is imported. "Importing a function" is nothing more than binding the function to a name. In fact import module is less work for interpreter than from module import func.


问:
Marked nodes in Fibonacci heaps
I don't understand why Fibonacci heaps have marked nodes (picture).
A node is marked when its child is deleted. Quoting from Wikipedia: "[Keeping degree of each node low] is achieved by the rule that we can cut at most one child of each non-root node. When a second child is cut, the node itself needs to be cut from its parent and becomes the root of a new tree."

Why do we need to do that? Why not just leave the node where it is after the second child is cut? The heap structure is not violated. I don't see the point of this optimization.

答:
The reason is not that it would violate the heap invariant, but that it would lead to a state in which the heap would be inefficient.

The heap is efficient because after compaction there is only log(N) trees. To guarantee that you need to know that a tree with root degree k contains at least O(2k) nodes. But if you can cut nodes freely, you could cut all the second-level children and the tree would remain of degree k, but could get down to k+1 nodes.

This is prevented by tearing the tree apart and compacting it's parts again in next compaction step.

Title: Marked nodes in Fibonacci heaps


问:
The array class in C# - Implementation questions
I am studying the Array class in C#. The following is the implementation of System.Array class:

```<code>[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
</code>```

I have two questions regarding this:

I have read that System.Array class is derived from System.Object. But why is this not seen in the above definition?

ICloneable is implemented in order to allow the Array to be Deep-Copied in case of XML serialization. ICloneable provides only one method - Clone(). What is the advantage of implementing ICloneable explicitly? Why could not Clone() method be directly implemented? Is this a type of providing a Marking Interface pattern where a particular Interface is implemented only to convey a certain characteristic of the class?

答:
System.Array is effectively derived from System.Object. You don't see it here, because everything in .NET Framework derives by default from System.Object, including types like int (System.Int32).

In other words:

class MyClass : MyOtherClass { } indicates that MyClass is derived from MyOtherClass.

class MyClass { } indicates that MyClass is derived from System.Object.

The advantage of using an interface is that methods (or classes with generics) may rely on interfaces when they need a specific method or property. Imagine the following source code:

```<code>public interface INamed
{
    string Name { get; }
}

public void SayHello(INamed namedEntity)
{
    Console.WriteLine("Hello, " + namedEntity.Name + "!");
}
</code>```

By using an interface, the method shows that it doesn't care about the exact type of namedEntity. All what it cares about is that the object should contain a property of type string called Name which has a getter.

The actual type may be a Person. Or a Cat : Animal. Or an AircraftModel. SayHello accepts them all, at the condition for them to implement INamed.

Why would Person implement an interface, instead of simply containing the Name property?

Because, aside using Reflection or dynamic programming, the caller doesn't have a clue that Person effectively implements Name property. For example this code will not compile:

```<code>public class Person
{
    public string Name { get; set; }
}

public void SayHello(object namedEntity)
{
    Console.WriteLine("Hello, " + namedEntity.Name + "!"); // Compile-time error here
}

public void Main()
{
    this.SayHello(new Person { Name = "Robert" });
}
</code>```

Body:
System.Array is effectively derived from System.Object. You don't see it here, because everything in .NET Framework derives by default from System.Object, including types like int (System.Int32).

In other words:

class MyClass : MyOtherClass { } indicates that MyClass is derived from MyOtherClass.

class MyClass { } indicates that MyClass is derived from System.Object.

The advantage of using an interface is that methods (or classes with generics) may rely on interfaces when they need a specific method or property. Imagine the following source code:

public interface INamed
{
    string Name { get; }
}

public void SayHello(INamed namedEntity)
{
    Console.WriteLine("Hello, " + namedEntity.Name + "!");
}

By using an interface, the method shows that it doesn't care about the exact type of namedEntity. All what it cares about is that the object should contain a property of type string called Name which has a getter.

The actual type may be a Person. Or a Cat : Animal. Or an AircraftModel. SayHello accepts them all, at the condition for them to implement INamed.

Why would Person implement an interface, instead of simply containing the Name property?

Because, aside using Reflection or dynamic programming, the caller doesn't have a clue that Person effectively implements Name property. For example this code will not compile:

public class Person
{
    public string Name { get; set; }
}

public void SayHello(object namedEntity)
{
    Console.WriteLine("Hello, " + namedEntity.Name + "!"); // Compile-time error here
}

public void Main()
{
    this.SayHello(new Person { Name = "Robert" });
}


答:
You're presently taking the traditional approach for this need within a relational database.

One alteration to consider is strongly-typed columns for the values - as in Option 4 from this post: https://stackoverflow.com/questions/1126783.

Title: Better way of storing key-value pairs in the database?

Body:
I have a C#/SQL Server program that sometimes needs to store data. The data could be a response from a web service, a result of a database query, or any number of other things. There's no way of knowing before the data is stored how many fields it might have or what the data structure might be. We have this kind of painful table we're using for this... four columns and lots of rows. An example of the data might be easier than an explanation.

```<code>InstanceID RowID PropertyName PropertyValue
1          1     Property1    Value1
1          1     Property2    Value2
1          1     Property3    Value3
1          2     Property1    Value1
1          2     Property2    Value2
1          2     Property3    Value3
2          1     OtherProp1   Value1
2          1     OtherProp2   Value2
2          2     OtherProp1   Value1
2          2     OtherProp2   Value2
</code>```

These values will then be pulled back and fed into a dictionary object, which can be updated, then the fields will be fed back into the database. This can be painful to code against, and also requires a lot of inserts which can make it very slow.

I can't think of a better way of doing this, but I feel like there must be one. Any advice?


问:
Nested Enum type in C++ or C#?
I've come across a recurring issue in a few of my recent projects in which I find myself using enums to represent state, or type, or something else, and I need to check against a few conditions. Some of these conditions span multiple enums, so I end up with a load of logic in switch and if blocks, which I don't like. This is a particular problem when having to cast things to and from the enum, like when the enum is being used to check an int that you're getting from a web request or a calculation.

Is there something in C++ or C# that can be used as a nested enum? Something like this:

```<code>enum Animal
{
    Mammal
    {
        Cat,
        Dog,
        Bear
    },
    Bird
    {
        Pigeon,
        Hawk,
        Ostrich
    },
    Fish
    {
        Goldfish,
        Trout,
        Shark
    },
    Platypus    //srsly what is that thing
};
</code>```

Obviously, it may or may not be declared like that, but you get the idea. The point is that in code you could use it like Animal thisAnimal = Animal.Mammal.Cat and then later check if (thisAnimal.IsMember(Animal.Mammal)) or something like that.

I've seen Java's EnumSet, and found them pretty useful, but I don't think they're an exact match for the functionality I'm after. For this example, you'd have to declare an enum with all the animals at one level, and then add them all to the relevant sets. That would mean that when using the original enum, higher-level things like Mammal or Invertebrate would appear on the same "level" as something very specific like African Swallow, which would imply that they were (to some degree) interchangeable, which isn't true. In theory, a nested structure as above might allow you to specify the level of "specificness" needed, so you could get this:

```<code>enum Animal::Kingdom.Order.Family.Genus.Species
{ /*stuff*/ }

Organism::Kingdom.Phylum.Class.Order.Family thisThing;

thisThing = Animalia.Cordata;                               //compiler error
thisThing = Animalia.Chordata.Aves.Passeri.Hirundinidae;    //compiles OK
</code>```

Does a structure like this exist anywhere? If not, how might I build one for C++ and/or C# and have it remain as generic and re-usable as possible?

答:
I agree with others that this seems overengineered. Usually, you want either a simple enum or a complex hierarchy of classes, it's not a good idea to combine the two.

But if you really want to do this (in C#), I think it's useful to recap what exactly do you want:

Separate types for the hierarchy Kingdom, Phylum, etc., which do not form inheritance hierarchy (otherwise, Phylum could be assigned to Kingdom). Though they could inherit from a common base class.

Each expression like Animalia.Chordata.Aves has to be assignable to a variable, which means we have to work with instances, not nested static types. This is especially problematic for the root type, because there are no global variables in C#. You could solve that by using a singleton. Also, I think there should be only one root, so the code above would become something like Organisms.Instance.Animalia.Chordata.Aves.

Each member has to be a different type, so that Animalia.Chordata compiled, but Plantae.Chordata didn't.

Each member needs to somehow know all its children, for the IsMember() method to work.

The way I would implement these requirements is to start with a class like EnumSet<TChild> (though the name could be better), where TChild is the type of the children of this level in hierarchy. This class would also contain a collection of all its children (see later about filling it). We also need another type to represent leaf level of the hierarchy: non-generic EnumSet:

```<code>abstract class EnumSet
{}

abstract class EnumSet<TChild> : EnumSet where TChild : EnumSet
{
    protected IEnumerable<TChild> Children { get; private set; }

    public bool Contains(TChild child)
    {
        return Children.Contains(child);
    }
}
</code>```

Now we need to create a class for each level in the hierarchy:

```<code>abstract class Root : EnumSet<Kingdom>
{}

abstract class Kingdom : EnumSet<Phylum>
{}

abstract class Phylum : EnumSet
{}
</code>```

And finally some concrete classes:

```<code>class Organisms : Root
{
    public static readonly Organisms Instance = new Organisms();

    private Organisms()
    {}

    public readonly Animalia Animalia = new Animalia();
    public readonly Plantae Plantae = new Plantae();
}

class Plantae : Kingdom
{
    public readonly Anthophyta Anthophyta = new Anthophyta();
}

class Anthophyta : Phylum
{}

class Animalia : Kingdom
{
    public readonly Chordata Chordata = new Chordata();
}

class Chordata : Phylum
{}
</code>```

Notice that children are always fields of the parent class. What this means is that to fill the Children collection, we can use reflection:

```<code>public EnumSet()
{
    Children = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)
                        .Select(f => f.GetValue(this))
                        .Cast<TChild>()
                        .ToArray();
}
</code>```

One problem with this approach is that Contains() always works only one level down. So, you can do Organisms.Instance.Contains(animalia), but not .Contains(chordata). You can do that by adding overloads of Contains() to the specific hierarchy classes, e.g.:

```<code>abstract class Root : EnumSet<Kingdom>
{
    public bool Contains(Phylum phylum)
    {
        return Children.Any(c => c.Contains(phylum));
    }
}
</code>```

But this would be a lot of work for deep hierarchies.

After all of this, you end up with quite a lot of repetitive code. One way to fix that would be to have a text file that describes the hierarchy and use a T4 template to generate all the classes based on that.

Title: Nested Enum type in C++ or C#?

Body:
I agree with others that this seems overengineered. Usually, you want either a simple enum or a complex hierarchy of classes, it's not a good idea to combine the two.

But if you really want to do this (in C#), I think it's useful to recap what exactly do you want:

Separate types for the hierarchy Kingdom, Phylum, etc., which do not form inheritance hierarchy (otherwise, Phylum could be assigned to Kingdom). Though they could inherit from a common base class.

Each expression like Animalia.Chordata.Aves has to be assignable to a variable, which means we have to work with instances, not nested static types. This is especially problematic for the root type, because there are no global variables in C#. You could solve that by using a singleton. Also, I think there should be only one root, so the code above would become something like Organisms.Instance.Animalia.Chordata.Aves.

Each member has to be a different type, so that Animalia.Chordata compiled, but Plantae.Chordata didn't.

Each member needs to somehow know all its children, for the IsMember() method to work.

The way I would implement these requirements is to start with a class like EnumSet<TChild> (though the name could be better), where TChild is the type of the children of this level in hierarchy. This class would also contain a collection of all its children (see later about filling it). We also need another type to represent leaf level of the hierarchy: non-generic EnumSet:

abstract class EnumSet
{}

abstract class EnumSet<TChild> : EnumSet where TChild : EnumSet
{
    protected IEnumerable<TChild> Children { get; private set; }

    public bool Contains(TChild child)
    {
        return Children.Contains(child);
    }
}

Now we need to create a class for each level in the hierarchy:

abstract class Root : EnumSet<Kingdom>
{}

abstract class Kingdom : EnumSet<Phylum>
{}

abstract class Phylum : EnumSet
{}

And finally some concrete classes:

class Organisms : Root
{
    public static readonly Organisms Instance = new Organisms();

    private Organisms()
    {}

    public readonly Animalia Animalia = new Animalia();
    public readonly Plantae Plantae = new Plantae();
}

class Plantae : Kingdom
{
    public readonly Anthophyta Anthophyta = new Anthophyta();
}

class Anthophyta : Phylum
{}

class Animalia : Kingdom
{
    public readonly Chordata Chordata = new Chordata();
}

class Chordata : Phylum
{}

Notice that children are always fields of the parent class. What this means is that to fill the Children collection, we can use reflection:

public EnumSet()
{
    Children = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)
                        .Select(f => f.GetValue(this))
                        .Cast<TChild>()
                        .ToArray();
}

One problem with this approach is that Contains() always works only one level down. So, you can do Organisms.Instance.Contains(animalia), but not .Contains(chordata). You can do that by adding overloads of Contains() to the specific hierarchy classes, e.g.:

abstract class Root : EnumSet<Kingdom>
{
    public bool Contains(Phylum phylum)
    {
        return Children.Any(c => c.Contains(phylum));
    }
}

But this would be a lot of work for deep hierarchies.

After all of this, you end up with quite a lot of repetitive code. One way to fix that would be to have a text file that describes the hierarchy and use a T4 template to generate all the classes based on that.


答:
SQL has not been designed for this scenario, but document and key-value stores have been. Have you considered using one of those?

For example MongoDB has a C# driver with Linq support (although I doubt you will actually need that). You can simply store all the "dynamic data" in one mongodb document per SQL entity.

Another alternative would be redis, simply mapping unique entity identifiers to hashes that contain the corresponding key-value-data.


问:
Is is acceptable to create mediocre code now in preparation for new language features?
I'll be specific: Java 8 is promised to bring lambda expressions as well as method and constructor references among other things. As a Java developer I'm super psyched about that.

In my day to day programming I see more and more opportunities where using these features would greatly simplify code that would otherwise be very verbose and tedious. In lieu of method and constructor references I started using more and more reflection and plan to migrate those code paths to Java 8 as soon as possible. I use special comments (like the well known TODO comments: JAVA8) that can be used by the IDE or grepped easily in order to find the relevant places. I also test all those cases extensively to make sure they work.

But still I have to wonder whether it's good to do it like that. Is it acceptable to produce a little more brittle code now that will eventually become robust again? GA for Java 8 is September 2013 so it's not too far in the future (provided the release date doesn't slip).

A kinda general example would be something like this: I want to create some container objects and fill them with data from a database. If I were to use the standard Java approach, it could look like this:

```
class ContainerService {
  private Database database;
  private final Map, ContainerInitializer> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, new FooInitializer());
  }

  public Container getContainer(Class cls) {
    return INITIALIZERS.get(cls).create();
  }

  interface ContainerInitializer {
    Container create();
  }

  class FooInitializer implements ContainerInitializer {
    Container create() {
      return new Container(database.getFoo());
    }
  }
}
```

The reflective code is

```
class ContainerService {
  private Database database;
  private final Map, String> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, "getFoo");
  }

  public Container getContainer(Class cls) {
    Method m = Database.class.getMethod(INITIALIZERS.get(cls));
    return new Container(m.invoke(database));
  }
}
```

Note how all the intermediate interfaces and classes fall away.

The Java 8 variant is something along the following lines:

```
class ContainerService {
  private Database database;
  private final Map, ContainerInitializer> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, database::getFoo);
  }

  public Container getContainer(Class cls) {
    return new Container(INITIALIZER.get(cls).create());
  }

  private interface ContainerInitializer {
    Container create();
  }
}
```

This is slightly longer again but has type safety. Also it's trivial to get from the prepared code to the final code using method references.

Of course the example is a bit simple. Imagine having a lot of types the container could contain. In the first method, there would be an extra class for each of them. In the other two methods, only data has to be added. It keeps everything so much simpler.

答:
Don't fall for the chant of sirens.

Their song talks about new features and performance improvements, but all you get by listening to that, is a neverending stream of pain, delays, procrastination, and deployment woes.

Write for what exists. The rest is mere speculation.


答:
I think the answer to this question most likely depends upon the situation in particular which you're dealing with. In terms of "day to day programming," does this consist of your job? Hobbyist/personal work, perhaps? If it's the latter, I don't necessarily think it to be a poor idea to look ahead in regards to refactoring and improving your code base, if you have the time -- attempting to improve upon your own work is never a bad thing. On the other hand, if it's a work scenario, even if you're a project manager you'd still have to run such thoughts by your peers to get their input. However, because these features don't exist yet, unless you have nothing else on your plate, it could be a very large waste of time and resources because none of the features really exist.

It's certainly something to think about, and there are a few ways in which you could handle it. You mention being able to make use of TODO comments where Java 8's features could be applied. You could also consider branching/forking a project entirely and writing makeshift pseudocode (assuming that the lambda syntax in Java 8 isn't finalized yet) in places where you might want to improve it in the future. Again, though, it brings up the aforementioned concerns of time and effort.

Title: Is is acceptable to create mediocre code now in preparation for new language features?

Body:
I'll be specific: Java 8 is promised to bring lambda expressions as well as method and constructor references among other things. As a Java developer I'm super psyched about that.

In my day to day programming I see more and more opportunities where using these features would greatly simplify code that would otherwise be very verbose and tedious. In lieu of method and constructor references I started using more and more reflection and plan to migrate those code paths to Java 8 as soon as possible. I use special comments (like the well known TODO comments: JAVA8) that can be used by the IDE or grepped easily in order to find the relevant places. I also test all those cases extensively to make sure they work.

But still I have to wonder whether it's good to do it like that. Is it acceptable to produce a little more brittle code now that will eventually become robust again? GA for Java 8 is September 2013 so it's not too far in the future (provided the release date doesn't slip).

A kinda general example would be something like this: I want to create some container objects and fill them with data from a database. If I were to use the standard Java approach, it could look like this:

```
class ContainerService {
  private Database database;
  private final Map, ContainerInitializer> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, new FooInitializer());
  }

  public Container getContainer(Class cls) {
    return INITIALIZERS.get(cls).create();
  }

  interface ContainerInitializer {
    Container create();
  }

  class FooInitializer implements ContainerInitializer {
    Container create() {
      return new Container(database.getFoo());
    }
  }
}
```

The reflective code is

```
class ContainerService {
  private Database database;
  private final Map, String> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, "getFoo");
  }

  public Container getContainer(Class cls) {
    Method m = Database.class.getMethod(INITIALIZERS.get(cls));
    return new Container(m.invoke(database));
  }
}
```

Note how all the intermediate interfaces and classes fall away.

The Java 8 variant is something along the following lines:

```
class ContainerService {
  private Database database;
  private final Map, ContainerInitializer> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, database::getFoo);
  }

  public Container getContainer(Class cls) {
    return new Container(INITIALIZER.get(cls).create());
  }

  private interface ContainerInitializer {
    Container create();
  }
}
```

This is slightly longer again but has type safety. Also it's trivial to get from the prepared code to the final code using method references.

Of course the example is a bit simple. Imagine having a lot of types the container could contain. In the first method, there would be an extra class for each of them. In the other two methods, only data has to be added. It keeps everything so much simpler.


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答: An assignment for building a silly widget on their mobile phones. Something that they could show their friends. I have a uber-cheap AT&T phone and it takes jar files of some sort .</p>


答:
You can use void * (or IUnknown *) to achieve loose coupling and reduce code complexity. It eliminates circular referencing in C++ header files.

```<code>// Model.h
class CModel
{
public:
    void addBlock(char *str, void** ppBlock);
};

// Block.h
class CBlock
{
public:
    void getParent(void** ppModel);
};
</code>```

Then with appropriate casting, you can get what you need, for example:

```<code>#include "Model.h"
#include "Block.h"

// ...

CModel model;
CBlock *pBlock = NULL;
model.addBlock("something", (void**) &pBlock);

CModel *pParent = NULL;
pBlock->getParent((void**) &pParent);
</code>```

If you add a reference counting system and smart pointers, then, you will have an ecosystem similar to ATL/COM.

Body:
You can use void * (or IUnknown *) to achieve loose coupling and reduce code complexity. It eliminates circular referencing in C++ header files.

// Model.h
class CModel
{
public:
    void addBlock(char *str, void** ppBlock);
};

// Block.h
class CBlock
{
public:
    void getParent(void** ppModel);
};

Then with appropriate casting, you can get what you need, for example:

#include "Model.h"
#include "Block.h"

// ...

CModel model;
CBlock *pBlock = NULL;
model.addBlock("something", (void**) &pBlock);

CModel *pParent = NULL;
pBlock->getParent((void**) &pParent);

If you add a reference counting system and smart pointers, then, you will have an ecosystem similar to ATL/COM.


答:
I agree with @ZJR's answer, but if you want to go ahead you can probably encapsulate this into a MethodReference class of some sort. With luck you might be able to gain type safety by juggling just one place when Java 8 comes along.

Boost basically does this before C++11. Certain features closely resembles the proposed syntax for C++11 to ease transition.


问:
Database data structures for RESTful api
I am creating a RESTful API. I am struggling to decide on the best way to design my database tables around my resources.

Initially, I though a table per resource would be a good way to go, but I'm now worried that this will result in exponentially bigger tables the further down the resource chain you go.

For example, imagine I have three resources - users, clients, sales. Users are subscribers to my api, clients are the users customers, and sales are purchases made by each client to the  users account.

A sale resource is accessed as follows

```<code>GET /users/{userID}/clients/{clientID}/sales/{salesID}
</code>```

So if there are 10 users, each with 10 customers, and for each customer there are 10 sales, the table size gets larger the further down the resource chain we go.

Im fairly confident that SQL can cope with large tables, but I'm not sure how read and writes will slow things down. The example above maybe doesn't illustrate it, but my api will have progressively more writes and reads the further down the resource chain we go. I therefore have the scenario where the biggest tables in my database, will be read and written to more times than smaller tables.

It will also be necessary to join tables before running queries. The reason is that I allow each user to have a client with the same name. To avoid getting the wrong client data, the users table and clients tables are joined by {userID}. This is also the case for sales. Will joining large tables and running reads and writes slow things down further?

答:
I don't see exactly where this would be different without REST. This is a rather normal task for a database and queries of this kind are done all the time. Main thing to do is having indices on the id fields of course.

Once this runs for some time you will have many sales and need to query for sales not only by user/client, but limit to a certain date range (like last month). Again that should be no problem, assuming you have indices on those fields.

One weak point in your design (though may depend on your use case) is a single client could work only with one specific user. I would think that some of those users are in a holiday once in a while and clients may purchase from different users for this (or other) reasons. So maybe the sales table should have userID and clientID.


问:
Is Object Oriented Programming a solution to complexity?
Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>

答:
Complex problems cannot be rendered simpler through technology, they can only be managed through technology.

OOP is a technology, a concept, and a way to approach a problem.

OOP gives you the tools to enforce a design that can make it easier to manage complexity, but you can just as easily have a bad design that increases your complexity.  In other words, if not used properly, you can have technology-induced complexity in your problems.

Keep in mind that there are many other aspects that will dictate how successful your project will be (i.e. project management style, problem definition, change management, etc...).  The technology you use is only relevant in how much will it help you manage the problem.

In the end, object oriented programming cannot be a solution to complexity; it's just a tool to manage it. (if used properly)


问:
What is the principle of least astonishment?
In programming what is called Principle of Least Astonishment? How is this concept related to designing good APIs?  Is this something applicable to only object oriented programming or does it permeate other programming techniques as well? Is this related to the principle of "doing a single thing in your method and do it well" ?</p>

答:
Principle of least astonishment is when you, as an API designer, prevent your users from saying WAT.

Some examples of astonishment in varying languages.

```<code>var array=new string[];
var list=array as IList<string>; //this works...
list.Add("foo"); //exception saying it's not supported

foo.Equals(bar); //will call overriden Equals method
foo == bar; //equivalent to above in everyway, except for it won't call overrides... unless you're dealing with a string

var d=DateTime.Today;
d.Add(new TimeSpan(36,0,0,0)); //add 36 days to datetime d
Console.Writeline(d); //will print todays date. WAT

//in javascript
var f=function(){
  return
    10;
} //will either throw a syntax error or return void, depending on your javascript runner
</code>```

And there are many more examples in various languages and APIs. Your job as an API writer is to prevent this. Things should be named and typed in such a way that it's blatantly obvious what a call to your API will do. Include ample documentation where this isn't possible.

Basically, if people have to read your documentation thoroughly to figure out how to READ code written for your API, you're probably doing it wrong.

Body:
Principle of least astonishment is when you, as an API designer, prevent your users from saying WAT.

Some examples of astonishment in varying languages.

var array=new string[];
var list=array as IList<string>; //this works...
list.Add("foo"); //exception saying it's not supported

foo.Equals(bar); //will call overriden Equals method
foo == bar; //equivalent to above in everyway, except for it won't call overrides... unless you're dealing with a string

var d=DateTime.Today;
d.Add(new TimeSpan(36,0,0,0)); //add 36 days to datetime d
Console.Writeline(d); //will print todays date. WAT

//in javascript
var f=function(){
  return
    10;
} //will either throw a syntax error or return void, depending on your javascript runner

And there are many more examples in various languages and APIs. Your job as an API writer is to prevent this. Things should be named and typed in such a way that it's blatantly obvious what a call to your API will do. Include ample documentation where this isn't possible.

Basically, if people have to read your documentation thoroughly to figure out how to READ code written for your API, you're probably doing it wrong.


答:
The Principle of Least Astonishment is applicable to a wide range of design activities - and not just in computing (though that is often where the most astonishing things happen).

Consider an elevator with a button next to it that says "call".  When you press the button, the payphone rings (rather than calling the elevator to that floor).  This would be considered astonishing.  The correct design would be to put the call button next to the phone rather than the elevator.

Next, think of a web page that has a pop up window that shows a windows style error with an 'ok' button on it.  People click the 'ok' button thinking it is for the operating system and instead go to another web page.  This astonishes the user.

When it comes to an API...

Think about a toString() method that instead of printing out the fields returns back "to be implemented".

An equals() method that works on hidden information.

Sometimes people try to implement a sorted list class by changing the add method to call sort() on the array afterwards - which is astonishing because the add method is supposed to append to the list - this is especially astonishing when one gets back a List object with no knowledge that somewhere deep inside, someone violated the interface contract.

Having a method that does one distinct thing contributes to reduction of astonishment, however these are separate principles in API design.  The four principles often touted as "good API design" are (from this pdf - just one instance of such a presentation.  The links at the end of this particular one make for good reading):

Single responsibility principle

Open closed principle

DRY

Principle of least astonishment

It is potentially astonishing for someone to have a class that tries to do everything - or needing two classes to do a single thing.  It is likewise potentially astonishing for someone to mess with the internals in odd ways under the covers (I find open classes in Ruby to be a source of never-ending astonishment).  It is also likewise astonishing to find two methods that do apparently the same thing.

As such, the principle of least astonishment underlies the other API designs - but it, itself, is not sufficient to simply say "don't have an astonishing API."

Further reading (from the UI perspective) - an IBM developer blog titled The cranky user: The Principle of Least Astonishment

Title: What is the principle of least astonishment?

Body: In programming what is called Principle of Least Astonishment? How is this concept related to designing good APIs?  Is this something applicable to only object oriented programming or does it permeate other programming techniques as well? Is this related to the principle of "doing a single thing in your method and do it well" ?</p>


答:
Here's an example of "astonishment" that happened to me recently. I got lost on the road, so pulled over and somewhat frantically (I was late) punched an intersection into my GPS. I clicked Go and put my hands back on the wheel - but then got a loud (full-screen) warning that the GPS should be updated - requiring me to acknowledge.

My thought was "are you kidding? you're telling me this now? I need to take my hands off the wheel to acknowledge?".

Astonishment surfaces in the interface (typically the UI, but I suppose it could also be an API that behaves in an unexpected manner). I would say it permeates below the interface as well, because it takes well-designed underlying software to support a truly well-designed interface.


问:
Domain Driven Design with an EAV database model
How can one apply DDD to a EAV database model?

Consider this EAV database model:

How am I supposed to build a domain model if all my entities and their attributes will be stored in the database?

UPDATE

To help clarify the question I'll give an example. If I'm building a Store that is going to sell some Products then I'll have 2 entities in my domain model corresponding to them.

Now my Product entity will normally have a fixed number of attributes (ex: Product_name, sku, weight, etc...). However, in a EAV model entities have a variable number of attributes.

How should I write a model for Product if each concrete instance of it will have a different number of attributes?

答:
DDD says nothing with regards to how you are going to persist your data and you shouldn't concern yourself with such things when creating your domain model. Doing so will tie your domain to your database (or other persistence method) which kind of defeats the purpose of creating a rich domain model to begin with.

From: http://devlicio.us/blogs/casey/archive/2009/02/12/ddd-there-is-no-database.aspx

So Why “There Is No Database”?
  Domain Driven Design states specifically, in the name, why – we are designing our applications from the point of view of the Domain, and the Domain is drawn from the Ubiquitous Language we negotiate with our Domain Experts.

If we were to start with a database the it would be Database Driven Design. If we were to consciously or subconsciously bring elements from the database into our Domain, then we would risk compromising our Domain model purely to support the persistence layer we had chosen.

Looking at the database tables you gave the code for the aggregate in c# could look something like this:

```<code>public class MyDomainObject
    public int Id { get; set; }

    public IList<MyDomainObjectAttribute> Attributes = new List<MyDomainObjectAttribute>();

    public class MyDomainObjectAttribute {
            public string Name { get; set; }
            public string Value { get; set; }
    }
}
</code>```

We can then use a mapper class or something similar (ORM, EventStore, etc...) to persist our aggregate to durable storage (be it a database or something else).

Body:
DDD says nothing with regards to how you are going to persist your data and you shouldn't concern yourself with such things when creating your domain model. Doing so will tie your domain to your database (or other persistence method) which kind of defeats the purpose of creating a rich domain model to begin with.

From: http://devlicio.us/blogs/casey/archive/2009/02/12/ddd-there-is-no-database.aspx

So Why “There Is No Database”?
  Domain Driven Design states specifically, in the name, why – we are designing our applications from the point of view of the Domain, and the Domain is drawn from the Ubiquitous Language we negotiate with our Domain Experts.

If we were to start with a database the it would be Database Driven Design. If we were to consciously or subconsciously bring elements from the database into our Domain, then we would risk compromising our Domain model purely to support the persistence layer we had chosen.

Looking at the database tables you gave the code for the aggregate in c# could look something like this:

public class MyDomainObject
    public int Id { get; set; }

    public IList<MyDomainObjectAttribute> Attributes = new List<MyDomainObjectAttribute>();

    public class MyDomainObjectAttribute {
            public string Name { get; set; }
            public string Value { get; set; }
    }
}

We can then use a mapper class or something similar (ORM, EventStore, etc...) to persist our aggregate to durable storage (be it a database or something else).


问:
How to write useful Java programs without using mutable variables
I was reading an article about functional programming where the writer states

```<code>(take 25 (squares-of (integers)))
</code>```

Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.

Is it possible to achieve this in Java? Supposing you are required to print the squares of first 15 integers, could you write a for or while loop without using variables?

Mod notice

This question is not a code golf contest. We are looking for answers that explain the concepts involved (ideally without repeating earlier answers), and not just for yet another piece of code.

答:
As we're looking for an example of the concepts, I'd say let's set aside Java and look for a different yet familiar setting in which to find a familiar version of the concepts. UNIX pipes are rather similar to chaining lazy functions.

```<code>cat /dev/zero | tr '\0' '\n' | cat -n | awk '{ print $0 * $0 }' | head 25
</code>```

In Linux this means, give me bytes each of which is composed of false rather than true bits, until I lose my appetite; change each of those bytes to a newline character; number each line thus created; and produce the square of that number. Furthermore I have appetite for 25 lines and no more.

I claim that a programmer wouldn't be ill advised to write a Linux pipeline in that manner. It's relatively normal Linux shell scripting.

I claim that a programmer would be ill advised to attempt writing the same thing similarly in Java. The reason is software maintenance as a major factor in the lifetime cost of software projects. We don't want to befuddle the next programmer by presenting what is ostensibly a Java program but actually is written in effect in a custom one-off  language by elaborately duplicating functionality that already exists in the Java platform.

On the other hand, I claim that the next programmer could be more accepting if some of our "Java" packages are actually Java Virtual Machine packages written in one of the functional or object/functional languages such as Clojure and Scala. These are designed to be coded by chaining functions together and to be called from Java in the normal manner of Java method calls.

Then again, it can still be a good idea for a Java programmer to take inspiration from functional programming, in places.

<s>Recently my favorite technique [was] to use an immutable, uninitialized return variable and a single exit so that, as some functional language compilers do, Java checks that no matter what happens in the body of the function, I always provide one and only one return value. Example:

```<code>int f(final int n) {
    final int result; // not initialized here!
    if (n < 0) {
        result = -n;
    } else if (n < 1) {
        result = 0;
    } else {
        result = n - 1;
    }
    // If I would leave off the "else" clause,
    // Java would fail to compile complaining that
    // "result" is possibly uninitialized.
    return result;
}
</code>```

</s>

Body:
As we're looking for an example of the concepts, I'd say let's set aside Java and look for a different yet familiar setting in which to find a familiar version of the concepts. UNIX pipes are rather similar to chaining lazy functions.

cat /dev/zero | tr '\0' '\n' | cat -n | awk '{ print $0 * $0 }' | head 25

In Linux this means, give me bytes each of which is composed of false rather than true bits, until I lose my appetite; change each of those bytes to a newline character; number each line thus created; and produce the square of that number. Furthermore I have appetite for 25 lines and no more.

I claim that a programmer wouldn't be ill advised to write a Linux pipeline in that manner. It's relatively normal Linux shell scripting.

I claim that a programmer would be ill advised to attempt writing the same thing similarly in Java. The reason is software maintenance as a major factor in the lifetime cost of software projects. We don't want to befuddle the next programmer by presenting what is ostensibly a Java program but actually is written in effect in a custom one-off  language by elaborately duplicating functionality that already exists in the Java platform.

On the other hand, I claim that the next programmer could be more accepting if some of our "Java" packages are actually Java Virtual Machine packages written in one of the functional or object/functional languages such as Clojure and Scala. These are designed to be coded by chaining functions together and to be called from Java in the normal manner of Java method calls.

Then again, it can still be a good idea for a Java programmer to take inspiration from functional programming, in places.

<s>Recently my favorite technique [was] to use an immutable, uninitialized return variable and a single exit so that, as some functional language compilers do, Java checks that no matter what happens in the body of the function, I always provide one and only one return value. Example:

int f(final int n) {
    final int result; // not initialized here!
    if (n < 0) {
        result = -n;
    } else if (n < 1) {
        result = 0;
    } else {
        result = n - 1;
    }
    // If I would leave off the "else" clause,
    // Java would fail to compile complaining that
    // "result" is possibly uninitialized.
    return result;
}

</s>


问:
Count true array elements
In my code (Python+numpy or Matlab, but issue can apply to any array programming language), I often need to count the number of elements in an array where the elements are true. Usually, I implement this as sum(x>0.5), but this may be considered improper. See Is it correct to add booleans in order to count the number of true values in a vector?. Numpy has count_nonzero, but if there is no special-purpose function, what would be the proper way to write this?

For example, in Matlab, I can either write sum(x>.5) or length(find(x>0.5)). The former is slightly faster but may be considered improper (see above). Are there any other alternatives for counting the number of true values in an array, and what should be my criteria for selecting one?

(In a low-level language, one would write an explicit for-loop, but that is an extremely inefficient way to implement this in a high-level array programming language)

答:
This seems like a natural use for a fold to me

i.e. something like this in pseudo functional code

```<code>let countiftrue bs = fold (fun acc b -> if b then acc + 1 else acc) 0 bs
</code>```

better yet have it as a higher order function that accepts a predicate to make it even more useful

```<code>let countif p xs = fold (fun acc x -> if p x then acc + 1 else acc) 0 xs
</code>```

Title: Count true array elements

Body:
This seems like a natural use for a fold to me

i.e. something like this in pseudo functional code

let countiftrue bs = fold (fun acc b -> if b then acc + 1 else acc) 0 bs

better yet have it as a higher order function that accepts a predicate to make it even more useful

let countif p xs = fold (fun acc x -> if p x then acc + 1 else acc) 0 xs