答:
The order of evaluation is usually undefined, and therefore can go either way depending on the compiler, although some pedantic languages might define it.  That's why most of the time when you see an example like that, it's to warn you not to do it.

If the compiler goes strictly by the order the index is needed, the book is right, because you have to read the value, then perform the addition, then do the assignment.  However, you don't have to compute the array indexes in the same order they are used, and some optimizations might take advantage of that fact.

Allow me to demonstrate with some intermediate representation pseudocode.  The first pass of a compiler will usually produce something like this:

```<code>temp1 = f(3)
temp2 = a[temp1]
temp3 = temp2 + 2
temp4 = f(3)
a[temp4] = temp3
</code>```

Line 1 must come before line 2.  Line 2 must come before line 3.  Line 3 must come before line 5.  Line 4 must come before line 5.  Aside from that, the order of execution is not usually defined by the language, so compilers will do whatever is more efficient or easier to implement.  It is perfectly allowed to end up like this:

```<code>temp4 = f(3)
temp1 = f(3)
temp2 = a[temp1]
temp3 = temp2 + 2
a[temp4] = temp3
</code>```

A compiler might do it that way if the last three lines can be combined into a single assembly instruction.  Since the destination is often specified first in an assembly instruction, it might make sense to calculate the destination index first, but you don't have to do it in that order.

Another compiler might not have so many registers to work with, or have a smaller instruction set, so they might calculate the source index first in order to be able to reuse the temp1 register.

Languages usually purposely leave it undefined to allow compiler implementations to do whatever is most efficient.

Body:
The order of evaluation is usually undefined, and therefore can go either way depending on the compiler, although some pedantic languages might define it.  That's why most of the time when you see an example like that, it's to warn you not to do it.

If the compiler goes strictly by the order the index is needed, the book is right, because you have to read the value, then perform the addition, then do the assignment.  However, you don't have to compute the array indexes in the same order they are used, and some optimizations might take advantage of that fact.

Allow me to demonstrate with some intermediate representation pseudocode.  The first pass of a compiler will usually produce something like this:

temp1 = f(3)
temp2 = a[temp1]
temp3 = temp2 + 2
temp4 = f(3)
a[temp4] = temp3

Line 1 must come before line 2.  Line 2 must come before line 3.  Line 3 must come before line 5.  Line 4 must come before line 5.  Aside from that, the order of execution is not usually defined by the language, so compilers will do whatever is more efficient or easier to implement.  It is perfectly allowed to end up like this:

temp4 = f(3)
temp1 = f(3)
temp2 = a[temp1]
temp3 = temp2 + 2
a[temp4] = temp3

A compiler might do it that way if the last three lines can be combined into a single assembly instruction.  Since the destination is often specified first in an assembly instruction, it might make sense to calculate the destination index first, but you don't have to do it in that order.

Another compiler might not have so many registers to work with, or have a smaller instruction set, so they might calculate the source index first in order to be able to reuse the temp1 register.

Languages usually purposely leave it undefined to allow compiler implementations to do whatever is most efficient.


问:
What's the effect of this assignment (whatever the language)?
I think my book (Programming Languages: Principles and Paradigms) is wrong. a is a vector, assume a C-like language:

b = 0;
a[f(3)] = a[f(3)] + 1;

int f(int n) {
    if(b == 0) {
        b = 1;

        return 1;
    }
    else return 2;
}
```

It has the effect of assigning the value of a[1] + 1 to a[2] whenever
  the evaluation of the left-hand component of the assignment precedes
  the evaluation of the right-hand one.

For me, it has the opposite effect, that is assigning the value of a[2] + 1 to a[1].

Because the left-hand component is evaluated first, so f returns 1 (because b is 0), thus a[1]. Then the right-hand component is evaluated, f returns 2 (because now b is 1), thus a[2] + 1.

Am I right and the book is wrong? Unfortunatly there is no errata...

答:
Your line of code is equivalent to

```<code>a[x] = a [y] + 1;
</code>```

The book may have it backwards, saying something happens when the left (x) is evalulated first, but actually that happens when the right (y) is evaluated first, but that is almost certainly not the point.

The point is that you don't know whether x or y will be evaluated first. You may feel that "before computing the value (right-hand side), the compiler should compute the l-value (left-side)" but you didn't write every compiler on the planet. Some compiler writers might want to go left to right, some right to left, some according to the order you will need them - you need y first, to get a value to add 1 to, and only then do you need x to figure out where to put the value - and they are all correct because this particular decision is left up to the compiler writer and you must not rely on it, ever.

ContentLicense: CC BY-SA 3.0

Body:
Your line of code is equivalent to

a[x] = a [y] + 1;

The book may have it backwards, saying something happens when the left (x) is evalulated first, but actually that happens when the right (y) is evaluated first, but that is almost certainly not the point.

The point is that you don't know whether x or y will be evaluated first. You may feel that "before computing the value (right-hand side), the compiler should compute the l-value (left-side)" but you didn't write every compiler on the planet. Some compiler writers might want to go left to right, some right to left, some according to the order you will need them - you need y first, to get a value to add 1 to, and only then do you need x to figure out where to put the value - and they are all correct because this particular decision is left up to the compiler writer and you must not rely on it, ever.


答:
You wrote "assume a C-like language". Just how C-like should it be?

First, it does appear that the author's logic is backwards:

It has the effect of assigning the value of a[1] + 1 to a[2] whenever
  the evaluation of the left-hand component of the assignment precedes
  the evaluation of the right-hand one.

In fact, it has that effect if the evaluation of the LHS follows the evaluation of the RHS.

Some "C-like" languages (in the sense that their syntax looks similar to C's) define the order of evaluation of expressions. (I think Java does this.) In such a language, the semantics of the code would depend on exactly how the language defines the order of evaluation. If the order is left-to-right, then the function call on the LHS (left-hand side) of the assignment will be evaluated first.

In C itself (and in C++), the order of evaluation is unspecified.  The two function calls could be evaluated in either order, depending on the whim of the compiler (optimization can change this; so, in principle, can the phase of the moon). I don't believe the behavior of this particular code is actually undefined, which would mean that the language says nothing about how it behaves, but similar code such as:

```<code>a[i++] = a[i++] + 1;
</code>```

does have undefined behavior, because i is modified twice with no intervening sequence point.  In C, the above could evaluate the LHS i++ before the right one, or vice versa -- but those aren't the only possibilities.  A C compiler is free to assume that your program doesn't modify i twice between sequence points.  This particular example seems easy for the compiler to detect, but in more complex cases it can be difficult or impossible to do so.

But the real answer to the question is: Don't write code like that.

You really don't need to have two function calls in a single statement, where the results depend on the order in which they're evaluated.  Separate the calls into distinct statements, for example:

```<code>int x = f(3);
int y = f(3);
a[x] = a[y] + 1;
</code>```

And in real life, you want better names than x, y, f, and a -- and f() probably shouldn't return different results on successive calls, or it should be very clear why it needs to do so.

Write your code so that questions like this don't arise in the first place.

Title: What's the effect of this assignment (whatever the language)?

Body:
I think my book (Programming Languages: Principles and Paradigms) is wrong. a is a vector, assume a C-like language:

b = 0;
a[f(3)] = a[f(3)] + 1;

int f(int n) {
    if(b == 0) {
        b = 1;

        return 1;
    }
    else return 2;
}
```

It has the effect of assigning the value of a[1] + 1 to a[2] whenever
  the evaluation of the left-hand component of the assignment precedes
  the evaluation of the right-hand one.

For me, it has the opposite effect, that is assigning the value of a[2] + 1 to a[1].

Because the left-hand component is evaluated first, so f returns 1 (because b is 0), thus a[1]. Then the right-hand component is evaluated, f returns 2 (because now b is 1), thus a[2] + 1.

Am I right and the book is wrong? Unfortunatly there is no errata...

Body:
You wrote "assume a C-like language". Just how C-like should it be?

First, it does appear that the author's logic is backwards:

It has the effect of assigning the value of a[1] + 1 to a[2] whenever
  the evaluation of the left-hand component of the assignment precedes
  the evaluation of the right-hand one.

In fact, it has that effect if the evaluation of the LHS follows the evaluation of the RHS.

Some "C-like" languages (in the sense that their syntax looks similar to C's) define the order of evaluation of expressions. (I think Java does this.) In such a language, the semantics of the code would depend on exactly how the language defines the order of evaluation. If the order is left-to-right, then the function call on the LHS (left-hand side) of the assignment will be evaluated first.

In C itself (and in C++), the order of evaluation is unspecified.  The two function calls could be evaluated in either order, depending on the whim of the compiler (optimization can change this; so, in principle, can the phase of the moon). I don't believe the behavior of this particular code is actually undefined, which would mean that the language says nothing about how it behaves, but similar code such as:

a[i++] = a[i++] + 1;

does have undefined behavior, because i is modified twice with no intervening sequence point.  In C, the above could evaluate the LHS i++ before the right one, or vice versa -- but those aren't the only possibilities.  A C compiler is free to assume that your program doesn't modify i twice between sequence points.  This particular example seems easy for the compiler to detect, but in more complex cases it can be difficult or impossible to do so.

But the real answer to the question is: Don't write code like that.

You really don't need to have two function calls in a single statement, where the results depend on the order in which they're evaluated.  Separate the calls into distinct statements, for example:

int x = f(3);
int y = f(3);
a[x] = a[y] + 1;

And in real life, you want better names than x, y, f, and a -- and f() probably shouldn't return different results on successive calls, or it should be very clear why it needs to do so.

Write your code so that questions like this don't arise in the first place.


问:
How is the Trial Period for Softwares generally implemented?
I was always under the assumption that trial softwares write a registry value of the installation date and then the software makes a comparison of the current date of the system with the remaining days + installation date to verify whether the trial period is still valid or not. If this assumption is to be true, winding your system clock further up ahead than the remaining days should end the trial period of the software (or keep winding the clock backwards to use the trial software as long as you wanted to). From experience, This was the case for some softwares, not so for others.

For the latter case, I noticed that the trial period expires only after the days have passed in real time. I confirmed that the software wasn't connecting to the outer network for validation mechanism, so it is definitely something being done locally on the computer. How does the trial period validation work in this case?

答: The way my trial versions handle it is to track a trial period 'window'.  The program won't run if the date is set back or forward.  Every time the program is run, the window gets smaller, and the updated 'start' time in the trial window is changed.</p>


问:
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.

答:
Implement a Monopoly game. Monopoly has an obvious sequence and lends itself to division into funcitons very easily. It also only requires a one dimensional array and a few basic classes. The logic is simple enough so that the students will think more about "how" than "what", and it results in something that can be demonstrated to others.

Give them an encrypted file that was encrypted with some reversible rule and ask them to write a decoder (make it simple enough though). This gives an extra incentive to solve it because of the mystery about the message's content.

I don't know why you only cover one dimensional arrays and not matrices (they really aren't all that different), but if you are willing to include that into the sylabus Jon Conway's Game of Life is also relatively easy and results in something fun.

A game like chess requires some thought but is still within the confines of what a beginner can do with minimal inheritance (specific pieces inherit from a general class Piece, and the board holds objects of type Piece), and 2D arrays (you can choose to simplify it by not requiring to implement hard stuff like stelmate detection or inability to castle if an enemy pieces is threatening the castling path).

ContentLicense: CC BY-SA 2.5


问:
Features that encourage use of project management software
I'm a student and I work as an undergrad in an IT department. They are very effective programmers, but as far as documenting what they do and tracking what time is spent on specific tasks - not so much.

I was put in charge of setting up project management software. So far, I've created a satisfactory solution with Trac. But still, programmers use it because "the boss says so" and do so grudgingly.

No one likes having to go to a separate webpage, logging what they did, checking boxes, and what not - so my question is this:

As a programmer, what incentives or features in project management software would encourage you (or least make it more bearable) to use it?

答:
One feature that worked well for me was a taskbar applet, or whatever a program running hidden with a small icon on the taskbar is called, that was always running on my machine and letting me know about events in the tracking system relevant to me. It would show a little reminder when I had a new bug or a new task assigned to me. It was also caching and refreshing queries in the background, so when I needed to see the list of my bugs, it was ready and appeared immediately after I clicked (no waiting for a web page to render, login, etc.).

Something like this could also be used to quickly report time allocation. Just double-click the item, and report today's progress within two clicks, assuming it would pre-populate the reporting form with yesterday's values and good defaults.

It was an internal tool, and I don't know which of the tracking systems offers such feature.


问:
Is there a code tag to indicate "need improvement" on code comments?
TODO indicates "task to be completed", FIXME to be fixed etc. Is there a code tag to indicate "need improvement" on code comments?</p>

答:
The closest thing to a document trying to standardize this is the Python PEP 350 - which was rejected as not a standard.

The Mnemonics section has a list of various ones used - I hesitate to call any of them "commonly used" beyond "TODO", "FIXME" and "XXX" (which are predefined in eclipse).

Going beyond this, it is local convention of that code base and team.

The new question - is there a "need improvement" type code tag.  The best practice would to use the minimal set of tags.  "TODO" indicates a task in the code.  // TODO this code needs to be refactored would be sufficient rather than using another // RFE should refactor or // IDEA you know, we should refactor this.  TODO is already recognized by Eclipse, by convention, by mylyn.


问:
Should I return from a function early or use an if statement?
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

答:
I prefer to keep if statements small.

So, choosing between:

if condition:
   line1
   line2
    ...
   line-n
```

<p>and</p>

<pre class="lang-python prettyprint-override"><code>if not condition: return

line1
line2
 ...
line-n
</code>```

I'd choose what you described as "early return".

Mind you, I don't care about early returns or whatever, I just really like to simplify the code, shorten the bodies of if statements, etc.

Nested if's and for's and while's are horrible, avoid them at all costs.

Body:
I prefer to keep if statements small.

So, choosing between:

if condition:
   line1
   line2
    ...
   line-n

and

if not condition: return

line1
line2
 ...
line-n

I'd choose what you described as "early return".

Mind you, I don't care about early returns or whatever, I just really like to simplify the code, shorten the bodies of if statements, etc.

Nested if's and for's and while's are horrible, avoid them at all costs.


问:
Many small classes vs. logical (but) intricate inheritance
I'm wondering what is better in terms of good OOP desing, clean code, flexibility and avoiding code smells in the future. Image situation, where you have a lot of very similar objects you need to represent as classes. These classes are without any specific functionality, just data classes and are different just by name (and context) Example:

```<code>Class A
{
  String name;
  string description;
}

Class B
{
  String name;
  String count;
  String description;
}

Class C
{
  String name;
  String count;
  String description;
  String imageUrl;
}

Class D
{
  String name;
  String count;
}

Class E
{
  String name;
  String count;
  String imageUrl;
  String age;
}
</code>```

Would it be better to keep them in separate classes, to get "better" readability, but wit many code repetitions, or would it be better to use inheritance to be more DRY?

By using inheritance, you will end up with something like this, but class names will lost it contextual meaning (because of the is-a, not has-a):

```<code>Class A
{
  String name;
  String description;
}

Class B : A
{
  String count;
}

Class C : B
{
  String imageUrl;
}

Class D : C
{
  String age;
}
</code>```

I know inheritance is not and should not be used for code reuse, but I don't see any other possible way how to reduce code repetition in such case.

答:
The general rule reads "Prefer delegation over inheritance", not "avoid all inheritance". If the objects have a logical relationship and a B can be used wherever an A is expected, it is good practice to use inheritance. However, if the objects just happen to have fields with the same name, and have no domain relationship, do not use inheritance.

Quite often, it pays off to ask the question of "reason of change" in the design process: If class A gets an extra field, would you expect that class B gets it as well? If that's true, the objects share a relationship, and inheritance is a good idea. If not, suffer the little repetition to keep distinct concepts in distinct code.


问:
Why does the .Net world seem to embrace magic strings instead of staticly typed alternatives?
So, I work in .Net. I make open source projects in .Net. One of my biggest problems with it isn't necessariyl with .Net, but with the community and frameworks around it. It seems everywhere that magical naming schemes and strings is treated as the best way to do everything. Bold statement, but look at it:

ASP.Net MVC:

Hello world route:

```<code>        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
</code>```

What this means is that ASP.Net MVC will somehow look up HomeController in your code. Somehow make a new instance of it, and then call the function Index  apparently with an id parameter of some sort. And then there are other things like:

```<code>RenderView("Categories", categories);
...or..
ViewData["Foobar"]="meh";
</code>```

And then there are similar things with XAML as well. DataContext is treated as an object and you have to hope and pray that it resolves to the type you want. DependencyProperties must use magic strings and magic naming conventions. And things like this:

```<code>  MyData myDataObject = new MyData(DateTime.Now);
  Binding myBinding = new Binding("MyDataProperty");
  myBinding.Source = myDataObject;
</code>```

Although it relies more on casting and various magical runtime supports.

Anyway, I say all that to end up here: Why is this so well tolerated in the .Net world? Aren't we using statically typed languages to almost always know what the type of things are? Why is reflection and type/method/property/whatever names(as strings) prefered so much in comparison to generics and delegates or even code generation?

Are there inherit reasons that I'm missing for why ASP.Net's routing syntax relies almost exclusively on reflection to actually resolve how to handle a route? I hate when I change the name of a method or property and suddenly things break, but there don't appear to be any references to that method or property and there are of course no compiler errors. Why was the apparent convenience of magic strings considered "worth it"?

I know there are also commonly statically typed alternatives to some things, but they usually take a backseat and seem to never be in tutorials or other beginner material.

答:
Actually there is a push back in the .NET world against these very things you mentioned. In the first example you gave however, the routing engine is given a convention for mapping the default route. The very fact that the routes are dynamic make it nigh impossible to use a static configuration.

You also mention XAML/WPF, both of which were under development well before generics were introduced into .NET and going back to support generics would have delayed an already very late product (Longhorn/Vista) even further.

There are examples within the ASP.NET MVC framework of using lambda expressions in place of magic strings and the Entity Framework/LINQ takes it even further where the language and framework provides native support for composing SQL queries over a static object graph (instead of constructing magic SQL strings, you get compile time validation of your queries).

For other examples of static configuration see structuremap and other modern dependency injection containers, and other frameworks that need to inspect the object graph at runtime but allow the developer to statically provide hints using lambda expressions.

So the short answer is that historically, .NET did not support static traversal of an object graph until the 3.5 release. Now that we have it, many developers prefer it over magic strings and many have been pushing for even deeper support such as a symbolOf operator that works similar to the typeOf operator.


答:
By using inheritance, you will end up with something like this, but class names will lost it contextual meaning (because of the is-a, not has-a):

Exactly. Look at this, out of context:

```<code>Class D : C
{
    String age;
}
</code>```

What properties does a D have? Can you remember? What if you complicate the hierarchy further:

```<code>Class E : B
{
    int numberOfWheels;
}

Class F : E
{
    String favouriteColour;
}
</code>```

And then what if, horror upon horrors, you want to add an imageUrl field to F but not E? You cannot derive it from C and E.

I've seen an actual situation where a lot of different Component types all had a name, an ID and a Description. But this wasn't by the nature of their being components, it was just a coincidence. Each had an ID because they were stored in a database. The name and description were for display.

Products also had an ID, Name and Description, for similar reasons. But they weren't components, nor were components products. You would never see the two things together.

But, some developer had read about DRY and decided he'd remove every hint of duplication from the code. So he called everything a product and did away with the need to define those fields. They were defined in Product and everything that needed those fields could derive from Product.

I cannot say this strongly enough: This is not a good idea.

DRY is not about removing the need for common properties. If an object is not a Product, don't call it a Product. If a Product doesn't REQUIRE a Description, by the very nature of its being a Product, do not define Description as a Property of Product.

It happened, eventually, that we had Components without descriptions. So we started having null Descriptions in those objects. Not nullable. Null. Always. For any Product of type X ... or later Y ... and N.

This is an egregious breach of Liskov Substitution Principle.

DRY is about never putting yourself in a position where you might fix a bug in one place and forget to do it somewhere else. This isn't going to happen because you have two objects with the same property. Never. So don't worry about it.

If the context of the classes makes it obvious that you should, which will be very rare, then and only then should you consider a common parent class. But, if it's properties, consider why you're not using an interface instead.

Title: Many small classes vs. logical (but) intricate inheritance

Body:
I'm wondering what is better in terms of good OOP desing, clean code, flexibility and avoiding code smells in the future. Image situation, where you have a lot of very similar objects you need to represent as classes. These classes are without any specific functionality, just data classes and are different just by name (and context) Example:

```<code>Class A
{
  String name;
  string description;
}

Class B
{
  String name;
  String count;
  String description;
}

Class C
{
  String name;
  String count;
  String description;
  String imageUrl;
}

Class D
{
  String name;
  String count;
}

Class E
{
  String name;
  String count;
  String imageUrl;
  String age;
}
</code>```

Would it be better to keep them in separate classes, to get "better" readability, but wit many code repetitions, or would it be better to use inheritance to be more DRY?

By using inheritance, you will end up with something like this, but class names will lost it contextual meaning (because of the is-a, not has-a):

```<code>Class A
{
  String name;
  String description;
}

Class B : A
{
  String count;
}

Class C : B
{
  String imageUrl;
}

Class D : C
{
  String age;
}
</code>```

I know inheritance is not and should not be used for code reuse, but I don't see any other possible way how to reduce code repetition in such case.

Body:
By using inheritance, you will end up with something like this, but class names will lost it contextual meaning (because of the is-a, not has-a):

Exactly. Look at this, out of context:

Class D : C
{
    String age;
}

What properties does a D have? Can you remember? What if you complicate the hierarchy further:

Class E : B
{
    int numberOfWheels;
}

Class F : E
{
    String favouriteColour;
}

And then what if, horror upon horrors, you want to add an imageUrl field to F but not E? You cannot derive it from C and E.

I've seen an actual situation where a lot of different Component types all had a name, an ID and a Description. But this wasn't by the nature of their being components, it was just a coincidence. Each had an ID because they were stored in a database. The name and description were for display.

Products also had an ID, Name and Description, for similar reasons. But they weren't components, nor were components products. You would never see the two things together.

But, some developer had read about DRY and decided he'd remove every hint of duplication from the code. So he called everything a product and did away with the need to define those fields. They were defined in Product and everything that needed those fields could derive from Product.

I cannot say this strongly enough: This is not a good idea.

DRY is not about removing the need for common properties. If an object is not a Product, don't call it a Product. If a Product doesn't REQUIRE a Description, by the very nature of its being a Product, do not define Description as a Property of Product.

It happened, eventually, that we had Components without descriptions. So we started having null Descriptions in those objects. Not nullable. Null. Always. For any Product of type X ... or later Y ... and N.

This is an egregious breach of Liskov Substitution Principle.

DRY is about never putting yourself in a position where you might fix a bug in one place and forget to do it somewhere else. This isn't going to happen because you have two objects with the same property. Never. So don't worry about it.

If the context of the classes makes it obvious that you should, which will be very rare, then and only then should you consider a common parent class. But, if it's properties, consider why you're not using an interface instead.


答:
Isn't this what interfaces are for? Unrelated classes with different functions but with a similar property.</p>

```<code>IName = Interface(IInterface)
  function Getname : String;
  property Name : String read Getname
end;

Class Dog(InterfacedObject, IName)
private
  FName : String;
  Function GetName : String;
Public
  Name : Read Getname;
end;

Class Movie(InterfacedObject, IName)
private
  FCount;
  FName : String;
  Function GetName : String;
Public
  Name : String Read Getname;
  Count : read FCount;
end;
</code>```

Body:
Isn't this what interfaces are for? Unrelated classes with different functions but with a similar property.

IName = Interface(IInterface)
  function Getname : String;
  property Name : String read Getname
end;

Class Dog(InterfacedObject, IName)
private
  FName : String;
  Function GetName : String;
Public
  Name : Read Getname;
end;

Class Movie(InterfacedObject, IName)
private
  FCount;
  FName : String;
  Function GetName : String;
Public
  Name : String Read Getname;
  Count : read FCount;
end;


答:
Inheritance is way to achieve polymorphic behavior. If your classes don't have any behavior, then inheritance is useless. In this case, I would not even consider them objects/classes, but structures instead.

If you want to be able to put different structures in different parts of your behavior, then consider interfaces with get/set methods or properties, like IHasName, IHasAge, etc..
This will make the design much more cleaner and allow better composition of these kind of hiearchies.


问:
Proper Git setup between designers and developers?
Basically we now have 2 developers for an iOS project, 2 developers for an Android project and 1 designer doing designs for both projects.

Right now, the way we exchange designs and images is through mail...so not very advanced or efficient. We're switching to Dropbox, but I feel like we could go a step further and somehow integrate the process into Git.

For the iOS project, we are using Git, and I'm thinking that it might be a good idea to introduce the designer as well to Git. The problem is that, being a designer, it might be a bit difficult for him to understand source version control.

As the 2 iOS devs, we'll probably be doing a lot of commits, branching, merging, but the designer will most likely only have to update images every now and then. We'd like to keep the setup as simple as possible (especially for the designer). We are using GitHub, so their OSX application might come in very handy for this.

Does anyone else have experience or best practices about how to set up the  branching/merging and integrating a designer into a technical Git project? Articles, blog posts etc. are welcomed as well.

答:
What you describe is a fairly common situation.

These are two typical setups I've used depending on the project.

(preferred) The designer and the developers do not share the project. The designer has his own project, doing his own commits, and the developers treat it as an external project, occasionally copying stuff from it into their own branches.

The designer and the developers share the same project. To keep things simple for the designer, don't make him work with multiple branches, let him stay on a single branch always. That way his workflow is be simply: git commit; git rebase origin; git push

In both of these setups, the designer needs to know only basic version control and it doesn't have to get in his way. The developers can use the products delivered by the designer by updating their copy of the designer's branch.

There might be other practical setups, workflows, I can only say that these two have been sufficient in my case.


问:
Should I split out synchronization from my class and what's it called?
When thinking about testability and modular code, I recently thought about whether I should split out the synchronization part of a class from the actual behavior part.

By example:

The app "needs" this:

```<code>class Mogrifier { // Mogrifier accesses are thread safe
private:
  unsigned int m_state;
  mutex m_sync;
public:
  Mogrifier()
  : m_state(0)
  { }

  unsigned int Mutate() {
    lock_guard<mutex> lock(m_sync);
    const unsigned int old = m_state;
    m_state += 42;
    return old;
   }

  :::
};
</code>```

Seems simple enough, except that locking and the actual stuff the class does aren't really related.

So I though about whether it's a good idea to split this up:

```<code>class Mogrifier { // Mogrifier is *not* synchronized
private:
  unsigned int m_state;
public:
  Mogrifier()
  : m_state(0)
  { }

  unsigned int Mutate() {
    const unsigned int old = m_state;
    m_state += 42;
    return old;
   }

  :::
};

class SyncedMogrifer {
private:
  mutex m_sync;
  Mogrifier m_;
public:
  unsigned int Mutate() {
    lock_guard<mutex> lock(m_sync);
    return m_.Mutate();
  }
};
</code>```

Would you do this?

Will it help with unit testing?

I'm awful with Pattern names ... what is it called?

Is there a simple way to "generate" such a wrapper in C++ for an arbitrary calls?

答:
I would do this if I had other classes that I wanted to synchronise. If I didn't then I would argue that it's needless complexity and the synchronised mogrifier looks good to me as it is.

It will help with unit testing if you want to test your synchronise code separate from the Mogrifier functionality, and vice verse. If not then it won't. Probably a good idea to unit test your synchronisation code as it's very easy to stuff up.

As for the last two questions... dunno :)

(Oh and BTW I'm Australian so I'm going to be bloody minded and spell synchronise with a S and not a Z even though chrome has highlighted all 5 instances of it in this textarea.)


问:
Which controller should I put for a search action that touches many different models?
I currently have the following models and am designing search functionality that searches within these 3 models:
Locations
Users
User_friends

Should I create a search controller or should I put the action in one of the existing locations, users, or user_friends controllers?  If so should it be pluralized - searches_controller or just search_controller?

答: I'd create a Searches controller, but perform the query in the models.</p>


答:
I'm going to be the dissenter here. I think you should give them valid business type-problems to solve not playtoys. If they aren't serious enough to be interested and motivated with the kind of work they will be actually doing as a professional, I'd rather you flunked them out in the intro course. Real work isn't about making cool stuff, it's about meeting the client's needs. I've also seen a lot of people who can;t make the leap between what they learning in a game and using the same techiniques in business programming.

Every senior developer and hiring manager I know is disgusted with the quality of recent graduates. Try focusing on what they need to learn to work in the real world and forget about making it fun.

Title: What are some good assignments for an introductory course, to reach today's students?

Body:
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.


问:
Do you start migrating your Swing project to JavaFX
I have a 4 years old project which is written in Swing + SwingX. Currently, it is still alive and still kicking.

However, as more GUI related feature requests coming in (For instance, a sortable tree table), I start to feel the difficulty in fulling the requests. This is true especially since there isn't any active development going around SwingX project.

Also, I can hardly find any good, yet actively maintained/ developed/ evolving GUI Java framework.

I was wondering, do any of the Swing developers feel the same thing? Have you start to migrate your Swing project to a much more active developed GUI framework, like JavaFX?

答:
I'm in the same position as the OP - having legacy swing applications but needing to implement new idioms and interfaces it does not natively support. The largest of these applications has been refactored a couple times for various reasons (improve modularity, better MVC and event dispatch structure, etc.) so I'm not completely averse to rewriting the UI code. So I've thought long and hard on the issue.

However, some things can't be solved with Swing without investing a lot more time and effort on what is essentially a legacy technology. For example, other than simple mouse events, new touch-screen devices and are unsupported by Swing itself. Providing a Swing based browser component is similarly troublesome or expensive, and in my case, the javafx-in-swing approach isn't an option as it complicates UI event handling in non-trivial ways.

I think it has been the old and faithful in its time, and if your platform is as unchanging as your code base - stick with it, obviously. But for an application to move forward into new more contemporary use cases, JavaFX 2+ will probably the way to move forward in my case.

As a side-note: the one misfeature in Swing I would have loved to have disappeared in jfx - but didn't - is the one-thread-to-rule-them-all approach to UI event dispatch. Any non-trivial user interface needs multi-threading to keep the UI crisp and responsive, and leaving it entirely up to the application developer to stumble over the same pitfalls so easily is a shortfall in the API IMHO.


问:
What does it mean to say an algorithm is Sound and Complete?
I heard different interpretations of sound and complete. I understand that completeness means finding a solution if there is one. What does it mean to say an algorithm is sound.

What does it mean to say an algorithm is Sound and Complete?

答:
I find Erik Dietrich's answer a tad confusing. The following is better:

An algorithm is sound if, anytime it returns an answer, that answer is true.
An algorithm is complete if it guarantees to return a correct answer for any arbitrary input (or, if no answer exists, it guarantees to return failure).

Two important points:

Soundness is a weak guarantee. It does not promise that A will terminate.

Soundness and Completeness are related concepts; infact they are the logical converse of each other. i.e. Soundness says that if an answer is returned that answer is true. Completeness says that an answer is true if it is returned.

Consider for an example a sorting algorithm A that receives as input a list of numbers. We say that A is sound if every time it returns a result that result is a sorted list. Likewise, we say that A is complete if guarantees to return a sorted list any time we give it a list of numbers.


问:
Why is Lisp useful?
Lisp obviously is an advantage for the AI stuff, but it doesn't appear to me that Lisp is any faster than Java, C#, or even C. I am not a master of Lisp, but I find it incredibly difficult to understand the advantage one would get in writing business software in Lisp.

Yet it is considered as a hacker's language.

Why does Paul Graham advocate Lisp? Why did ITA Software choose Lisp over other high-level languages? What value does it have over these languages?

答:
Paul Graham sort of answers this question himself in What Made Lisp Different.

Keep in mind he used it for his startup during the mid 1990s, so Python and Ruby weren't really mature at that point (or maybe not even born).

Lisp basically has all the advantages of dynamic languages, and I think for most of today's web applications, Python and Ruby are pretty awesome, and they have the advantage of frameworks and documentation and vibrant communities.

The killer feature is probably that the entire program is made of expressions. This means you can sort of pass around blocks of code to functions (or macros...), because a block of code is nothing more than an expression.

Python doesn't exactly have this feature; you'd have to define functions and pass them around. Ruby seems to have blocks, perhaps it's somewhat limited compared to what Lisp can do (I'm not sure).

Title: Why is Lisp useful?


问:
C# dynamics and Expando object
Under which application development scenarios C# dynamics and ExpandoObject can be used or when to consider using c# dynamics and ExpandoObject</p>

答:
This might be my personal opinion but : Never

You are using C#. Static typed language. And probably one of the reasons why are you using it is because you like the safety of static typing for various reasons. If you wanted to sacrifice it, you would be using real dynamic language like Python or Ruby.

Title: C# dynamics and Expando object


问:
How does if/else work internally in all programming languages?
```<code>if(true/false){
     //if condition is true
}else {
     // if condition is false
}
</code>```

Everyone knows about the structure of if-else. But what is if actually? Is it a class method, static method or keyword? I'm little confused about this.

答: Once you get down to the metal, it is a jump/branch statement -- basically a fancy goto.  Higher level languages have control structures that let you implement common low level activities in a clear and understandable manner.  But when you get down to it, it's a bunch of registers, jumps and poking things in and out of memory.</p>


答:
It can actually be several things. In imperative languages like C++ or Java, it is a statement type. In pure object-oriented languages like Smalltalk it is an instance method of boolean. In pure functional languages it is a function.

But in all languages it is a primitive. Some form of conditional must be built into the language. It may be slightly different type of conditional (e.g. cond in Lisp), but one must be built in.

Title: How does if/else work internally in all programming languages?

Body:
```<code>if(true/false){
     //if condition is true
}else {
     // if condition is false
}
</code>```

Everyone knows about the structure of if-else. But what is if actually? Is it a class method, static method or keyword? I'm little confused about this.


答:
I wouldn't let the designer use git. It's plenty of complications for him that he doesn't need. Just let him add his psd/jpg as attached files on your bug tracking system. It's good if he uses dropbox for his own "backup", but I clearly wouldn't let him use Git.

Not to mention the education problem, but also because the repo is then polluted with non-code related binaries. That Git is known to suck with.

Title: Proper Git setup between designers and developers?

Body:
Basically we now have 2 developers for an iOS project, 2 developers for an Android project and 1 designer doing designs for both projects.

Right now, the way we exchange designs and images is through mail...so not very advanced or efficient. We're switching to Dropbox, but I feel like we could go a step further and somehow integrate the process into Git.

For the iOS project, we are using Git, and I'm thinking that it might be a good idea to introduce the designer as well to Git. The problem is that, being a designer, it might be a bit difficult for him to understand source version control.

As the 2 iOS devs, we'll probably be doing a lot of commits, branching, merging, but the designer will most likely only have to update images every now and then. We'd like to keep the setup as simple as possible (especially for the designer). We are using GitHub, so their OSX application might come in very handy for this.

Does anyone else have experience or best practices about how to set up the  branching/merging and integrating a designer into a technical Git project? Articles, blog posts etc. are welcomed as well.


答:
It seems to me that you are asking two different questions:

How if else works internally?

What if is in terms of high level programming?

This answer is for question 1. For question 2 see other answers. Gustav Bertram's answer seems very clear.

Before your code gets executed, it must be translated into machine code. The translation is done by either a compiler (like a C-compiler) or an interpreter (like Ruby interpreter) or a virtual machine (like with Java).

Control structures like if-else are translated into a pattern of machine code instructions. The actual pattern depends on the target machine and the compiler/interpreter/virtual machine. An if-else-structure like

```<code>if (x >= y) {
    // main branch
} else {
    // else branch
}
</code>```

could be translated into code (here some kind of pseudo-assembly) like

```<code>cmp (r1),(r2)    ;compare words at memory addresses pointed by registers r1 and r2
blt else         ;jump to else-part if (r1) is less than (r2)
   ...           ;insert the main branch code here
bra end_if       ;jump to end_if
else:
   ...           ;insert the else branch code here
end_if:
</code>```

The actual machine code consists of just binary data but it is structurally similar with assembly code.

Body:
It seems to me that you are asking two different questions:

How if else works internally?

What if is in terms of high level programming?

This answer is for question 1. For question 2 see other answers. Gustav Bertram's answer seems very clear.

Before your code gets executed, it must be translated into machine code. The translation is done by either a compiler (like a C-compiler) or an interpreter (like Ruby interpreter) or a virtual machine (like with Java).

Control structures like if-else are translated into a pattern of machine code instructions. The actual pattern depends on the target machine and the compiler/interpreter/virtual machine. An if-else-structure like

if (x >= y) {
    // main branch
} else {
    // else branch
}

could be translated into code (here some kind of pseudo-assembly) like

cmp (r1),(r2)    ;compare words at memory addresses pointed by registers r1 and r2
blt else         ;jump to else-part if (r1) is less than (r2)
   ...           ;insert the main branch code here
bra end_if       ;jump to end_if
else:
   ...           ;insert the else branch code here
end_if:

The actual machine code consists of just binary data but it is structurally similar with assembly code.


答:
This answer is about languages like C, C++, Java, PHP and Javascript. There are other programming languages that work differently.

if is a keyword, and else is a keyword. When they are used in code, if and else together form a control flow statement.

Class methods, or static methods are always functions or procedures that are attached to a class. "Method" means the same thing as "function" or "procedure", but on a class.

if else is not a function, but it can appear inside a function.

```<code># This part is a function, and *could* be a class method or static method
function hello($name)
{

  # This part is a control flow statement, and can be *inside* a function
  if($name=='Peter')
  {
    #The next line is one statement
    echo 'Hello Pete!";
  } else {
    echo 'Hello $name!";
  }

}
</code>```

These are examples of keywords: if, else, while, for, case, continue, function, return, class, public, private, protected, static, new.

Each programming language has different keywords. What your keywords are, and how they work are different in every language.

Keywords (if, else), operators (==, <, !=), variables ($name), string literals ('Peter'), functions (echo, hello) all work together to make statements. Statements do all most of the work, and are grouped into functions or methods (usually).

I think you should try Code Academy. It teaches basic programming, and it might help you understand the parts of programming statements.

You should also try to find a book that teaches your programming language. Such books should explain the parts of statements too. If one book is not clear, try another one.

Body:
This answer is about languages like C, C++, Java, PHP and Javascript. There are other programming languages that work differently.

if is a keyword, and else is a keyword. When they are used in code, if and else together form a control flow statement.

Class methods, or static methods are always functions or procedures that are attached to a class. "Method" means the same thing as "function" or "procedure", but on a class.

if else is not a function, but it can appear inside a function.

# This part is a function, and *could* be a class method or static method
function hello($name)
{

  # This part is a control flow statement, and can be *inside* a function
  if($name=='Peter')
  {
    #The next line is one statement
    echo 'Hello Pete!";
  } else {
    echo 'Hello $name!";
  }

}

These are examples of keywords: if, else, while, for, case, continue, function, return, class, public, private, protected, static, new.

Each programming language has different keywords. What your keywords are, and how they work are different in every language.

Keywords (if, else), operators (==, <, !=), variables ($name), string literals ('Peter'), functions (echo, hello) all work together to make statements. Statements do all most of the work, and are grouped into functions or methods (usually).

I think you should try Code Academy. It teaches basic programming, and it might help you understand the parts of programming statements.

You should also try to find a book that teaches your programming language. Such books should explain the parts of statements too. If one book is not clear, try another one.


答:
Would depend on a few details about your search options. Our website has rather complex search options (using Apache Solr to search over articles that have a heavy load of facets like categories, technical properties etc.).

I have actually two search controllers, one for customers (basic search functionality) and one in the admin section that handles some more complicated internal queries.

The outward bound controller is named search_controller and has only a show action. Mostly because the text input that triggers the search is available from everywhere on the site, so you can do only a single "search". (I'm not 100% happy with this singular naming here and may change it)

The admin variant is called searches_controller and has an index action and a show action. The index action will display a page with all the search options. This then triggers the show action to display search results.

If there is any doubt, I would more likely go with the plural variation, it's just more simple. index giving the options, show displays the results. (though using new for the options would maybe make sense too)

Since you search over multiple tables a dedicated searches_controller most likely makes sense, though if one of the models is the "main" model, you could as well use this models index action if this isn't already taken. If you would start to add non REST actions, it's a sign that a controller makes sense (not mandatory of course)

The work load to actually search belongs in the models or some library.

Title: Which controller should I put for a search action that touches many different models?

Body:
I currently have the following models and am designing search functionality that searches within these 3 models:
Locations
Users
User_friends

Should I create a search controller or should I put the action in one of the existing locations, users, or user_friends controllers?  If so should it be pluralized - searches_controller or just search_controller?


答:
As the others have already explained, control flow is usually implemented with branching instructions.

But, jumps are not always necessary. In some ISAs there is a so called "conditional execution": instructions will be bypassed if they're marked as conditional and a flag after a previous comparison operation is not set. Jumps can be mispredicted and may thrash pipeline, whereas a short sequence of conditional instructions might be much cheaper.

Another interesting form of low level control flow is a so called "zero-overhead looping", common in many modern DSP processors (e.g., in Hexagon).


答:
One very interesting and cool thing for an assignment is writing an implementation of Conway's Game of Life in 2D. It maps very well to basic array data structures, it's fun and pretty easy to do, but still requires some thinking. It may open up some curiosity and experimentation as well (AI).

Advanced students can write a version in 3D for extra points.


问:
Searching for text within a webpage
I'm currently designing a search algorithm for a document, and just got curious about this while designing the algorithm: how do web browsers search a webpage?

For example, in Google Chrome, you can press the keyboard shortcut Ctrl-F to activate the "Find" bar, which will let you search a particular webpage for text. How does it do that, given that it only has the raw HTML as reference?

答:
When you say that you are designing a search algorithm for a document, could be more specific? Are you doing in within the webpage itself or are you doing this as a server-side operation? Also, are you just trying to find the page/document that matches best or are you searching for a particular element within the page to highlight, much like Firefox and Chrome do?

As @iglvzx mentioned, you should look into DOM. I've setup a very simple example below for implementing a search on a page. The main point I'm trying to show is building up a cache object that is a hash with the DOM element/node as the key and it's searchable text as the value. As for the actual search algorithm, I assume you are building your own but I do have a link to a  project for live-searching in JavaScript that could be of good help.

I'm sure there are plenty of problems with the below code when it comes to actual application, but hopefully this can help point you in the right direction.

// setup a global search-cache
var cache = null;

/**
 * Public: Generate the cache from the existing page. Note, this may need
 *         to be re-run if the DOM (page) changes.
 *
 * Returns nothing; populates a global cache object
 */
function generate_cache() {
    var cache = {};

    $('body').children().each(function () {
        (function process_node(node) {
            var has_children = node.children().length > 0;
            if (has_children) {
                node.children().each(function () { process_node(this); });
            }
            else {
                cache[node] = node.text();
            }
        })(this);
    });
}

/**
 * Public: Search the cache of the page
 *
 * value - The value to search for within the cache
 *
 * Returns the node the text was found in or with the highest score
 * or whatever your search algorithm does.
 */
function search (value) {
    // You're search-code here...
    // I'd recommend that you checkout quicksilver for
    // scoring your results and getting the highst-matching
    // node. You can find the code here:
    // http://ejohn.org/blog/jquery-livesearch/
    // which you'll need to adapt to your situation
}

/*
 * When the document loads, build your cache and bind a keyup event
 * to you search-box.
 */
$(document).ready(function () {
    generate_cache();
    $('#search-box').keyup(function() {
        var node = search($('search-box').val());

        // I assume you'll wan to do something with the node
        // once you've found it so I just made up a function
        // for highlighting the entire node.
        highlight_node(node);
    });
});
```

OwnerDisplayName: Bryan

Title: Searching for text within a webpage

OwnerDisplayName: John


答:
One scenario where I've seen dynamic used effectively was in the implementation of feature toggles.

We had a globally accessible FeatureToggles class which was a dynamic object, therefore in our code we could make certain features of the code dependent on the toggle being enabled eg:

```<code>public void DoSomething()
{
    if (FeatureToggles.SomeFeatureEnabled)
    {
        DoSomeFeature();
    }
}
</code>```

The feature toggles were configured in the application configuration file, and the dynamic FeatureToggles object read the app config at startup. If a feature toggle was enabled in the config, the FeatureToggles class would return true; if a feature toggles was not enabled, or was not yet in the configuration file, the FeatureToggles class would return false. Crucially, this enabled us to start using feature toggles before they had even been configured*, in which case they defaulted to off.

* naturally there was logging output in this case.

Title: C# dynamics and Expando object

Body: Under which application development scenarios C# dynamics and ExpandoObject can be used or when to consider using c# dynamics and ExpandoObject</p>

Body:
One scenario where I've seen dynamic used effectively was in the implementation of feature toggles.

We had a globally accessible FeatureToggles class which was a dynamic object, therefore in our code we could make certain features of the code dependent on the toggle being enabled eg:

public void DoSomething()
{
    if (FeatureToggles.SomeFeatureEnabled)
    {
        DoSomeFeature();
    }
}

The feature toggles were configured in the application configuration file, and the dynamic FeatureToggles object read the app config at startup. If a feature toggle was enabled in the config, the FeatureToggles class would return true; if a feature toggles was not enabled, or was not yet in the configuration file, the FeatureToggles class would return false. Crucially, this enabled us to start using feature toggles before they had even been configured*, in which case they defaulted to off.

* naturally there was logging output in this case.


问:
How to detect the encoding of a file?
On my filesystem (Windows 7) I have some text files (These are SQL script files, if that matters).

When opened with Notepad++, in the "Encoding" menu some of them are reported to have an encoding of "UCS-2 Little Endian" and some of "UTF-8 without BOM".

What is the difference here? They all seem to be perfectly valid scripts. How could I tell what encodings the file have without Notepad++?

答:
You cannot. If you could do that, there would not be so many web sites or text files with “random gibberish” out there. That's why the encoding is usually sent along with the payload as meta data.

In case it's not, all you can do is a “smart guess” but the result is often ambiguous since the same byte sequence might be valid in several encodings.

Title: How to detect the encoding of a file?


答:
Files generally indicate their encoding with a file header. There are many examples here. However, even reading the header you can never be sure what encoding a file is really using.

For example, a file with the first three bytes 0xEF,0xBB,0xBF is probably a UTF-8 encoded file. However, it might be an ISO-8859-1 file which happens to start with the characters ï»¿. Or it might be a different file type entirely.

Notepad++ does its best to guess what encoding a file is using, and most of the time it gets it right. Sometimes it does get it wrong though - that's why that 'Encoding' menu is there, so you can override its best guess.

For the two encodings you mention:

The "UCS-2 Little Endian" files are UTF-16 files (based on what I understand from the info here) so probably start with 0xFF,0xFE as the first 2 bytes. From what I can tell, Notepad++ describes them as "UCS-2" since it doesn't support certain facets of UTF-16.

The "UTF-8 without BOM" files don't have any header bytes. That's what the "without BOM" bit means.

Title: How to detect the encoding of a file?

Body:
On my filesystem (Windows 7) I have some text files (These are SQL script files, if that matters).

When opened with Notepad++, in the "Encoding" menu some of them are reported to have an encoding of "UCS-2 Little Endian" and some of "UTF-8 without BOM".

What is the difference here? They all seem to be perfectly valid scripts. How could I tell what encodings the file have without Notepad++?


问:
Is it a acceptable approach to put try catch wherever null pointer exception occurs?
There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

答: No. If someone passes a null pointer where you did not expect it, then that's a bug. Make them deal with the exception- it's their problem.</p>


答:
You really need some assistance from Herb. He can tell you how to deal with this. Cliffnotes:

```<code>template<typename T> class Monitor {
    T t;
    std::mutex m;
public:
    template<typename F> auto operator()(F&& f) -> decltype(f(t)) {
        lock_guard<mutex> lock(m);
        return f(t);
    }
};
Monitor<Mogrifier> safe;
safe([](Mogrifier& m) {
    m.mutate();
});
</code>```

The second part is that you really shouldn't block, and if you do, you can't do it on a per-method level.

Title: Should I split out synchronization from my class and what's it called?

Body:
When thinking about testability and modular code, I recently thought about whether I should split out the synchronization part of a class from the actual behavior part.

By example:

The app "needs" this:

```<code>class Mogrifier { // Mogrifier accesses are thread safe
private:
  unsigned int m_state;
  mutex m_sync;
public:
  Mogrifier()
  : m_state(0)
  { }

  unsigned int Mutate() {
    lock_guard<mutex> lock(m_sync);
    const unsigned int old = m_state;
    m_state += 42;
    return old;
   }

  :::
};
</code>```

Seems simple enough, except that locking and the actual stuff the class does aren't really related.

So I though about whether it's a good idea to split this up:

```<code>class Mogrifier { // Mogrifier is *not* synchronized
private:
  unsigned int m_state;
public:
  Mogrifier()
  : m_state(0)
  { }

  unsigned int Mutate() {
    const unsigned int old = m_state;
    m_state += 42;
    return old;
   }

  :::
};

class SyncedMogrifer {
private:
  mutex m_sync;
  Mogrifier m_;
public:
  unsigned int Mutate() {
    lock_guard<mutex> lock(m_sync);
    return m_.Mutate();
  }
};
</code>```

Would you do this?

Will it help with unit testing?

I'm awful with Pattern names ... what is it called?

Is there a simple way to "generate" such a wrapper in C++ for an arbitrary calls?

Body:
You really need some assistance from Herb. He can tell you how to deal with this. Cliffnotes:

template<typename T> class Monitor {
    T t;
    std::mutex m;
public:
    template<typename F> auto operator()(F&& f) -> decltype(f(t)) {
        lock_guard<mutex> lock(m);
        return f(t);
    }
};
Monitor<Mogrifier> safe;
safe([](Mogrifier& m) {
    m.mutate();
});

The second part is that you really shouldn't block, and if you do, you can't do it on a per-method level.


答:
I like Lisp because it's an excellent medium for expressing my thoughts. The predicate for my favorite language is "If I could pick anything to express ideas in, what would it be?". Currently it's Lisp* (Scheme to be specific), to the point that I find myself writing out programming notes in it. As IRL, paper and pen notes. Even when I'm thinking about programs I need to implement in PHP or Ruby or Python.

This isn't a trick I taught myself, or something I do for nerd credibility (no one gets to see the inside my notebook anyway); it's just that Lisp is so much more natural for me to think in than any of the alternatives, and any language that resonates with you that deeply is one you treasure.

*Just as a footnote though, Haskell is closing the gap pretty quickly as I learn more of it.

Title: Why is Lisp useful?

Body:
Lisp obviously is an advantage for the AI stuff, but it doesn't appear to me that Lisp is any faster than Java, C#, or even C. I am not a master of Lisp, but I find it incredibly difficult to understand the advantage one would get in writing business software in Lisp.

Yet it is considered as a hacker's language.

Why does Paul Graham advocate Lisp? Why did ITA Software choose Lisp over other high-level languages? What value does it have over these languages?


答:
Using a try-catch block every time will make your code needlessly complicated and less readable. Besides, if your code is thought thoroughly, there usually shouldn't "unpredictable" null pointers. </p>

<p>In most cases a simple check if some variable is null is enough. If necessary, you could log a message if a variable is null. </p>

Title: Is it a acceptable approach to put try catch wherever null pointer exception occurs?

Body:
There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

Body:
Using a try-catch block every time will make your code needlessly complicated and less readable. Besides, if your code is thought thoroughly, there usually shouldn't "unpredictable" null pointers.

In most cases a simple check if some variable is null is enough. If necessary, you could log a message if a variable is null.


答:
Regarding your comment:

I mean instead of showing a Stack trace error how can we make the user more understandable about the Null pointer that happened.

The user neither knows nor cares about what a Null pointer is. If a NullPointerException occured, it's a bug in your code. It should be caught and logged by the global exception handler, then the bug should be fixed and an update should be shipped.

(You do use a global, catch-all exception handler that logs the exception, apologizes to the user, terminates the application and instructs the user how to send the stack trace to you, right? If not, this might be a good time to start.)


答:
It depends on the code block, but yes, in many cases try-catch is a good solution to handle a number of null-pointer related bugs you are not prepared to address individually. You need to fulfill two conditions to make exceptions useful:

Non-locality of handling: Don't use try-except when a simple if would suffice. Use try-except when the error occurs far from the place where it is handled, e.g. deep in the call stack or within a large block of code.

Useful error handling: Do more than the default exception handler. Logically abort an operation with a useful error message. Handle the exception at a point where you can actually make an informed decision over the high-level process. In a MVC GUI application, the Controller is often a good place. Under no circumstances handle the exception close to the generating point, log it and forget about it - that's just useful for your logs.


问:
WAN Connectivity between multiple MS ACCESS DB
I have a client that asked me to develop his Windows Application and use MS Access instead of SQL database. I did and now he asked me that he deployed the Application through several of his offices.

Now he wished to have a "main Server" with all information from the "client applications" for Reporting purposes and also to update information per "client application". I proposed the idea of "EDI" through FTP, also converting the current app to connect thru SQL via WAN, but somehow he said that FTP is not an option and also WAN connection is impossible since the internet on their country is so slow that an mp3 must be downloaded for 20 minutes or so he says.

Is there any other way to communicate with the other DB(MS Access) and capture data or update data as necessary without using FTP EDI exchange?

答:
I suggest start reading this article http://www.kallal.ca/Wan/Wans.html It explains in detail why Access on a WAN is not reliable. It shows also some alternatives, like

using MS SQL server as a backend store instead of access (I guess this will only help if you get those servers into a shared intranet)

create a web-based system (for example, a REST API)

use replication (which typically requires either ftp or a VPN)
EDIT: read this SO post about Access replication, or the MS Access replication FAQ here. Replication of the local MDBs to the central office may be solution in your case.

use a terminal server (which I guess is not a solution for the problem you have described)

use a Share Point server

You could also try to utilize something like DropBox, GoogleDrive or MS Office 365 to replicate the access MDB from the local offices to the central office, but make sure you transfer only consistent copies of the MDB files this way and don't work directly on those files while replication is in progress.

You should clarify the following questions with your client:

which kind of shared network access is available?

how up-to-date must the data in the central office be?

EDIT: SMTP is not secure, but of course you can pack, encrypt and and send the MDB files programmatically by mail, if you have no shared file server available and don't want to use any of the "cloud" services I suggested above. Someone has to press the "send data to central office" button in the local offices, but if that is ok for you, why not.

Of course, this all boils down to "how to transfer files between offices without ftp or a shared file server", which is not an Access question any more (so you might choose a different title for your question).


问:
requirements for software quality for internally developed / shared software?
In environments where software is built internally by one team and then that software is used by other internal teams, how does one decide what the required quality should be for the produced artefacts?  For example:

documentation completeness and accuracy

extensibility/re-usability of artefact (without hacking at source code)

defects

etc

I guess one aspect to consider is the length of time into a project before quality is considered.  It should be more cost effective to ensure quality is built into a product from the start rather than leaving it until later in the project life-cycle.

答:
I worked for a programming team which developed on top of a framework built by yet another internal programming team, so maybe I can share some insights I've learned.

While it's true that both teams are internal, in my experience, that grants you little extra freedom that you'd otherwise have if the objective is to produce code in an efficient manner. General guidelines within a programming team still apply:  never commit broken code, branch significant modifications in order to disturb work being performed by other programmers, etc.

When it comes to committing code that another team will use, like a final product, it must be up to par in terms of testing and functionality.  The difference is that if something is broken, rather than upset a client, you're wasting company time and money (and you're probably upsetting programmers rather than clients).  After a bit of trial and error, we figured out that the best way to handle such things was for the framework to be committed like you'd produce a release.

There would be a trunk source repository, which, rather than being the place where all programmers commit their daily unbroken code to, would be the definitive tested and stable version that other programming teams can draw from.  The "what would have been" trunk turns into a common branch (which we called the release branch) where new features get added and bugs are fixed.  Where you'd normally branch from the trunk, you simply branch from the release branch and merge back into the release branch when you're finished.  Once you've reached a point in which important features/bugs are added to the release branch, make a point that a programmer spends a good couple days to thoroughly test all (not just newly added) functionality.  Once this is done, the stable branch can become the new trunk and a new release branch is created for the next version.

Even with this system in place, there were still many problems, but I can't imagine how many more problems we would have had if the framework worked every other day.

And to end with a little bit of advice, the biggest advantage that you have working with an internal programming team is that you have communication.  Use it.


答:
how does one decide what the required quality should be for the produced artefacts?

I always strive for the best*, but be aware that there is a multitude of non-coding "things" that are potentially going to get in your way.

These can include scope creep, dependencies on other teams/departments, budgets being slashed, personnel being re-assigned, political changes within company, incompetent managers/developers/BAs/PMs.

*where the word "best" is arbitrary in itself.

Title: requirements for software quality for internally developed / shared software?

Body:
In environments where software is built internally by one team and then that software is used by other internal teams, how does one decide what the required quality should be for the produced artefacts?  For example:

documentation completeness and accuracy

extensibility/re-usability of artefact (without hacking at source code)

defects

etc

I guess one aspect to consider is the length of time into a project before quality is considered.  It should be more cost effective to ensure quality is built into a product from the start rather than leaving it until later in the project life-cycle.


答:
One edge case where dynamic is not necessary, but can make your code more DRY and not actually less type-safe is when implementing the visitor pattern.

The classical way to implement this is to have an Accept(Visitor visitor) method on each derived type and you have to implement it with the same visitor.Visit(this) boilerplate.

And this assumes the types in question support the visitor. If not, you need one big if (obj is DerivedType1) … else if (obj is DerivedType2) … else if … and modify it each time new type is added (along with adding the overload of Visit() for the new type).

With dynamic, it's a matter of single line to cast your type to dynamic, which means the correct overload will be chosen:

```<code>public void Visit(BaseType obj)
{
    VisitInternal((dynamic)obj);
}

protected virtual void VisitInternal(DerivedType1 obj)
{
}

protected virtual void VisitInternal(DerivedType2 obj)
{
}

// etc.
</code>```

Title: C# dynamics and Expando object

Body:
One edge case where dynamic is not necessary, but can make your code more DRY and not actually less type-safe is when implementing the visitor pattern.

The classical way to implement this is to have an Accept(Visitor visitor) method on each derived type and you have to implement it with the same visitor.Visit(this) boilerplate.

And this assumes the types in question support the visitor. If not, you need one big if (obj is DerivedType1) … else if (obj is DerivedType2) … else if … and modify it each time new type is added (along with adding the overload of Visit() for the new type).

With dynamic, it's a matter of single line to cast your type to dynamic, which means the correct overload will be chosen:

public void Visit(BaseType obj)
{
    VisitInternal((dynamic)obj);
}

protected virtual void VisitInternal(DerivedType1 obj)
{
}

protected virtual void VisitInternal(DerivedType2 obj)
{
}

// etc.


问:
Literate programming, good/bad design methodology
I have recently found the concept of literate programming. And I found it rather intriguing. Yet I have not been encountered with claims that it is a bad way to structure a program. It seems not covered many places. Not even here could I find any questions regarding this.

My question is not about its flaws or ways of handling documentation. I consider the documentation a side-effect of what it would mean for the flow of literate programming. I know that the design was originally intended for easy documentation as well as the concept of forward programming flow.

The concept of dividing the problem into small sentence based problems seems to be really a brilliant idea. It will thus ease the understanding of the program's flow.

A consequence of the literate design method is also that the number of functions required will be limited to the imagination of the programmer. Instead of defining a function for a certain task, it could be created as a scrap in the literate method. This would yield automatic insertion of the code, instead of a separate function compilation and subsequent requirement of an inter-procedural compilation optimization step to obtain the equivalent speed. In fact Donald E. Knuth first attempt showed an inferior execution time, due to this very fact. I know that compilers can be made to a lot of this, however this is not my concern.

So I would like to get feedback of why one should consider this a bad/good design methodology?

答:
I think this is mistake to think that LP is some kind of DSL. Because LP is -- journal (with diagrams, schemes, pseudo-code fragments, i.e. chunks) of developed program, it's architecture and so on... It's absolutely analogue of paper notebook - many of developers use they but after finishing of program - drop out your' notebooks, papers...

Long time ago each physicist, astonomer, chemist/alchemist, mathematician has own notebooks, manuscripts with many schemes, needful information, tables, and without them you can understand or repeat their successful experience, his results. And always between such peoples exists manuscreepts/notebooks hunting.

Today many programmers writes code, and sometimes they adds comments! Byt program is not only code - it's thoughts, ideas, imagination, concepts and when new developer inherits alien code - he brokes all ideas and concepts often, makes different "loopholes" and "backdoors", I hope you understand me :)

So, main requirement for LP (as tool!) is too allow all of these with simple, light, readable syntax. I tried many LP tools, but today i'm developing own - NanoLP (http://code.google.com/p/nano-lp/) which is aims to acomplish this demand.


答:
Internally on x86/64 architecture if/else/then is generated with internal CMP mnemonic.

It compares the results and sets the EFLAGS register with appropriate flags(zero, overflow, etc.).

Internally if the arguments are equal their minus product is zero. For example
if (a == b) where a = 10, b = 10. Processor does 10-10=0. Once the result is zero - ZF(Zero Flag) is set.

So:

```<code>cmp a, b
jz equal
jnz notEqual
</code>```

JZ - Jump if Zero is equal to JE as well as JNZ(Not Zero) is equal to JNE(Not Equal). They are equal and JE and JNE exist just because of readability.

JL stands for - Jump if Less

JG stands for - Jump if Greater

Body:
Internally on x86/64 architecture if/else/then is generated with internal CMP mnemonic.

It compares the results and sets the EFLAGS register with appropriate flags(zero, overflow, etc.).

Internally if the arguments are equal their minus product is zero. For example
if (a == b) where a = 10, b = 10. Processor does 10-10=0. Once the result is zero - ZF(Zero Flag) is set.

So:

cmp a, b
jz equal
jnz notEqual

JZ - Jump if Zero is equal to JE as well as JNZ(Not Zero) is equal to JNE(Not Equal). They are equal and JE and JNE exist just because of readability.

JL stands for - Jump if Less

JG stands for - Jump if Greater


问:
Do I include third party classes in my UML class diagrams
I'm developing a system which involves 2 Android applications and a Java web application. For my UML class diagrams I have not included third party classes I use e.g. observer type interfaces. Should I include them? If so how can I differentiate between my entities (classes, interfaces, enums etc) and their entities? Thank you.</p>

答:
For my UML class diagrams I have not included third party classes I use e.g. observer type interfaces. Should I include them?

If they are important for understanding your system, yes.

If so how can I differentiate between my entities (classes, interfaces, enums etc) and their entities?

Perhaps a package diagram to clearly show what belongs where. In other diagrams, you could use color to show the difference.


问:
Features that encourage use of project management software
I'm a student and I work as an undergrad in an IT department. They are very effective programmers, but as far as documenting what they do and tracking what time is spent on specific tasks - not so much.

I was put in charge of setting up project management software. So far, I've created a satisfactory solution with Trac. But still, programmers use it because "the boss says so" and do so grudgingly.

No one likes having to go to a separate webpage, logging what they did, checking boxes, and what not - so my question is this:

As a programmer, what incentives or features in project management software would encourage you (or least make it more bearable) to use it?

答:
Asking about features

Asking about features is the wrong question, because most of the features mentioned don't help its users reach the end goals.

Whose tool is it?

There are two major confusions:

Individual team members confusing project management tool with personal productivity tool.

Personal productivity tool is a personal choice, i.e. each coworker may have different choices. It's what works best for an individual.

Personal productivity tool can't help reach the end-goals below. To reach the end-goals, the whole team must agree on some shared Project management tools that everyone will use.

Good project management tools should improve personal productivity, but that's a side-effect, not an end-goal. On the other hand, bad project management tools that impede personal productivity will impede its own adoption.

Managers seeing project management tool as their tool to manage people.

What are the end goals

Visibility of work - allowing everyone to know what each coworker is going to work on. If two coworkers' work is going to conflict with each other, or if one has a good suggestion to offer to another, then having this visibility will encourage the dialogue to happen.

Status of project - exposing impediments; warning about impossible-to-meet deadlines or features that are too hard to implement; to indicate a project's readiness

Change control - making sure that changes to the production system, or to the source code, or to the hardware are well-documented, and that potential conflicts are prevented from happening.

Knowledge management - make note-sharing, record-keeping and searching easy. Anyone may share anything learned from the work - it could be some Heisenbugs, some online tutorials, or someone's hunch that a few issue tickets have a common underlying cause. Casual observations must be gathered so that patterns can be mined out.

These are just a few examples of end goals. None of these are "software features" per se. They are features (characteristics) of productive teams.

But some people say the best project management tool is a whiteboard

Judging from the end-goals, I cannot refute that.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: that you can speed up a late project, simply by throwing more people at it.</p>


问:
Which license for an open source project which may be, but is not intended to be, used as a bot in some apps?
I'm wondering if there is some license which I could put on my website on which I could publish an open-source application that potentially could be used for purposes of cheating in one game for smartphones.

Now, I have to stress that the goal of the application is in no way cheating, so with this license I want to eliminate the possibility that the authors of the smartphone game (in which my bot could be used) could sue me if someone else starts using the application to get better at their game.

I may be too paranoid, but with all the weird laws you just never know.

I did a little research and came up with Creative Commons Attribution 3.0 (CC BY 3.0), but was wondering whether any of you guys were ever in a similar situation, and what you did in that case?

By the way, I did read and consider the moral implications of the possible app appearing on my site, so now I just need some license as stated in the question.

答:
I would think that you would have a hard time enforcing such a license. There will be some ambiguity in the license, and only a court would be able to decide whether someone violates it. Would I be correct to say that you don't have a financial interest in enforcing your license? If so I doubt that you'd be willing to pay the legal fees.

Treat your library like any other piece of technology: it is possible to use it for both good and nefarious purposes. Choose an open-source license that suits you and perhaps put an additional disclaimer or statement along-side it, expressing your wishes.

It may be more effective to modify your library so it less useful for cheating, but still functional for it's intended purpose.


问:
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.

答:
You wouldn't. Variables are at the core of imperative programming, and if you try to program imperatively without using variables, you are just causing everyone a pain in the ass.
In different programming paradigms, the styles are different, and different concepts form your basis. A variable in Java, when used well with a small scope, is no evil. Asking for a Java program without variables is like asking for a Haskell program without functions, so you don't ask for it, and you don't let yourself be fooled into viewing imperative programming as inferior because it uses variables.

So, the Java way would be:

```<code>for (int i = 1; i <= 25; ++i) {
    System.out.println(i*i);
}
</code>```

and don't let yourself be fooled to write it in any more complex way due to a hatred of variables.

Body:
You wouldn't. Variables are at the core of imperative programming, and if you try to program imperatively without using variables, you are just causing everyone a pain in the ass.
In different programming paradigms, the styles are different, and different concepts form your basis. A variable in Java, when used well with a small scope, is no evil. Asking for a Java program without variables is like asking for a Haskell program without functions, so you don't ask for it, and you don't let yourself be fooled into viewing imperative programming as inferior because it uses variables.

So, the Java way would be:

for (int i = 1; i <= 25; ++i) {
    System.out.println(i*i);
}

and don't let yourself be fooled to write it in any more complex way due to a hatred of variables.


答:
The real answer is that it depends on the domain of the application.

Is it more important that it functions exactly to spec (Financial Hedging calculator giving wrong results) or is it more important that it stays up no matter what (e-commerce site with a fudged up header)?

In some business a slightly-wrong result is worse than no result at all. In those cases you want to fail fast loud and explicit when something unexpected and strange happens so that people who inspect the logs can do their work and the root cause can be found and fixed.

Meanwhile if that is not your situation, and the goal is maximum uptime then thiton's answer is the way to go.


答:
In your functional example we don't see how the squares-of and take functions are implemented.  I'm not a Java expert, but I'm pretty sure we could write those functions to enable a statement like this...

```<code>squares_of(integers).take(25);
</code>```

which is not so very different.

Title: How to write useful Java programs without using mutable variables

Body:
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.

Body:
In your functional example we don't see how the squares-of and take functions are implemented.  I'm not a Java expert, but I'm pretty sure we could write those functions to enable a statement like this...

squares_of(integers).take(25);

which is not so very different.


答: Link it to source control, and require a task ID on commit. The time spent on the task is assumed to be the time between commits. If a dev stops working on a task to start another, they should commit to a work in progress branch.</p>

Title: Features that encourage use of project management software

Body:
I'm a student and I work as an undergrad in an IT department. They are very effective programmers, but as far as documenting what they do and tracking what time is spent on specific tasks - not so much.

I was put in charge of setting up project management software. So far, I've created a satisfactory solution with Trac. But still, programmers use it because "the boss says so" and do so grudgingly.

No one likes having to go to a separate webpage, logging what they did, checking boxes, and what not - so my question is this:

As a programmer, what incentives or features in project management software would encourage you (or least make it more bearable) to use it?