问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
```<code>if (cond)
   //do something
else (cond)
   //do something
else (cond)
   //do something
first
   //do something
then
   //do something
else (cond)
   //do something
else
   //do something
end
</code>```

FIRST and THEN blocks runs if any of 3 conditionals are evaluated to true. FIRST block runs before the conditional block and THEN runs after the conditional block has ran.

ELSE conditional or final write following FIRST and THEN statement are independent from these blocks.

It can read as :

```<code>if (cond)
   first()
   //do something
   then()
else (cond)
   first()
   //do something
   then()
else (cond)
   first()
   //do something
   then()
else (cond)
   //do something
else
   //do something
end

function first()
   //do something
return
function then()
   //do something
return
</code>```

These functions are just a form to read. They wouldn't create scope. It's more like a gosub/return from Basic.

Usefulness and readability as matter of discussion.

Body:
if (cond)
   //do something
else (cond)
   //do something
else (cond)
   //do something
first
   //do something
then
   //do something
else (cond)
   //do something
else
   //do something
end

FIRST and THEN blocks runs if any of 3 conditionals are evaluated to true. FIRST block runs before the conditional block and THEN runs after the conditional block has ran.

ELSE conditional or final write following FIRST and THEN statement are independent from these blocks.

It can read as :

if (cond)
   first()
   //do something
   then()
else (cond)
   first()
   //do something
   then()
else (cond)
   first()
   //do something
   then()
else (cond)
   //do something
else
   //do something
end

function first()
   //do something
return
function then()
   //do something
return

These functions are just a form to read. They wouldn't create scope. It's more like a gosub/return from Basic.

Usefulness and readability as matter of discussion.


问:
Disadvantages of vertical user stories
The agile approach is to structure the work into vertical user stories and deliver a focused but fully functioning piece of the application from end-to-end. Because this is the new approach to building software I read a lot of literature about why this is better than horizontal stories but I do not find much about the disadvantages to this approach.

I already drank the agile cool-aid and I too agree that vertically slicing the cake has much advantages over horizontal slicing. Here is a short list of disadvantages that I could come up with:

A developer might initially be slower at implementing a feature because s/he must understand all the technologies required to develop the story (UI + service layer + data access + networking, etc...)

Overall architecture design (crating the backbone of the application) does not really fit this mantra (however some might argue that it is part of a user story to develop/change the overall architecture)

What are some more drawbacks of vertically slicing user stories?

Note: The reason I am asking this question now is because I am going to attempt to convince a team to start writing stories the 'vertical way' and I want to be able to bring up the possible trade-offs ahead of time so they won't consider the approach a failure when they are faced with the drawbacks.

答:
The big drawback I have found is that it makes it hard for a team to build the application following a unified architectural approach.

In the early stages of the project everyone will write their layers in isolation.  The stories (and layers involved) will work, but when looking back at the delivered product at the sprint-end it'll be easy to see the slight differences between each developer's architectural ideas.

This kind of thing is inevitable, but not a blocker.  I've tried to battle this in two ways:

Have lengthy design discussions with the team before implementing each story

This gets tiring quickly.  It's often too early for anyone to make an informed decision and then you just end up arguing over stuff that will definitely have to change anyway.

Go ahead and develop in relative isolation, keeping in mind that you're building up technical debt.

The key here is to log the technical (architectural) debt as an issue.  This is something that will need to be paid back.

After a few sprints it'll be easier to decide on a coherent and unified architecture.  This is when you should request a hardening sprint to pay back some of your technical debt (refactor the existing code).  Alternatively, you can pay it back piecemeal over the next iterations of the project.

The only other problem I can think of other than that is that there's usually a lot of boilerplate code to add at the beginning of a project.  Writing vertical slice stories means the team's velocity on the first few stories will be artificially low due to this prerequisite boilerplate... but as long as everyone is aware that this should only affect the first couple of sprints then everything is fine.

ContentLicense: CC BY-SA 3.0

Title: Disadvantages of vertical user stories


问:
Does it hurt to learn bits of many programming languages?
I started my programming career with BASIC, during 9th grade. I learned a bit of BASIC by writing simple programs to add, subtract and to print. Then I went to the university and took Computer Information and Systems Engineering. In the first year I was taught C, and I have good command over it.

Next I learned C++ in the second year. It just taught me some knowledge of OOP. Now I am doing PHP (along with HTML). I have not mastered C++, BASIC or PHP. I am now planning to move to mobile development. But I feel that I have not covered everything in the languages I learned.

Does it really matter?

答:
Well,
The way I see it is you dont have to learn each and every bit of language. But try learning very basic features which will be required in other languages too.
For example, OOPS concepts are required in all the languages be it Java, PHP, or any other language.
Memory allocation concepts are quite similar in many programming languages. These kind of topics you should never miss out on.

Each and every language have grammar and rules, same applies for programming languages; Dennis Ritchie himself accepted that fact. So one should learn the grammar of that language.

But the way I see it is that you got to learn the non common factors between two programming languages. They will let you identify what which language stands for what.
C++ is all basic OOP(Object Oriented Programming), so once you learn the OOP concepts, you learn the grammar which you will see in PHP and Java too.

My learning flow was :

Visual Basic 5 (partial) -> HTML 2.0 (partial) -> C (partial) -> CPP (partial) -> Java (partial)

and then I learned C Language again followed by C++ followed by JAVA (complete this time) then I moved to android as I was familiar with Java and XML (partial) and learned it in mean time. First attempt taught me less but in second attempt be sure to learn everything which will help you next time.


问:
What to do when your company doesn't encrypt passwords
Background

I'm been contracted to help a company maintain their server. I work on some minor PHP projects but also look over performance issues and recently, scan logs for hackers.

These guys have been running their server for some time and have what I would call a legacy application on its last legs. It uses magic quotes, global variables (which allows $id to be overwritten by $_GET['id']), use .htaccess as their only security in some instances, you name it. A security and programming nightmare.

We have been hacked in the past, mostly with SQL injections, which would run SLEEP(99999999) commands and act as a DOS-attack. Luckily they didn't run "little bobby tables",

XKCD: http://xkcd.com/327/

So I re-wrote their vulnerable SQL statements from mysql_query() (not mysqli) to PDO transactions. I'm also analyzing the queries for SLEEP and UNION, which we don't use but the injections have. So far, so good.

Latest Issue

Recently we've been told records are changing in the DB for users, such as their e-mail addresses to ones presumably made by spammers.

I noticed their columns didn't have a last_modified column, so we weren't able to even know when they were being changed, let alone by who. I added that column, but that's barely a first step.

When I was looking in to this table, I noticed the passwords weren't salted nor even hashed, just saved as plaintext.

Client Communication

How can I approach them about the entire situation, as a contractor, without flailing my arms like a madman? Any advice? I was thinking a calm approach of,

```
    ISSUE #1
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix

    ISSUE #2
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix
        ```

答:
Surely if changing customer's email address is already happening, and that is considered a problem - then the ability to change passwords is also a problem.

Now, if you've secured the DB sufficiently to prevent this from occurring in the future, then the chance that anyone can edit the user's password is similarly fixed and you only have to consider whether someone can read the password now.

Of course if they can, or if (in the unlikely event) that you haven't totally secured the DB then surely encrypting the passwords should be done - how to do it? Just put it in the same context as the "having email addresses updated" problem. Whether this requires the application to change, and whether that is a "too-difficult" problem is another matter that needs to be raised with them. Look at the code and see how much the cost of changing it will be before taking the suggested fix to them.

OwnerDisplayName: bafromca


答:
I agree with brian, FrustratedWithFormsDesign and SRKX, but I'd like to add that during university this, broadening your knowledge with multiple programming languages and paradigms, is the desirable way to become a good professional.

It's really improbable that you are coming out of college as a formed programmer. Programming is a hard craft and you will need the years in the industry working alongside good programmers, attending good training programs and community meetings, and mostly, you will have to face the craft problems and fail a lot, until you learn your way to master it.

Learning multiple paradigms, multiple languages, solving the multiple problems of our area, will give you a good supporting base to learn the craft on your own, daily while acting as a professional in the industry.

You may attend a Compilers class, but you won't get out as a language designer, creator or even as a compiler developer. You'll get the steps, the processes, and the problems and the basic solutions, and that will give you the edge to adapt this knowledge to a broad range of problems.

Title: Does it hurt to learn bits of many programming languages?

Body:
I started my programming career with BASIC, during 9th grade. I learned a bit of BASIC by writing simple programs to add, subtract and to print. Then I went to the university and took Computer Information and Systems Engineering. In the first year I was taught C, and I have good command over it.

Next I learned C++ in the second year. It just taught me some knowledge of OOP. Now I am doing PHP (along with HTML). I have not mastered C++, BASIC or PHP. I am now planning to move to mobile development. But I feel that I have not covered everything in the languages I learned.

Does it really matter?


问:
Is it ever justifiable to write code without tests when doing TDD?
Is it ever justifiable to write production-code without also writing tests for it when doing Test Driven Development?</p>

答:
I assume that by tests you mean 'unit tests', don't you?

TDD has its limitation, in particular you can't write unit tests for the parts of the system that depend on external components that you can't mock. Of course you can write tests but it would be different kind of tests with different level of granularity.


问:
How to deal with bad versioned software as SCM
I have been asked to be the SCM (Software Configuration Manager) in my company. I've read online documentation to learn what SCM is, what SCM does, etc.

Currently, the company works with a version control system (Bazaar), so the software is versioned correctly, but there are old programs that are not well versioned (some of them not versioned at all), some of them are in CVS, the old version control system used at first, but they are not updated.

I'm asking for your help, based on experience more than theoretical information, to know how to deal with this, how to be a good SCM even with all these issues.

答:
You have a big task in front of you, and the details behind all of this could fill books.  Broadly speaking, here are the things you need to consider.

Decide on a versioning scheme

Have a look at the Wikipedia article on versioning to identify what versioning scheme you want to use.

Version (or freeze) everything

Apply a version (and version control) on everything within your realm otherwise you won't be able to get a handle on what is in and what needs to be in the system.

Build a dependency matrix

Next up is building a dependency matrix that shows what applications rely upon what versions of what components.  In a large application environment this will get messy due to the number of components to cover as well as the high number of individual or one-off components you'll find.

Build a deployment matrix

Following that, you need to get a handle on what is actually out "in the wild" and deployed across your enterprise.  Challenges here will include tracking applications that haven't been versioned as well as the multitude of versions of an app that have been deployed.

Establish a governance model

Once you have quantified the problem, you need to get technical and management buy-in so that everyone agrees there is a problem and that changes must be made in order to resolve the problem.  Decide how future versions will be identified and how dependent applications will be notified of updates.  Don't forget to include the Test / QA organization at this stage!

Migrate all existing deployments to builds that have a version number

Remember all those unversioned and down-level applications that made your matrices a complete mess?  Time to start getting rid of them so you can simplify what you have to manage and the resulting governance overhead.

Reduce the dependency and deployment matrices dimensions

Remember all those one-off dependency components?  Now it's time to merge and eliminate those for the same reasons that you migrated everyone to current levels.  Reducing the scope of what you have to manage is critical to establishing a successful program.

(Optional) Reduce the number of source code repositories

There are bonus points at this stage if you can get the development teams to converge onto one code repository.  This will make the system administrators happy as there is less to maintain, and it should make the developers happy as they will be able to find the odd-ball dependent components more easily.


答:
Short answer: No.

Long answer:
So much of a programmer or software engineer or designer's job is independent of a specific language but very dependent on a certain methodology. For example, Object Oriented Programming is very much about where things exist in memory and in runtime, how accessible they are, and how available they are for later use (inheritance and encapsulation). Implementations differ, such as Java having a top-level inherited class Object whether you like it or not and C++ not having any that you don't specify.

Many languages share features (and many diverge). Syntax differs, of course, and it's trickier when you compare entirely different paradigms like imperative versus functional. But String processing is largely the same wherever you go, once you get little questions of syntax, index, and mutability out of the way. Any language with static typing generally has some method of casting and coercion, but how and when you can do it are up to the language designer.

The language is the tool. You're just putting more tools in your belt. But the tool is only as good as the craftsman who wields it.

Now, how many you learn is a personal choice. I would never learn a language for the sake of learning a new one.  Any choice to learn a new language is prompted by either a course requirement (had to pick up js, php, and R for a single class last year), an existing project requirement (if 90% of the work is done in perl 6 before you get hired, so is the remaining 10% after) or an application-specific benefit (R over say Java combined with some sugary library for statistical analysis).

That said, you do want to learn what is out there and available. My college taught a course on this subject, Programming Language Concepts. It was a broad overview course, not a rigorous mathematics or a coding related one, covering the basics of what might be considered practical rather than theoretical computer science. It was a great course and I wish it was something offered in the 1st-2nd year rather than the 3rd-4th. The text was Concepts of Programming Languages. Not saying you have to go out and read this book, but that'd certainly broaden your horizons.


问:
Jump into Android or learn Java basics first?
I am quite proficient in C and know some C++, but never touched Java. Recently I got an idea for an app which I think has potential, and I want to develop it.

I am planning to go Android first, cause it doesn't require a mac/iPhone.

So my question is: can I go straight to learning Android development, picking up the Java syntax as I go along and need it (after all I don't think it's much different from C/C++), or should I take a couple of weeks to learn the basics of Java first and then start with Android development?

答:
I decided to jump straight to Android and to learn Java as I go. Start is usually easy - you can get Android Developer Tools from the Android developers site, where you will also find some tutorials to help you make the first steps.

However, without proper Java knowledge, Android development soon becomes overwhelming (at least it did for me). Luckily, there are tutorials for those, who want to learn Java solely for Android development. You can find them here (they are designed for people who already know another language like C++/VisualBasic/etc.).

One way to check if you have enough knowledge to develop in Android is to sign up for an Android MOOC (like this one) and check out the assignments. The logic behind this approach is: Since Android development is what you really aim at, you can give it a go immediately. This way will help you realise what you can do and what you still need to learn. Plus you can always take some time out to brush up your Java skills.

Good luck picking the most effective for you way!


问:
How do you encode Algebraic Data Types in a C#- or Java-like language?
There are some problems which are easily solved by Algebraic Data Types, for example a List type can be very succinctly expressed as:

```<code>data ConsList a = Empty | ConsCell a (ConsList a)

consmap f Empty          = Empty
consmap f (ConsCell a b) = ConsCell (f a) (consmap f b)

l = ConsCell 1 (ConsCell 2 (ConsCell 3 Empty))
consmap (+1) l
</code>```

This particular example is in Haskell, but it would be similar in other languages with native support for Algebraic Data Types.

It turns out that there is an obvious mapping to OO-style subtyping: the datatype becomes an abstract base class and every data constructor becomes a concrete subclass. Here's an example in Scala:

```<code>sealed abstract class ConsList[+T] {
  def map[U](f: T => U): ConsList[U]
}

object Empty extends ConsList[Nothing] {
  override def map[U](f: Nothing => U) = this
}

final class ConsCell[T](first: T, rest: ConsList[T]) extends ConsList[T] {
  override def map[U](f: T => U) = new ConsCell(f(first), rest.map(f))
}

val l = new ConsCell(1, new ConsCell(2, new ConsCell(3, Empty)))
l.map(1+)
</code>```

The only thing needed beyond naive subclassing is a way to seal classes, i.e. a way to make it impossible to add subclasses to a hierarchy.

How would you approach this problem in a language like C# or Java? The two stumbling blocks I found when trying to use Algebraic Data Types in C# were:

I couldn't figure out what the bottom type is called in C# (i.e. I couldn't figure out what to put into class Empty : ConsList< ??? >)

I couldn't figure out a way to seal ConsList so that no subclasses can be added to the hierarchy

What would be the most idiomatic way to implement Algebraic Data Types in C# and/or Java? Or, if it isn't possible, what would be the idiomatic replacement?

答:
If you abuse C# named parameters (introduced in C# 4.0), you can make algebraic data types that are easy to match on:

```<code>Either<string, string> e = MonthName(2);

// Match with no return value.
e.Match
(
    Left: err => { Console.WriteLine("Could not convert month: {0}", err); },
    Right: name => { Console.WriteLine("The month is {0}", name); }
);

// Match with a return value.
string monthName =
    e.Match
    (
        Left: err => null,
        Right: name => name
    );
Console.WriteLine("monthName: {0}", monthName);
</code>```

Here is the implementation of the Either class:

```<code>public abstract class Either<L, R>
{
    // Subclass implementation calls the appropriate continuation.
    public abstract T Match<T>(Func<L, T> Left, Func<R, T> Right);

    // Convenience wrapper for when the caller doesn't want to return a value
    // from the match expression.
    public void Match(Action<L> Left, Action<R> Right)
    {
        this.Match<int>(
            Left: x => { Left(x); return 0; },
            Right: x => { Right(x); return 0; }
        );
    }
}

public class Left<L, R> : Either<L, R>
{
    L Value {get; set;}

    public Left(L Value)
    {
        this.Value = Value;
    }

    public override T Match<T>(Func<L, T> Left, Func<R, T> Right)
    {
        return Left(Value);
    }
}

public class Right<L, R> : Either<L, R>
{
    R Value { get; set; }

    public Right(R Value)
    {
        this.Value = Value;
    }

    public override T Match<T>(Func<L, T> Left, Func<R, T> Right)
    {
        return Right(Value);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you abuse C# named parameters (introduced in C# 4.0), you can make algebraic data types that are easy to match on:

Either<string, string> e = MonthName(2);

// Match with no return value.
e.Match
(
    Left: err => { Console.WriteLine("Could not convert month: {0}", err); },
    Right: name => { Console.WriteLine("The month is {0}", name); }
);

// Match with a return value.
string monthName =
    e.Match
    (
        Left: err => null,
        Right: name => name
    );
Console.WriteLine("monthName: {0}", monthName);

Here is the implementation of the Either class:

public abstract class Either<L, R>
{
    // Subclass implementation calls the appropriate continuation.
    public abstract T Match<T>(Func<L, T> Left, Func<R, T> Right);

    // Convenience wrapper for when the caller doesn't want to return a value
    // from the match expression.
    public void Match(Action<L> Left, Action<R> Right)
    {
        this.Match<int>(
            Left: x => { Left(x); return 0; },
            Right: x => { Right(x); return 0; }
        );
    }
}

public class Left<L, R> : Either<L, R>
{
    L Value {get; set;}

    public Left(L Value)
    {
        this.Value = Value;
    }

    public override T Match<T>(Func<L, T> Left, Func<R, T> Right)
    {
        return Left(Value);
    }
}

public class Right<L, R> : Either<L, R>
{
    R Value { get; set; }

    public Right(R Value)
    {
        this.Value = Value;
    }

    public override T Match<T>(Func<L, T> Left, Func<R, T> Right)
    {
        return Right(Value);
    }
}


问:
Does this justify goto statements?
I came across this question a second ago, and I'm pulling some of the material off of there: Is there a name for the 'break n' construct?

This appears to be a needlessly complex way for people to have to instruct the program to break out of a double-nested for loop:

```<code>for (i = 0; i < 10; i++) {
    bool broken = false;
    for (j = 10; j > 0; j--) {
        if (j == i) {
            broken = true;
            break;
        }
    }
    if (broken)
        break;
}
</code>```

I know textbooks like to say goto statements are the devil, and I'm not fond of them at all myself, but does this justify an exception to the rule?

I'm looking for answers that deal with n-nested for loops.

NOTE: Whether you answer yes, no, or somewhere in between, completely close-minded answers are not welcome.  Especially if the answer is no, then provide a good, legitimate reason why (which is not too far from Stack Exchange regulations anyway).

答:
The short answer is "it depends". I advocate to choose regarding legibility and understandability  of your code. The goto way might be more legible than tweaking the condition, or vice versa. You might also take into account least surprise principle, guideline used in the shop/project and consistency of the code base. For instance, goto to leave switch or for error handling is a common practice in the Linux kernel code base. Also note that some programmers might have problems reading your code (either raised with the "goto is evil" mantra, or just not learned because their teacher think so) and a few of them might even "judge you".

Generally speaking, a goto going further in the same function is often acceptable, especially if the jump is not too long. Your use case of leaving a nested loop is one of the known example of "not so evil" goto.

Title: Does this justify goto statements?


问:
Is Python suitable for a statistical modeling application looking over thousands of past events?
I'm currently working on a project with a partner where we analyze large datasets of past sporting events. There are approximately 30,000 events per year and we have historical data for five years. Thus, we're looking at analyzing 150,000 events.

I wrote our first version in Python with a heavy reliance on Pandas (great tool, by the way). However, each time I add a "factor" or calculation to the process it slows down by quite a bit. Simply put, it can read all the various data files and data queries we need at a rate of 25-events-per-second.

The problem is once I start working with the data, it drops fast. If I add a simple calculation, it drops to 24... and each calculation after that it drops again.

With just 10-12 "factors" calculated from the data (we're not talking complex loops or anything crazy), it's now down to 6-events-per-second. ... and we're barely scratching the surface. At this rate, it'll take this thing days to work through all 150k events!

I've optimized our data queries, flat file reads etc. Those really aren't the issue. I can live with doing 15-20 events per second. However, I can't live with such drastic slowdowns each time a new factor calculation is added.

I've read a lot where Python as an interpreted language is slow etc., but my question to the experts out there - what language should this project be done in?

EXAMPLE...

One of the key "DataFrames" I am using through Pandas is fairly large. 350 rows x 70 columns, as an example. Even when trying to simply multiply one column's value by another...

```<code> data['value'] = data['col1'] * data['col2']
</code>```

...I see what I could consider significant drop in performance. It's very puzzling, and very frustrating. I understand this is a large set of data, but I can't believe this is anything so crazy that Python would be slowing to a crawl.

If I just read the data files and do no calculations on them at all, it reads 67 events in 2.807 seconds. If I add one simple calculation where I execute code like the example above, it slows to 2.877 seconds. Based on our research, we're needed to add upwards of 100 calculations on the data.... so 7 seconds worth of slowdown? Seems too hard to believe.

答:
You should use the language you are most comfortable with and that allows you to manipulate the data in the manner you'd like.  Python has a number of scientific libraries that allow you to do just that.

Regarding performance issues - you won't know until you get there.  And for as small of a data set as you're talking, you can always throw more hardware at it.  And yes, 150k events is small.

You should also look into static analysis / performance analysis tools to identify what you could optimize within your code.  If you're new to python then you're likely making mistakes (don't feel bad, we've all been there).  So there's likely plenty of room for optimization.  Switching to another language won't resolve those issues.  In other words, don't blame the tool until you're sure you have removed any operator error.


问:
Why develop free, open source programs?
Why would someone use his own time to develop an open-source project for free and without compensation?</p>

答:
This is a hobby for some people; believe it or not.

Gillette will be happy to give you a free razor and sell you the blades.

Some people make money in other ways and want to give back to the community. I'm sure Linus Torvalds has made plenty of money 'off' of Linux without actually selling the code and probably turns money away.

Not all open source software was intended or designed for any user to just download, install and use, so you may end up spending more of your time depending on skill level and most people value their time.

Title: Why develop free, open source programs?

ContentLicense: CC BY-SA 2.5


答:
I don't know of any long term disadvantages. In the short term, and for a team new to this kind of development, the main disadvantage is that it takes some getting used to and some learning.

The most efficient way to work vertically is to have full-stack developers: in this way a story can be typically executed by one person (or more than one but without pipelining tasks). Clearly this requires that the developers work vertically across the stack (from html to database in the case of a web application).

If your team is not used to working on vertical stories, then they are very likely to be doing the opposite: each person will have knowledge of one layer/tier of the application only. When you introduce vertical stories, you can expect the team to split them into tasks corresponding to layers and then distributing the tasks to different people. This will be very inefficient.

The best approach I can give regarding this is to tolerate this pipelining initially while making it clear that the long term goal is completely different. Have team members across layers pair program so to build up trust and eventually enable people to be completely independent.

I don't agree with the other answer that this approach brings technical debt. It can, but so can any other approach.

Title: Disadvantages of vertical user stories

Body:
The agile approach is to structure the work into vertical user stories and deliver a focused but fully functioning piece of the application from end-to-end. Because this is the new approach to building software I read a lot of literature about why this is better than horizontal stories but I do not find much about the disadvantages to this approach.

I already drank the agile cool-aid and I too agree that vertically slicing the cake has much advantages over horizontal slicing. Here is a short list of disadvantages that I could come up with:

A developer might initially be slower at implementing a feature because s/he must understand all the technologies required to develop the story (UI + service layer + data access + networking, etc...)

Overall architecture design (crating the backbone of the application) does not really fit this mantra (however some might argue that it is part of a user story to develop/change the overall architecture)

What are some more drawbacks of vertically slicing user stories?

Note: The reason I am asking this question now is because I am going to attempt to convince a team to start writing stories the 'vertical way' and I want to be able to bring up the possible trade-offs ahead of time so they won't consider the approach a failure when they are faced with the drawbacks.


答:
Why does everything have to be about money? How do you think wikipedia works? Nobody gets paid to put content on the Wikipedia, yet it is arguable the best encyclopaedia around.

edit:

Let's talk money.

Open source projects, as any projects, are written out of neccessity. You have a problem X and you write library Y or application Z to solve it, because

There are not tools, that solve it or

They are not good enough or

They are not worth the money (writing your own tool probably "costs" more, but in the end you have exactly what you want and you can modify it as you want, so the cost amortized quickly).

So now you spent a few evenings and weekends (and/or paid time) writing the next hot thing until you reach a point, where the baby starts walking. You now have to chose between:

Commercial distribution: this involves marketing, legal stuff, customer support, doing all the fixes yourself, getting tons of incredibly stupid feature requests and less than useless feedback. In the end you get what's left of the money once all the parasites get their piece of the cake. And probably noone will like your product because it costs way too much.

Open source distribution: this involves ... uhm ... pushing the code to a public repository and making an announcement or two on relevant mailing lists. You will get acknowledgement or even some fame. You will get a user base, that provides constructive feedback, helpful bugreports and possibly even patches. You get some donations or get invited to some conferences or get paid to implement features a or b. And you produced a lot of value, albeit nobody paid for anything. And the next time you or your company needs something, chances are good, you'll get it and you'll get it for free.

Open source works, because it is a community. Because it is mutual. You do not get money by writing open source code. You get money by consuming open source code. So why do you write open source code? To give something back.

Title: Why develop free, open source programs?

Body: Why would someone use his own time to develop an open-source project for free and without compensation?</p>


问:
Good idea to put bug numbers in a comment in the beginning of the source file?
Is it a good practice to put bug numbers in the file itself inside a header comment?

The comments would look something like this:

```<code> MODIFIED    (MM/DD/YY)
 abc 01/21/14 - Bug 17452317 - npe in drill across in dashboard edit mode

 cde 01/17/14 - Bug 2314558  - some other error description
</code>```

It seems helpful, but is it considered bad practice?

答:
No, it is not a good practice to track your bug fixes as comments in the code. This only generates clutter.

I'll also say the same for the copyright message that you mentioned. If no one outside your company is ever going to see this code, there's no reason to include a copyright message.

If you are using version tracking software (Git, SVN, etc.), then you should include those notes in your commit messages. No one wants to dig through the headers of every code file to generate release notes or see an overview of what changes were made. These change logs should all be stored together, either in your version tracking history, your defect tracker, or both.

If you're looking for a good read on this subject, I recommend chapter four of Clean Code.


答:
Monetary compensation isn't the only possible compensation. Fame (although mostly to a limited circle) is another. The joys of showing off what you've done is yet another.

Me, I mostly do it because I have an urge to write software and if it happens to help someone else, everyone wins.

Title: Why develop free, open source programs?


问:
Proxy to redirect DNS during development
I am using Genymotion to test an app. The app is basically a browser that connects to my website. I do not have the app's source.
I do the development and testing of the website in a domain like this: dev.mywebsite.com

The app connects to mywebsite.com. Genymotion allows me to use an HTTP proxy. My question is, is there any software for windows or linux that would work as a proxy and redirect all requests to mywebsite.com to dev.mywebsite.com ?

答:
This is the classic purpose of using a hosts file. It's a very simple to edit file wherein you can put manual overrides for domain names to force them to resolve to some given IP.

Windows

Here's a simple tutorial on how to edit your windows hosts file: http://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/

Example of windows hosts file (C:\windows\system32\drivers\etc\hosts):

```<code>102.54.94.97     rhino.acme.com          # source server
38.25.63.10     x.acme.com              # x client host
</code>```

In the windows host file you can see the # mark identifying the start of a comment which is ignored by the OS.

Linux

Here's the linux man page for the linux /etc/hosts file which is nigh identical to the windows hosts file, examples at the bottom of the man page make fairly clear how it works: http://man7.org/linux/man-pages/man5/hosts.5.html

Example of linux /etc/hosts file:

```<code>127.0.0.1       localhost
192.168.1.10    foo.mydomain.org       foo
192.168.1.13    bar.mydomain.org       bar
146.82.138.7    master.debian.org      master
209.237.226.90  www.opensource.org
</code>```

The linux host file also recognizes the # as beginning of comments just the same as the windows file.

Body:
This is the classic purpose of using a hosts file. It's a very simple to edit file wherein you can put manual overrides for domain names to force them to resolve to some given IP.

Windows

Here's a simple tutorial on how to edit your windows hosts file: http://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/

Example of windows hosts file (C:\windows\system32\drivers\etc\hosts):

102.54.94.97     rhino.acme.com          # source server
38.25.63.10     x.acme.com              # x client host

In the windows host file you can see the # mark identifying the start of a comment which is ignored by the OS.

Linux

Here's the linux man page for the linux /etc/hosts file which is nigh identical to the windows hosts file, examples at the bottom of the man page make fairly clear how it works: http://man7.org/linux/man-pages/man5/hosts.5.html

Example of linux /etc/hosts file:

127.0.0.1       localhost
192.168.1.10    foo.mydomain.org       foo
192.168.1.13    bar.mydomain.org       bar
146.82.138.7    master.debian.org      master
209.237.226.90  www.opensource.org

The linux host file also recognizes the # as beginning of comments just the same as the windows file.


答:
Python is plenty fast for this purpose.  Depending on what kind of analysis you're running, I would expect to easily handle hundreds or even thousands of events per second.

Your slowdown is most likely algorithmic.  It's not enough to optimize pieces of the puzzle, you have to optimize the system as a whole by choosing appropriate data structures and algorithms.

I once encountered some code that ran very slowly, but looking at just one layer it didn't look like it should.  It appeared to be a simple linked list traversal with at most 64 nodes, which is O(n) with a pretty small n.  Well it turns out, that function called another O(n) function, which called another O(n) function, and so on 6 layers deep.  That resulted in an O(n6) algorithm that no one noticed before because they only looked at one layer at a time, and ran it on data that happened to short circuit fortuitously.

So look at your system as a whole.  Are you reading the same files over and over again or caching appropriately?  Are you performing the same joins or other calculations over and over again or preprocessing and memoizing your data for future use?  Are you assuming lower layers of function calls are linear or constant time when they're not?  Can you rearrange the order of operations to make it faster?  Can you create indexes to speed up certain lookups?

These are the sorts of issues you need to fix before you start looking at linear speedups you might gain from switching to another language.  If it's difficult to fix in python, imagine how difficult it will be to fix in an unfamiliar programming language.

Title: Is Python suitable for a statistical modeling application looking over thousands of past events?

Body:
I'm currently working on a project with a partner where we analyze large datasets of past sporting events. There are approximately 30,000 events per year and we have historical data for five years. Thus, we're looking at analyzing 150,000 events.

I wrote our first version in Python with a heavy reliance on Pandas (great tool, by the way). However, each time I add a "factor" or calculation to the process it slows down by quite a bit. Simply put, it can read all the various data files and data queries we need at a rate of 25-events-per-second.

The problem is once I start working with the data, it drops fast. If I add a simple calculation, it drops to 24... and each calculation after that it drops again.

With just 10-12 "factors" calculated from the data (we're not talking complex loops or anything crazy), it's now down to 6-events-per-second. ... and we're barely scratching the surface. At this rate, it'll take this thing days to work through all 150k events!

I've optimized our data queries, flat file reads etc. Those really aren't the issue. I can live with doing 15-20 events per second. However, I can't live with such drastic slowdowns each time a new factor calculation is added.

I've read a lot where Python as an interpreted language is slow etc., but my question to the experts out there - what language should this project be done in?

EXAMPLE...

One of the key "DataFrames" I am using through Pandas is fairly large. 350 rows x 70 columns, as an example. Even when trying to simply multiply one column's value by another...

```<code> data['value'] = data['col1'] * data['col2']
</code>```

...I see what I could consider significant drop in performance. It's very puzzling, and very frustrating. I understand this is a large set of data, but I can't believe this is anything so crazy that Python would be slowing to a crawl.

If I just read the data files and do no calculations on them at all, it reads 67 events in 2.807 seconds. If I add one simple calculation where I execute code like the example above, it slows to 2.877 seconds. Based on our research, we're needed to add upwards of 100 calculations on the data.... so 7 seconds worth of slowdown? Seems too hard to believe.


问:
Should I change the name of the WTFPL?
I'm using the WTFPL in my personal projects that I have published on GitHub.

Currently I'm using the license verbatim, but I have a suspicion that I shouldn't be leaving the third line:

```<code>Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
</code>```

in there, and instead should use my name instead of Sam's.

But the license is very confusing about this.

Half of the WTFPL site is about the WTFPL itself, so I thought that copyright statement might refer to a copyright on the license text itself, and not on the project that is using the license.

However, the site also says:

Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.

So would I have to change the name from "WTFPL" to something like "WTFPL-Domenic"?

答:
Short answer: No, you do not need to rename the license to use it.

Wall of text: As described in the FAQ page:

The copyright notice, as you said, applies only to the license document itself. You cannot put your own name in there and still call it WTFPL.

On the other hand, you are allowed to modify the license document as long as you change the license name, so yes, you can license your work under a custom "WTFPL-Domenic", but that would be inventing your own license.

So, the copyright notice does not mean you're giving all rights to your work to Sam. It just means the license document was written by him.

BTW, you are not obligated to include the license document with your work, if you think it might cause confusion for your licensees. You can simply put one-liner notices in your code like this (with or without the URL):

```<code>// This code is released under WTFPL Version 2 (http://www.wtfpl.net/)
</code>```

Or you could get wordier, if that appears not-legal-enough for you:

```<code>Copyright © 2000 Your Name <your@address>
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
</code>```

(Note that your own copyright notice goes into the first line.)

Another option (includes a no-warranty clause):

```<code>/* This program is free software. It comes without any warranty, to
 * the extent permitted by applicable law. You can redistribute it
 * and/or modify it under the terms of the Do What The Fuck You Want
 * To Public License, Version 2, as published by Sam Hocevar. See
 * http://www.wtfpl.net/ for more details. */
</code>```

Title: Should I change the name of the WTFPL?

Body:
Short answer: No, you do not need to rename the license to use it.

Wall of text: As described in the FAQ page:

The copyright notice, as you said, applies only to the license document itself. You cannot put your own name in there and still call it WTFPL.

On the other hand, you are allowed to modify the license document as long as you change the license name, so yes, you can license your work under a custom "WTFPL-Domenic", but that would be inventing your own license.

So, the copyright notice does not mean you're giving all rights to your work to Sam. It just means the license document was written by him.

BTW, you are not obligated to include the license document with your work, if you think it might cause confusion for your licensees. You can simply put one-liner notices in your code like this (with or without the URL):

// This code is released under WTFPL Version 2 (http://www.wtfpl.net/)

Or you could get wordier, if that appears not-legal-enough for you:

Copyright © 2000 Your Name <your@address>
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.

(Note that your own copyright notice goes into the first line.)

Another option (includes a no-warranty clause):

/* This program is free software. It comes without any warranty, to
 * the extent permitted by applicable law. You can redistribute it
 * and/or modify it under the terms of the Do What The Fuck You Want
 * To Public License, Version 2, as published by Sam Hocevar. See
 * http://www.wtfpl.net/ for more details. */


答:
I see that everyone is opposed to the idea and gave a historical reason (pre source control era) of why people were doing it.

However, in my current company, database developers are following this practice and they additionally tag the bug number around the piece of code. I sometimes find this helpful when you see a bug in the code and you can instantly find out the bug fix that introduced this issue. If we don't have that information in my database package it certainly won't be easy to find the root cause of that implementation.

Yes, it clutters the code, but it helps in finding the reason of why that piece of code is there.

Title: Good idea to put bug numbers in a comment in the beginning of the source file?

Body:
Is it a good practice to put bug numbers in the file itself inside a header comment?

The comments would look something like this:

```<code> MODIFIED    (MM/DD/YY)
 abc 01/21/14 - Bug 17452317 - npe in drill across in dashboard edit mode

 cde 01/17/14 - Bug 2314558  - some other error description
</code>```

It seems helpful, but is it considered bad practice?


答:
I think there are other elements to this discussion that are often forgotten but are cases where some revision comment is expeditious to a team.

When working in a team environment with a shared code base and where several team members are potentially working in the same areas of code, putting a short revision comment in the correct scope (method or class) indicating a change was made can be very useful for quickly resolving merge or checkin conflicts.

Likewise, when working in an environment where several (feature) branches are involved, it makes it easier for a third person (build master) to identify what to do to resolve potential conflicts.

Any time you have to get away from the IDE and ask someone why they changed something, it is disruptive to both team members' productivity. A quick note in the correct scope can help abate or eliminate most of this interruption.


问:
How do I integrate a browser-based JavaScript unit testing framework into my workflow?
I'm wondering how I seamlessly include a JavaScript unit testing framework into my workflow.

The context is, we have an existing data processing algorithm + webapp to display it, with no automated testing or continuous integration.

We use Eclipse as our IDE.

For the webapp JavaScript modification, it would be nice to add some unit tests, and qUnit looks straightforward, plenty of community support etc.

Here's how I'm currently thinking the workflow would go:

Branch the JavaScript code, check it out, modify it. Refactor it to make it more testable if needed.

Write qUnit unit tests in accordance to the above tutorial.

Start Tomcat in eclipse, run the qUnit test page.

Open the browser, check that all the tests have passed.

Commit the code back to the branch.

Merge the branch back into to trunk.

At this point there might have been a merge conflict, and so unit tests would need to be run again for the trunk to check that they're still working.

The issue here, it still seems a little cumbersome to be running the unit tests, several clicks involved to run and check the results.

Now with the merge back to trunk issue, clearly a continuous integration solution like Jenkins would be good here, but given that that's out of the question for now, let's just focus on how we can make it easy to run the tests as a developer.

Do you think I'm missing something here, or is what I'm proposing reasonable sensible?

答:
Ideally, the workflow should be fully automated end-to-end

Use a tool like Karma.  Run them minimally in PhantomJS to catch the logic errors, and ideally with every supported browser. Integrate it directly in your build. All you should need to test your app should be something like

```<code>mvn verify
</code>```

(in this case if you use maven. If you use say Ant, it should be integrated in your Ant build, if you use Grunt... you get the point).

Nothing more (and I mean it). If running the test is even slightly an hassle, you will stop running them, which is bad. If you need to click, you can't run them with your CI server, which is bad. If its not part of your build, you can forget running them, which is bad.

I highly recommend that you have a IDE agnostic build system. If not, it's time you check that out, before anything else. Then integrate the testing in your build. Failing test should fail the build in an automatic matter, without any intervention. In a perfect world, it should be impossible to forget to run the test.

So in conclusion : check karma and phantomjs. This is what will help you the most. But I insist on going the extra mile : add a complete build script that check the validity of the code in one single command. And while we're at it, do you validate your javascript with a tools like JSHint? If not, check that out too (and put it in your build :) ). It can catch many mistakes.

Body:
Ideally, the workflow should be fully automated end-to-end

Use a tool like Karma.  Run them minimally in PhantomJS to catch the logic errors, and ideally with every supported browser. Integrate it directly in your build. All you should need to test your app should be something like

mvn verify

(in this case if you use maven. If you use say Ant, it should be integrated in your Ant build, if you use Grunt... you get the point).

Nothing more (and I mean it). If running the test is even slightly an hassle, you will stop running them, which is bad. If you need to click, you can't run them with your CI server, which is bad. If its not part of your build, you can forget running them, which is bad.

I highly recommend that you have a IDE agnostic build system. If not, it's time you check that out, before anything else. Then integrate the testing in your build. Failing test should fail the build in an automatic matter, without any intervention. In a perfect world, it should be impossible to forget to run the test.

So in conclusion : check karma and phantomjs. This is what will help you the most. But I insist on going the extra mile : add a complete build script that check the validity of the code in one single command. And while we're at it, do you validate your javascript with a tools like JSHint? If not, check that out too (and put it in your build :) ). It can catch many mistakes.


答:
Any bug information directly associated to a piece of code, become irrelevant when the integrity of the whole change is modified by a successive fix.

It used to be common to add info in the function summary when we had to rely on external tools (say javadocs) to create release notes from the code.
It is mostly useless or redundant with modern version control tools.

It could only make sense as a comment in a very modular piece of code, if one has to resort to some obscure or non stellar coding which future developers would be tempted to change - unaware of the reason behind it - like in a workaround to a library bug/shortcoming.


问:
How does the Fibonacci exponentiation by squaring algorithm work?
This is one of the best algorithms to calculate the nth Fibonacci sequence. It only needs O(log(n)) time to do its job, so it's very efficient. I found it somewhere but don't know how it works!

Can anyone tell me how this algorithm works?

int fib3 (int n) {
    int i = 1, j = 0, k = 0, h = 1, t;
    while (n > 0) {
        if (n % 2) {
            t = j * h;
            j = i * h + j * k + t;
            i = i * k + t;
        }
        t = h * h;
        h = 2 * k * h + t;
        k = k * k + t;
        n /= 2;
    }
    return j;
}
```

答:
It's called the "matrix form" - take a look at Wikipedia

You can compute next Fibonacci number (k+2) by multiplying matrix on a vector of two previous elements (k + 1 and k). Hence, k + 3 can be computed by multiplying matrix on vector of (k + 2 and k + 1). This equals squared matrix multiplied on (k + 1 and k). So on.

Your code simply squares the matrix, taking into account odd powers.


问:
How do crackers determine number of iterations of a Hashing algorithm?
Does a cracker need to know the number of iterations a hashing algorithm uses to compute a hash?

If they don't know it, how do they figure it out? How much longer does it take to figure it out, than if they didn't know?

I can only guess that they try a number of the most common passwords, and try it with different iterations, and see what amount of iterations returns the most correct passwords. Would this even work though?

答:
The usual attack models assume that the attacker knows the exact algorithm used and the only unknown is (in the case of hashing-to-hide-plaintexts) the plaintext. In short, the enemy already knows the system.

Sometimes this gives the attacker too much credit, but that's better then underestimating them. Since password hashes are typically retrieved by breaking into a production server, it's likely that the application source code (which includes a full specification of the hashing procedure used) was grabbed at the same time. In other cases, the source code is open to begin with.


答: Unless you implement hashing algorithm on server side, and use some non-standard algorithm, Everything about hashing algorithm is known to hacker. if implemented on client side, it can be reverse engineered, even if you use non-standard algorithm, or obfuscate a standard algorithm.</p>

Title: How do crackers determine number of iterations of a Hashing algorithm?

Body:
Does a cracker need to know the number of iterations a hashing algorithm uses to compute a hash?

If they don't know it, how do they figure it out? How much longer does it take to figure it out, than if they didn't know?

I can only guess that they try a number of the most common passwords, and try it with different iterations, and see what amount of iterations returns the most correct passwords. Would this even work though?


答:
There are several reasons to develop open source applications.  In general, the more foundational the need is the better suited to open source it is.  For example, ASP.NET MVC, Ruby on Rails, Django, PHP, and other web frameworks are all open source.  That's right, even Microsoft has a fairly well known open source project.  The need for a well organized web framework that lets you focus on building a web application is larger than the specific web application you are building.

Many people (myself included) contribute to open source because we use these frameworks in our day job.  It's self preservation in a sense.  If I don't have to keep reinventing the wheel just because I am at a new company, why should I?

As to making money with open source, that is a tricky subject.  Most open source licenses allow you to sell your software.  The specific license governs whether you need to share your modifications (BSD/ASL style licenses do not while GPL style licenses do in most cases), or provide attribution ot the original project.

The cases that I see work most often are:

Selling support.  MySQL, Spring, and a few others follow this model and do well with it.

Selling convenience.  RedHat, SuSE, and other Linux distros package a group of applications together for the user's convenience.

Selling appliances.  In short this is the way companies like Google, Nokia, Linksys, etc. make money packaging proprietary and open source products together and keeping them safe.  It's probably the most lucrative option.

Selling T-Shirts/Mugs/etc.  Doesn't bring in a whole lot, but better than nothing.

Bottom line is that the source code may be open, but there are always people who need more than the raw code.  I'm sure there are more ways to make money off of open source, you just have to be creative.

Title: Why develop free, open source programs?


答:
I don't know any disadvantages either, however vertical stories can be implemented badly.

When I first started my career I joined a team that was keen to do XP but they had no experience with it. We made a number of mistakes when using vertical user stories.

One of the problems we encountered when doing horizontal work was that features did not integrate well across the layers. APIs often did not match the specification, features where missing and numerous other problems. Often because the developer of the had moved on to something else, you would either have to wait for them or do it yourself yourself.

Switching to doing Vertical Stories solved these problems and reduced/eliminated the waste of re-working to integrate.

There are a number of XP practices that support this way of working. Anyone needs to be able to work on any area and everyone is expected to fix the bugs they find (Collective Code ownership).

When you are making the change to vertical stories, it can be tricky to work in areas that you're not familiar with. Pair Programming can help, if you aren't confident grab someone in the team who is pair with them. I've found pair programming to be the fastest way to get up to speed with a new code base.

Without strong owners over layers we found, that there was some duplication emerging. Although this was not a big problem, we needed to make sure that we practiced Refactor Mercilessly (with appropriate tests to support).

Although I mention a number of problems, I don't think Vertical User Stories was the cause. In fact, it made the problems more apparent. After we made the switch, problems were no longer obfuscated across teams or application layers.

Title: Disadvantages of vertical user stories


问:
Are frameworks used for "big" websites?
I'm kind of new to PHP. I can create basic sites with login/registration, etc., but I always struggle to build complex sites with lots of features, because eventually the code becomes messy and I just run into more and more little bugs, and then fixing those produces another, and so on. I realise that that's partially to do with me simply not writing clean code (I'm working on that!) but I would also probably benefit from using a framework.

But is using ready-made frameworks "unprofessional"? Would a big site such a YouTube or Facebook use a framework like CakePHP or CodeIgniter?

答:
I don't think that using a framework is a problem. In fact, it brings a lot of useful features and benefits, such as unit testing, good practices, or stability of your code. Zend and Symphony are good examples of frameworks that enhance your coding abilities.

However, using a framework does not make your code more performant. There are many other factors which need to be considered in order to make your application run fast.

Answering your question: yes, frameworks are used in big websites.

Title: Are frameworks used for "big" websites?


答:
Keep this in mind - the code is often around longer than the tools that support it.  Said differently, the issue trackers, version control and all the other scripts will evolve over the course of development.  Information gets lost.

While I do agree, file clutter is annoying, opening a file and understanding its history without resorting to using the tools, has always been very helpful - especially if I'm maintaining the code.

Personally, I think there is room for both the tools and in-code log.


问:
What Functional features are worth a little OOP confusion for the benefits they bring?
After learning functional programming in Haskell and F#, the OOP paradigm seems ass-backwards with classes, interfaces, objects.  Which aspects of FP can I bring to work that my co-workers can understand?  Are any FP styles worth talking to my boss about retraining my team so that we can use them?

Possible aspects of FP:

Immutability

Partial Application and Currying

First Class Functions (function pointers / Functional Objects / Strategy Pattern)

Lazy Evaluation (and Monads)

Pure Functions (no side effects)

Expressions (vs. Statements - each line of code produces a value instead of, or in addition to causing side effects)

Recursion

Pattern Matching

Is it a free-for-all where we can do whatever the programming language supports to the limit that language supports it?  Or is there a better guideline?

答:
There are many good answers already, so mine will address a subset of your question; namely, I take umbrage to the premise of your question, as OOP and functional features aren't mutually exclusive.

If you use C++11, there are a lot of these sorts of functional-programming features built into the language/standard library that synergize (pretty) well with OOP. Of course, I'm not sure how well TMP will be received by your boss or coworkers, but the point is you can get many of these features in some form or another in non-functional/OOP languages, like C++.

Using templates with compile time recursion relies on your first 3 points,

Immutability

Recursion

Pattern Matching

In that template-values are immutable (compile-time constants), any iteration is done using recursion, and branching is done using (more or less) pattern matching, in the form of overload resolution.

As for the other points, using std::bind and std::function gives you partial function application, and function pointers are built-in to the language. Callable objects are functional objects (as well as partial function application). Note that by callable objects, I mean ones that define their operator ().

Lazy evaluation and pure functions would be a bit harder; for pure functions, you can use lambda functions which only capture by value, but this is non-ideal.

Lastly, here's an example of using compile-time recursion with partial function application. It's a somewhat contrived example, but it demonstrates most of the points above. It'll recursively bind the values in a given tuple to a given function and generate a (callable) function object

```<code>#include <iostream>
#include <functional>

//holds a compile-time index sequence
template<std::size_t ... >
struct index_seq
{};

//builds the index_seq<...> struct with the indices (boils down to compile-time indexing)
template<std::size_t N, std::size_t ... Seq>
struct gen_indices
  : gen_indices<N-1, N-1, Seq ... >
{};

template<std::size_t ... Seq>
struct gen_indices<0, Seq ... >
{
    typedef index_seq<Seq ... > type;
};

template <typename RType>
struct bind_to_fcn
{
    template <class Fcn, class ... Args>
    std::function<RType()> fcn_bind(Fcn fcn, std::tuple<Args...> params)
    {
        return bindFunc(typename gen_indices<sizeof...(Args)>::type(), fcn, params);
    }

    template<std::size_t ... Seq, class Fcn, class ... Args>
    std::function<RType()> bindFunc(index_seq<Seq...>, Fcn fcn, std::tuple<Args...> params)
    {
        return std::bind(fcn, std::get<Seq>(params) ...);
    }
};

//some arbitrary testing function to use
double foo(int x, float y, double z)
{
    return x + y + z;
}

int main(void)
{
    //some tuple of parameters to use in the function call
    std::tuple<int, float, double> t = std::make_tuple(1, 2.04, 0.1);
    typedef double(*SumFcn)(int,float,double);

    bind_to_fcn<double> binder;
    auto other_fcn_obj = binder.fcn_bind<SumFcn>(foo, t);
    std::cout << other_fcn_obj() << std::endl;
}
</code>```

Body:
There are many good answers already, so mine will address a subset of your question; namely, I take umbrage to the premise of your question, as OOP and functional features aren't mutually exclusive.

If you use C++11, there are a lot of these sorts of functional-programming features built into the language/standard library that synergize (pretty) well with OOP. Of course, I'm not sure how well TMP will be received by your boss or coworkers, but the point is you can get many of these features in some form or another in non-functional/OOP languages, like C++.

Using templates with compile time recursion relies on your first 3 points,

Immutability

Recursion

Pattern Matching

In that template-values are immutable (compile-time constants), any iteration is done using recursion, and branching is done using (more or less) pattern matching, in the form of overload resolution.

As for the other points, using std::bind and std::function gives you partial function application, and function pointers are built-in to the language. Callable objects are functional objects (as well as partial function application). Note that by callable objects, I mean ones that define their operator ().

Lazy evaluation and pure functions would be a bit harder; for pure functions, you can use lambda functions which only capture by value, but this is non-ideal.

Lastly, here's an example of using compile-time recursion with partial function application. It's a somewhat contrived example, but it demonstrates most of the points above. It'll recursively bind the values in a given tuple to a given function and generate a (callable) function object

#include <iostream>
#include <functional>

//holds a compile-time index sequence
template<std::size_t ... >
struct index_seq
{};

//builds the index_seq<...> struct with the indices (boils down to compile-time indexing)
template<std::size_t N, std::size_t ... Seq>
struct gen_indices
  : gen_indices<N-1, N-1, Seq ... >
{};

template<std::size_t ... Seq>
struct gen_indices<0, Seq ... >
{
    typedef index_seq<Seq ... > type;
};

template <typename RType>
struct bind_to_fcn
{
    template <class Fcn, class ... Args>
    std::function<RType()> fcn_bind(Fcn fcn, std::tuple<Args...> params)
    {
        return bindFunc(typename gen_indices<sizeof...(Args)>::type(), fcn, params);
    }

    template<std::size_t ... Seq, class Fcn, class ... Args>
    std::function<RType()> bindFunc(index_seq<Seq...>, Fcn fcn, std::tuple<Args...> params)
    {
        return std::bind(fcn, std::get<Seq>(params) ...);
    }
};

//some arbitrary testing function to use
double foo(int x, float y, double z)
{
    return x + y + z;
}

int main(void)
{
    //some tuple of parameters to use in the function call
    std::tuple<int, float, double> t = std::make_tuple(1, 2.04, 0.1);
    typedef double(*SumFcn)(int,float,double);

    bind_to_fcn<double> binder;
    auto other_fcn_obj = binder.fcn_bind<SumFcn>(foo, t);
    std::cout << other_fcn_obj() << std::endl;
}


问:
Licensing - Using Standard C Library
I've been reading about software licenses for a few hours because of the reason that I want to release a software commercially. I'm no lawyer and I'm incredibly bad at understanding licenses.

Perhaps my question is very trivial but anyways pardon me for my ignorance. So the question is if I include any standard C library header (ex. math.h) am I supposed to release it (my program) under GPL? As the notice at the top says so, or is that notice targeted for people MODIFYING it and not USING it? O and BTW, I'm using MinGW/GCC and I've read that you are not obliged to release it under GPL as long as only the compiler is used, well then how about the Standard C Headers that have seperate copyright notices in them?

PS: If I am obliged to release it under GPL, how can I make a program to be released commercially without relying on that library/header that I need (that is in the standard C headers)?

答:
The C library & headers included with most unix-type systems is NOT licensed under the GPL. It's licensed under the LGPL (L for Lesser or Library, depending).

With the LGPL, you can use the library in your code WITHOUT releasing your code under GPL.

So you're ok on that library. Be sure to check all the libraries you use, however, there are a few out there that are GPL.

Title: Licensing - Using Standard C Library


问:
How to decompose / model a chessboard
As someone new to programming, I am building a chess web application in JavaScript, both for fun and to learn more about design patterns. I keep running into a wall, which is how to decompose the program.

To start, I have picked a straightforward representation of a chessboard, here:

```<code>Board = function() {
  var turn = 0;
  var model = [[-4, -2, -3, -5, -6, -3, -2, -4],
               [-1, -1, -1, -1, -1, -1, -1, -1],
               [ 0,  0,  0,  0,  0,  0,  0,  0],
               [ 0,  0,  0,  0,  0,  0,  0,  0],
               [ 0,  0,  0,  1,  0,  0,  0,  0],
               [ 0,  0,  0,  0,  0,  0,  0,  0],
               [ 1,  1,  1,  1,  1,  1,  1,  1],
               [ 4,  2,  3,  5,  6,  3,  2,  4]];
</code>```

with some basic access routines, such as

```<code>  this.move = function(pt1, pt2) {
    turn += 1;
    model[pt2.x][pt2.y] = model[pt1.x][pt1.y];
    model[pt1.x][pt1.y] = 0;
  };
  ...
</code>```

It makes sense that the board encapsulates state and is responsible for changing state but may not know the rules of the game--I like the idea of being able to plug in some sort of RulesContoller and completely change the nature of the game at runtime. But beyond that, I'm a little paralyzed as to how granular to model the pieces. I see a few options.

First, I could define a Piece constructor and instantiate a new piece for each index in the nested array, something like:

```<code>  _.each(state, function(row, y) {
    _.each(row, function(val, x) {
      state[y][x] = new Piece(x, y, val);
    });
  });
</code>```

Piece could easily deduce its color, type (e.g. 'king'), and location from that information. But it also feels redundant, since I'm just translating a model that already completely represents the board. Also, it doesn't seem like the primary purpose of the Piece 'class' is this translation, e.g. "Oh, I'm a -5, must be a dark Queen."

Another option is to make the pieces dumber, i.e. not able to deduce this information from the model. But then I just build the array in-line, like

```<code>  var model = [new Rook(1,1,'dark'), new Knight(1,2,'dark'), new Bishop(1,3,'dark')... ],
  ...
</code>```

This seems closer to the way a chessboard is actually setup: there isn't some elegant formula; rather, you just put pieces in their correct location. But it's also just brute force. There are a few symmetries involved and patterns that might be simplified.

Anyway, I'm just spitballing at this point. Any ideas would be useful. Thanks.

答:
The answer is to stop designing, since you don't have enough experience to know what to do, and start coding something.  Maybe start with just pawns; add functions that can calculate the legal moves if there are only pawns on the board.  Then add a king and see what that does to your code.  And so on.

I have a lot of experience coding, and I still mostly work like this, implementing one thing at a time, and cleaning up as I go. A lot of complex applications have been built incrementally.

Title: How to decompose / model a chessboard


问:
How should I structure my namespace tree so that I have a Math class and Math namespace?
I don't know if this is a good or bad idea, or if it's technically even possible... but I'd like to have something of the following sort:

```<code>public class Math {
  public int gcd(a,b) // Method for Greatest Common Denominator
  public int lcm(a,b) // Method for Least Common Multiple
  public int factorial(a) // Method for factorial
  ...
}
</code>```

and then I'd also like to have a namespace called Math that has subclasses such as Math.Matrix, Math.RowVector, Math.ColumnVector, etc... so I can define my own Matrix data structure and its associated actions.

Is this advisable? I am not too keen on the idea of using some other name for my Math class, as I want it to be a static class with all sorts of functions/methods that are useful to me, and at the same time, I want to gather all my relevant data structures under a Math namespace.

答:
See these for a clarification: Do not name a class the same as its namespace and Names of Namespaces

Basically,

DO NOT use the same name for a namespace and a type in that namespace.

I would use something like MathUtilities or MathUtil, for short, for the namespace and then you can have your MathUtil.Math and the rest.


答:
Is it technically possible?  Try it and find out, at worst the compiler will yell at you, but won't call you nasty names.

What you are trying to do is make a "Utils" or similar class that should be in your Math namespace.  Generally though "Utils" class is frowned upon but still well understood if you use it.  In that case you can break them up into disciplines like Math.Trig or Math.Geometry.

Title: How should I structure my namespace tree so that I have a Math class and Math namespace?

Body:
I don't know if this is a good or bad idea, or if it's technically even possible... but I'd like to have something of the following sort:

```<code>public class Math {
  public int gcd(a,b) // Method for Greatest Common Denominator
  public int lcm(a,b) // Method for Least Common Multiple
  public int factorial(a) // Method for factorial
  ...
}
</code>```

and then I'd also like to have a namespace called Math that has subclasses such as Math.Matrix, Math.RowVector, Math.ColumnVector, etc... so I can define my own Matrix data structure and its associated actions.

Is this advisable? I am not too keen on the idea of using some other name for my Math class, as I want it to be a static class with all sorts of functions/methods that are useful to me, and at the same time, I want to gather all my relevant data structures under a Math namespace.


问:
What is a uniform way to express Country, City, State? (ISO standard, etc)
I need to encode data into a user token that describes the user's Country, State, and city.  I understand that different descriptors apply to different government hierarchies, but am looking for a standard of some type that has already sorted this out.

What ISO standard, binary format, etc is best at describing a user who may be from any country?

答:
Bluntly, there isn't any one standard. Within the US, there are differing notations for states, counties, and regions (zip codes, area codes, metropolitan regions, etc.). While the US does have a standardized address format, even that is highly subject to variations. Also, address standards change regularly. Before the age of the internet, mailing a letter could be done without a zip code (because they hadn't been invented at the time) and you used a 3 letter abbreviation for most states.

Canada has a similar addressing scheme to the US. However, the postal codes in Canada are 6 or 7 digits. Including a space after the 3rd character of the postal code may appear to be the same region, but it isn't. I have also heard rumors of Canada moving to an 8 digit postal code.

Almost every country has an online guide from their official postal service with detailed information about acceptable address formats.

Google, ESRI, and other map data providers have come up with varying ways to associate an address with a lat/long pair. Google uses KML (a specific standard of XML used for addresses). They break an address into a street number, street name, lat/long, and several political hierarchies. You will find that in some countries, the political divisions can be 7 or 8 layers deep (maybe more since the last time I did research into this area).

If you are looking at what you need to store in a database for your customers, follow the US address format with several additional address lines (I typically store a minimum of 3 address lines for international addresses), a city, a state or province, a postal code (international needs to allow for at least 15 characters, digits and alpha), and a country. I have started to include lat/long recently as addresses can change without warning.

There are ISO standards for country code which a quick search will turn up a bunch of links. Beyond that, you are pretty much on your own for formatting though.


问:
Using error numbers which only work on 64 bit servers: a bad idea?
In an attempt to solve one problem I encountered another. I would like to have an easy and memorable way of creating unique error numbers, across projects and across developers. The scheme I came up with was to use the initials of the developer, find their position in the alphabet, and append the date and time.
Example: lets say the developer Mark Elliot Zuckerberg (initials MEZ) writes code that throws an exception on Feb 8th 2014 at 12:54AM. The error code would be: 8526020820140054

This works brilliantly on 64 bit machines, but the resulting integer is too large for 32 bit computers. Does that make this a bad idea? How common are 32 bit servers, and do we expect them to slowly disappear completely?

答:
Why not use a string data type for the error code instead of a number?  This will allow large code to be stored without any issues as to integer size.  Even though the error code does look like a number, unless the design is calling for arithmetic with it then it is not a number, then it really should be a string data type.  </p>

<p>I'm also a little concerned about this method for error codes.  Error codes should be designed into the application, listed in the documentation, and when triggered be predictable.  If your code triggers an exception then it should be the same error code with the same inputs.  However this design is using a random event to identify the error, nor does it point where in the code that the exception is happening, only who wrote the code and when the exception was fired.  </p>

Body:
Why not use a string data type for the error code instead of a number?  This will allow large code to be stored without any issues as to integer size.  Even though the error code does look like a number, unless the design is calling for arithmetic with it then it is not a number, then it really should be a string data type.

I'm also a little concerned about this method for error codes.  Error codes should be designed into the application, listed in the documentation, and when triggered be predictable.  If your code triggers an exception then it should be the same error code with the same inputs.  However this design is using a random event to identify the error, nor does it point where in the code that the exception is happening, only who wrote the code and when the exception was fired.


答: The design of the board object should reflect somewhat to how it is viewed in the real world.  A square on the chess board is defined by a x,y cord where one is a alphabetic character and the other being a integer.  Each "space" in the data structure can be a pointer to a piece object.  The Piece should be able to get its position on the board, but does not change the state of the board itself.  The Rules Controller idea sounds good, it can take a piece look up its legal moves and then relocate the piece on the board.  It can hit up any rules configuration you throw at it, like, replacing the pawn pieces with checkers.</p>

Title: How to decompose / model a chessboard

Body:
As someone new to programming, I am building a chess web application in JavaScript, both for fun and to learn more about design patterns. I keep running into a wall, which is how to decompose the program.

To start, I have picked a straightforward representation of a chessboard, here:

```<code>Board = function() {
  var turn = 0;
  var model = [[-4, -2, -3, -5, -6, -3, -2, -4],
               [-1, -1, -1, -1, -1, -1, -1, -1],
               [ 0,  0,  0,  0,  0,  0,  0,  0],
               [ 0,  0,  0,  0,  0,  0,  0,  0],
               [ 0,  0,  0,  1,  0,  0,  0,  0],
               [ 0,  0,  0,  0,  0,  0,  0,  0],
               [ 1,  1,  1,  1,  1,  1,  1,  1],
               [ 4,  2,  3,  5,  6,  3,  2,  4]];
</code>```

with some basic access routines, such as

```<code>  this.move = function(pt1, pt2) {
    turn += 1;
    model[pt2.x][pt2.y] = model[pt1.x][pt1.y];
    model[pt1.x][pt1.y] = 0;
  };
  ...
</code>```

It makes sense that the board encapsulates state and is responsible for changing state but may not know the rules of the game--I like the idea of being able to plug in some sort of RulesContoller and completely change the nature of the game at runtime. But beyond that, I'm a little paralyzed as to how granular to model the pieces. I see a few options.

First, I could define a Piece constructor and instantiate a new piece for each index in the nested array, something like:

```<code>  _.each(state, function(row, y) {
    _.each(row, function(val, x) {
      state[y][x] = new Piece(x, y, val);
    });
  });
</code>```

Piece could easily deduce its color, type (e.g. 'king'), and location from that information. But it also feels redundant, since I'm just translating a model that already completely represents the board. Also, it doesn't seem like the primary purpose of the Piece 'class' is this translation, e.g. "Oh, I'm a -5, must be a dark Queen."

Another option is to make the pieces dumber, i.e. not able to deduce this information from the model. But then I just build the array in-line, like

```<code>  var model = [new Rook(1,1,'dark'), new Knight(1,2,'dark'), new Bishop(1,3,'dark')... ],
  ...
</code>```

This seems closer to the way a chessboard is actually setup: there isn't some elegant formula; rather, you just put pieces in their correct location. But it's also just brute force. There are a few symmetries involved and patterns that might be simplified.

Anyway, I'm just spitballing at this point. Any ideas would be useful. Thanks.


问:
What's the difference between syntax and semantics?
I've always thought that referring to the syntax of a language was the same as referring to the semantics of a language. But I've been informed that apparently that's not the case. What's the difference?</p>

答:
Syntax and semantics is like strategy and tactics or left and right.

They are not really independent universal concepts, but a related pair of words that, when you are in a particular context, indicate opposite directions. But the same thing that is strategy on one scale is tactics on another.

So if you are writing code in a language, the syntax is the language you are using and the desired behaviour is the semantics. But if you are implementing, or discussing, the compiler for that language, then the syntax is the grammar and perhaps type system and the semantics everything built on that. And so on.


答:
This works brilliantly on 64 bit machines, but the resulting integer is too large for 32 bit computers.

Actually, 32 bit computers can handle 64 bit numbers just fine.  OK, so 64 bit arithmetic might take a few extra clock cycles on a 32 bit machine, but this is unlikely to be significant.  (Or even relevant ... in your use-case.)  For instance, the x86 instruction sets have 64 bit arithmetic instructions.

Does that make this a bad idea?

Not for the reason you stated.  It could be a bad idea for other reasons.  (For instance, if there is more information that you can encode in 64 bits then your scheme breaks down.)

How common are 32 bit servers, and do we expect them to slowly disappear completely?

They are still common, and they are likely to continue indefinitely.  If you don't actually need more than 2^30 of address space for an application, then 32 bit pointers occupy less memory than 64 bit pointers ... so a "small" model architecture is going to be more power efficient, etc.

I also agree with @DocBrown.  Error numbers introduce all sorts of problems of their own ... including the tendency to display unintelligible sequences of digits to end users.  The human friendly approach is a well named exception, and an intelligible / informative exception message.

The other observation is that your question shows the signs of "premature optimization".  The chances are that the real impact on performance of your proposed optimization will be insignificant, and possibly even too small to measure in a real application running under realistic conditions.

The standard advice is to not waste your time on this kind of thing ... unless you have concrete evidence (from measuring your application) that 1) the effort of optimization is warranted, and 2) this particular bit of code has a significant impact on your application's overall performance.

Title: Using error numbers which only work on 64 bit servers: a bad idea?

Body:
In an attempt to solve one problem I encountered another. I would like to have an easy and memorable way of creating unique error numbers, across projects and across developers. The scheme I came up with was to use the initials of the developer, find their position in the alphabet, and append the date and time.
Example: lets say the developer Mark Elliot Zuckerberg (initials MEZ) writes code that throws an exception on Feb 8th 2014 at 12:54AM. The error code would be: 8526020820140054

This works brilliantly on 64 bit machines, but the resulting integer is too large for 32 bit computers. Does that make this a bad idea? How common are 32 bit servers, and do we expect them to slowly disappear completely?


问:
When subclassing is it better to "Copy Paste, then Refactor", or "Refactor, then Implement"
I currently have a class Foo,
i've decided I need a second type of Foo where I want to test out a significantly different implementation. It will no doubt share some functionality with Foo so I'll need to create a Abstract Class parent for both of them.

At the end of the process I want to have:

AbstractFoo: an abstract class

FooBoo: functionaly identical to the original Foo

FooBar: the new subclass of AbstractFoo I've created.

There are two ways I could go about this:

Copy Paste, then Refactor

Create a copy of Foo, and name it FooBar and rename Foo to FooBoo

Edit FooBar with the new implementation

Inspect, FooBar and FooBoo, move methods that are the same between them into a abstract class AbstractFoo, which both inherit from

Refactor, then Implement

Rename Foo, FooBoo

Consider what methods are not related to the part of the implementation that FooBoo and FooBaz are going to be different in. Move these to AbstractFoo

Create FooBaz and reimplement all the methods that remain within FooBoo

Which is to be preferred?
*Is there another method?*

Last time I had to do this, it was because the I decided that Foo had 2 different modes, that was determined by a boolean passed into the constructor.

This time (on a different class), it is because I want to try out using a different engine underneath that might be faster.
I want to keep FooBoo around because it has a subclass that I think will be much harder to implement for FooBaz, and I also want to be able to check that in the end they behave the same.

答:
I would do it this way:

Rename Foo to AbstractFoo and make it abstract

Create FooBoo that derives from AbstractFoo

Push down all methods from AbstractFoo to FooBoo leaving behind only abstract methods

Implement FooBar

I like this because most of it can be achieved using refactor functions of IDE. This makes sure that you don't have to manually change code where Foo was used. Also, compiler gives you errors in places where you used Foo's constructor, because it cannot instantiate abstract class.


答:
Hard to say, it depends on the case, what approach makes the most sense.

If most of the stuff is going into the base class, I'd either use your "Refactor, then Implement" approach, or follow a slightly changed variant of @Euphorics' approach: I would make sure everything works as before after his Step 3 (completed AbstractFoo and FooFoo) and before moving on to his Step 4 (creating FooBar).

In some cases, it is the other way round. You decide for a common base class, which actually will have only a few methods from old Foo. In that case, rename Foo to FooFoo, create an empty AbstractFoo and move just the few methods into the new base (don't forget to change FooFoos inheritance).

I have also used the "copy + paste + refactor" approach. It can be useful, when the methods to move to the base compared to the methods that need to stay in FooBoo are around 50:50 distribution. Again, it depends, and sometimes you'll find during refactoring, that you need another class to extract things from the Foo class family.

Title: When subclassing is it better to "Copy Paste, then Refactor", or "Refactor, then Implement"

Body:
I currently have a class Foo,
i've decided I need a second type of Foo where I want to test out a significantly different implementation. It will no doubt share some functionality with Foo so I'll need to create a Abstract Class parent for both of them.

At the end of the process I want to have:

AbstractFoo: an abstract class

FooBoo: functionaly identical to the original Foo

FooBar: the new subclass of AbstractFoo I've created.

There are two ways I could go about this:

Copy Paste, then Refactor

Create a copy of Foo, and name it FooBar and rename Foo to FooBoo

Edit FooBar with the new implementation

Inspect, FooBar and FooBoo, move methods that are the same between them into a abstract class AbstractFoo, which both inherit from

Refactor, then Implement

Rename Foo, FooBoo

Consider what methods are not related to the part of the implementation that FooBoo and FooBaz are going to be different in. Move these to AbstractFoo

Create FooBaz and reimplement all the methods that remain within FooBoo

Which is to be preferred?
*Is there another method?*

Last time I had to do this, it was because the I decided that Foo had 2 different modes, that was determined by a boolean passed into the constructor.

This time (on a different class), it is because I want to try out using a different engine underneath that might be faster.
I want to keep FooBoo around because it has a subclass that I think will be much harder to implement for FooBaz, and I also want to be able to check that in the end they behave the same.


问:
How to represent an agile project to people focused on waterfall
Our team has been asked to represent our development efforts in a project plan. No one is unhappy with our work or questioning our ability to deliver, we are just participating in an IT cattle call for project plans. Trouble is we are an agile team and haven't thought about our work in terms of a formal project plan.

While we have a general idea of what we are working on next we aren't 100% sure until we plan an iteration. Until now our team has largely operated in a vacuum and has not been required to present our methodology or metrics to outside parties. We follow most of the practices espoused in Extreme Programming.

We hold quarterly planning meetings to have a general idea of the stories we are going to work on for a quarter. That said, our stories are documented on 3x5 cards and are only estimated at the beginning of the iteration in which they are going to be worked. After estimation we document the story in Team Foundation Sever. During an iteration, we attach code to stories and mark stories as completed once finished. From this data we are able to generate burn down and velocity charts. Most importantly we know our average velocity for an iteration keeping us from biting off more than we can chew.

I am not looking to modify the way we do development but want to present our development activities in a report that someone only familiar with waterfall will understand. In What Does an Agile Project Plan Look Like, Kent McDonald does a good job laying out the differences between agile and waterfall project plans. He specifies the differences in consumable bullets:

An agile project plan is feature based

An Agile Project Plan is organized into iterations

An Agile Project Plan has different levels of detail depending on the time frame

An Agile Project Plan is owned by the Team

Being able to explain the differences is great, but how best to present the data?

答:
I had to do this, once.
The Team wanted to do Agile, the Client wanted (and understood Agile),
a external 3rd Party (call them "Auditors"), wanted to see Waterfall reports.

An important reason why we could Lie was because the 3rd Party didn't actually care,
they just wanted to check boxes. If the Client was happy and the Team was happy the "Auditors" would hardly go back and look at the reports we gave them, prior to checking off the final boxes.

Don't do this if the 3rd Party matters and ACTUALLY cares that you are using waterfall. If the Auditors know you are being Agile, and just haven't updated their paperwork to support you -- then you can Lie.

What do you do?
Lie, but white lie.

Rephrase Features, as requirement "Must have Feature".

Your work is in Iterations, iterations generally go over X weeks, a waterfall plan likes to see things generally in Weeks, so no big issue. You can label the end of each iteration as a Milestone. Milestones are waterfall. Iterations tend to have a theme (or an associated Epic) so you can stick the theme/epic title on the the milestone (eg. 21/11 Have GUI complete.)

Calculate your velocity (from your burn down/up charts) and work out how much time a Story Point, on average, represents (at least at your current velocity), this will give you task durations. Often wildy inaccurate ones, but they will be meaningful to an extent.

Your plan has different level of detail depending on timeframe - basically the same for waterfall. Possible differer a waterfall plan has different detail depending on Audience.

An Agile plan is owned by the Team. A waterfall plan is owned by the Project Manager. You've provably got a Project Manager already, and they are probably doing this translation. They should take ownership of this translated document and shield the team from the flack that might come raining down upon them because of it. It is the job of a Agile or Waterfall Project Manager to shield the team from distractions that will stop them from working.

Sure you don't really know what you are doing next iteration, but you do know roughly what you are doing. You've got a feel for it, and a rougher still the Iteration after. (I've heard this called the Iteration Radar). Lie and say you do. and when lie through your teeth about story card that isn't on your Iteration Radar, and just put it in somewhere. Hope you don't have to submit too many updates on the project plan, or they will notice that you haven't done what you said you will.

Basically this is a pain.
Translation will be many hours of work.
If you have to do it a lot, automate it.


答:
I would like to have a [...] way of creating unique error numbers, across projects and across developers.

IMHO that is the bad idea. You should avoid the need for having a global unique error number across project boundaries. That is a global requirement you cannot fulfill as soon as you need to add third-party components, and at the long run, it will also be hard to enforce such a rule across many projects and many developers. So better design your system in a way you can manage your error numbers locally, this will give you much more flexibility and does not couple unrelated projects together with obstructive rules.

How your indivual projects manage their error numbers then is up to them, but I am pretty sure they will find a way to keep them below 32 bits.