问:
Haskell: Best tools to validate textual input?
In Haskell, there are a few different options to "parsing text". I know of Alex & Happy, Parsec and Attoparsec. Probably some others.

I'd like to put together a library where the user can input pieces of a URL (scheme e.g. HTTP, hostname, username, port, path, query, etc.) I'd like to validate the pieces according to the ABNF specified in RFC 3986.

In other words, I'd like to put together a set of functions such as:

```<code>validateScheme    :: String -> Bool
validateUsername  :: String -> Bool
validatePassword  :: String -> Bool
validateAuthority :: String -> Bool
validatePath      :: String -> Bool
validateQuery     :: String -> Bool
</code>```

What is the most appropriate tool to use to write these functions?

Alex's regexps is very concise, but it's a tokenizer and doesn't straightforwardly allow you to parse using specific rules, so it's not quite what I'm looking for, but perhaps it can be wrangled into doing this easily.

I've written Parsec code that does some of the above, but it looks very different from the original ABNF and unnecessarily long.

So, there must be an easier and/or more appropriate way. Recommendations?

答:
I'm curious why Parsec was so long, I'd write it something like

```<code>data URL = URL { scheme, hostname, username, port, path, query :: String}

parser :: String -> Either ParseError URL
parser = flip parse "Foo" $ Parser <$> parseScheme <*> parseHostname <*> parseUsername ...

validators = [validateScheme . scheme, validateHostname . hostname, .....]
validate :: URL -> Bool
validate url = all ($url) validators
</code>```

This is nice and concise looking to me. As for how to implement the parser, it's a straightforward to parse each section and then apply URL to each piece.

Body:
I'm curious why Parsec was so long, I'd write it something like

data URL = URL { scheme, hostname, username, port, path, query :: String}

parser :: String -> Either ParseError URL
parser = flip parse "Foo" $ Parser <$> parseScheme <*> parseHostname <*> parseUsername ...

validators = [validateScheme . scheme, validateHostname . hostname, .....]
validate :: URL -> Bool
validate url = all ($url) validators

This is nice and concise looking to me. As for how to implement the parser, it's a straightforward to parse each section and then apply URL to each piece.


问:
How do you cope with ugly code that you wrote?
So your client asks you to write some code, so you do. He then changes the specs on you, as expected, and you diligently implement his new features like a good little lad. Except... the new features kind of conflict with the old features, so now your code is a mess. You really want to go back and fix it, but he keeps requesting new things and every time you finish cleaning something, it winds up a mess again.

What do you do? Stop being an OCD maniac and just accept that your code is going to wind up a mess no matter what you do, and just keep tacking on features to this monstrosity? Save the cleaning for version 2?

答:
1) Proper change control is your friend

If the customer changes the specification that's fine, that's his right, however it is a change and it needs to be charged for (or costed in whatever manner is appropriate to the project structure / relationship).

The estimate for that change should include the cost of the necessary refactoring.  The client may well baulk at what seems to be a high cost but at that point you need to explain to him that because the code is already half written there are elements that need to be rewritten to ensure it's robust and supportable in the future and that if it's not done then he's likely to have problems down the line with future support or changes becoming even more expensive.

2) Refactoring Should Be Done Such That Is Provides Genuine Long Term Benefit to the Client

When considering refactoring you always need to consider what's actually needed and what's important and ensure that the refactoring work provides genuine long term value for money.

After all, we should do these things so the code remains extendable and supportable in the medium / long term to ensure that the client's investment remains valid rather than out of any drive for theoretical perfection.  Refactoring work (and the corresponding estimates) should be done with this as the scope, and not just because you now think there might be a slightly better way to do it.

ContentLicense: CC BY-SA 2.5


问:
What's the best/most efficent way to create a semi-intelligent AI for a tic tac toe game?
basically I am attempting to make a a efficient/smallish C game of Tic-Tac-Toe. I have implemented everything other then the AI for the computer so far. my squares are basically structs in an array with an assigned value based on the square. For example

```<code>s[1].value = 1;
</code>```

therefore it's a x, and then a value of 3 would be a o. My question is whats the best way to create a semi-decent game playing AI for my tic-tac-toe game? I don't really want to use minimax, since It's not what I need. So how do I avoid a a lot of if statments and make it more efficient.

Here is the rest of my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct state{ // defined
    int state; // 0 is tie, 1 is user loss, 2 is user win, 3 is ongoing game
    int moves;
};

struct square{ // one square of the board
    int value; // 1 is x, 3 is o
    char sign; // no space used
};

struct square s[9]; //set up the struct
struct state gamestate = {0,0}; //nothing

void setUpGame(){ // setup the game
    int i = 0;
    for(i = 0; i < 9; i++){
        s[i].value = 0;
        s[i].sign = ' ';
    }
    gamestate.moves=0;
    printf("\nHi user! You're \"x\"! I'm \"o\"! Good Luck :)\n");
}

void displayBoard(){// displays the game board
    printf("\n %c | %c | %c\n", s[6].sign, s[7].sign, s[8].sign);
    printf("-----------\n");
    printf(" %c | %c | %c\n", s[3].sign, s[4].sign, s[5].sign);
    printf("-----------\n");
    printf(" %c | %c | %c\n\n", s[0].sign, s[1].sign, s[2].sign);
}

void getHumanMove(){ // get move from human
    int i;
    while(1){
        printf(">>:");
        char line[255]; // input the move to play
        fgets(line, sizeof(line), stdin);
            while(sscanf(line, "%d", &i) != 1) { //1 match of defined specifier on input line
            printf("Sorry, that's not a valid move!\n");
            fgets(line, sizeof(line), stdin);
        }
        if(s[i-1].value != 0){printf("Sorry, That moves already been taken!\n\n");continue;}
        break;
    }
    s[i-1].value = 1;
    s[i-1].sign = 'x';
    gamestate.moves++;
}

int sum(int x, int y, int z){return(x*y*z);}

void getCompMove(){ // get the move from the computer

}

void checkWinner(){ // check the winner
    int i;
    for(i = 6; i < 9; i++){ // check cols
        if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
        if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
    }
    for(i = 0; i < 7; i+=3){ // check rows
        if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
        if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
    }
    if((sum(s[0].value,s[4].value,s[8].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
    if((sum(s[0].value,s[4].value,s[8].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
    if((sum(s[2].value,s[4].value,s[6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
    if((sum(s[2].value,s[4].value,s[6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
}

void playGame(){ // start playing the game
    gamestate.state = 3; //set-up the gamestate
    srand(time(NULL));
    int temp = (rand()%2) + 1;
    if(temp == 2){ // if two comp goes first
        temp = (rand()%2) + 1;
        if(temp == 2){
            s[4].value = 2; s[4].sign = 'o';
            gamestate.moves++;
        }else{
            s[2].value = 2; s[2].sign = 'o';
            gamestate.moves++;
        }
    }
    displayBoard();
    while(gamestate.state == 3){
        if(gamestate.moves<10);
            getHumanMove();
        if(gamestate.moves<10);
            getCompMove();
        checkWinner();
        if(gamestate.state == 3 && gamestate.moves==9){
            printf("The game is a tie :p\n");
            break;
        }
        displayBoard();
    }
}

int main(int argc, const char *argv[]){
    printf("Welcome to Tic Tac Toe\nby The Elite Noob\nEnter 1-9 To play a move, standard numpad\n1 is bottom-left, 9 is top-right\n");
    while(1){ // while game is being played
        printf("\nPress 1 to play a new game, or any other number to exit;\n>>:");
        char line[255]; // input whether or not to play the game
        fgets(line, sizeof(line), stdin);
        int choice; // user's choice about playing or not
        while(sscanf(line, "%d", &choice) != 1) { //1 match of defined specifier on input line
            printf("Sorry, that's not a valid option!\n");
            fgets(line, sizeof(line), stdin);
        }
        if(choice == 1){
            setUpGame(); // set's up the game
            playGame(); // Play a Game
        }else {break;} // exit the application
    }
    printf("\nThank's For playing!\nHave a good Day!\n");
    return 0;
}
</code>```

答:
If one represents X as +1 and O as -1 on a 3x3 matrix, a necessary move is one where the absolute value of the sum of the values on the line is 2.  An unnecessary play is into the 3rd spot where the value is 0.

Thus, takes the state of the board, and examines each line and places the empty spots on that line in one of three lists:

necessary

ok

unnecessary

Then the algorithm picks a random play from one of the lists in order of necessity.  An improvement for slightly more intelligent play would be to bias this selection based on the number of times the play exists in the list (this will cause it to tend to play to the center (4 possible lines) and corners (3 possible lines) over the edges (2 possible lines).

```
O | X |
--+---+--
  | X |
--+---+--
  |   |
```

Would become:

```
    1  2  0  1
    |  |  | /
T  -1| 1 |  - 0
   --+---+--
C    | 1 |  - 1
   --+---+--
B    |   |  - 0
    L  c  R \ 0
```

In this situation, the empty spot in the center column would be played in because its value is 2.  As this is O to play, this would be a block.

The full set of moves and grouping for this board state would be:

```
Necessary:
  Bc (1)
Ok:
  TR (1)
  CL (2)
  CR (1)
  BL (2)
Unnecessary:
  TR (2)
  CR (1)
  BL (1)
  Bc (1)
  BR (3)
```

Note that a single cell may very well fall into multiple groupings (Bottom Center Bc is both necessary to play to win/block, but it is also unnecessary to play on the bottom row as it will not contribute to a winning or blocking play on that row).

The key here is that it identifies the obvious plays but doesn't do any look ahead for what board position is strongest later (it doesn't have any preference to play the known strategies for winning with X or forcing a draw with O).  It will attempt to block or win obvious setups - if you don't block it when its placed two on a line, it will attempt to win (unless you also have a win possible in which case it may decide to block rather than win).

Note that this is almost a byproduct of detecting the winning conditions for the board, as that would have a row, column, or diagonal that has an absolute value of its values of 3.

ContentLicense: CC BY-SA 3.0

Body:
If one represents X as +1 and O as -1 on a 3x3 matrix, a necessary move is one where the absolute value of the sum of the values on the line is 2.  An unnecessary play is into the 3rd spot where the value is 0.

Thus, takes the state of the board, and examines each line and places the empty spots on that line in one of three lists:

necessary

ok

unnecessary

Then the algorithm picks a random play from one of the lists in order of necessity.  An improvement for slightly more intelligent play would be to bias this selection based on the number of times the play exists in the list (this will cause it to tend to play to the center (4 possible lines) and corners (3 possible lines) over the edges (2 possible lines).

O | X |
--+---+--
  | X |
--+---+--
  |   |

Would become:

    1  2  0  1
    |  |  | /
T  -1| 1 |  - 0
   --+---+--
C    | 1 |  - 1
   --+---+--
B    |   |  - 0
    L  c  R \ 0

In this situation, the empty spot in the center column would be played in because its value is 2.  As this is O to play, this would be a block.

The full set of moves and grouping for this board state would be:

Necessary:
  Bc (1)
Ok:
  TR (1)
  CL (2)
  CR (1)
  BL (2)
Unnecessary:
  TR (2)
  CR (1)
  BL (1)
  Bc (1)
  BR (3)

Note that a single cell may very well fall into multiple groupings (Bottom Center Bc is both necessary to play to win/block, but it is also unnecessary to play on the bottom row as it will not contribute to a winning or blocking play on that row).

The key here is that it identifies the obvious plays but doesn't do any look ahead for what board position is strongest later (it doesn't have any preference to play the known strategies for winning with X or forcing a draw with O).  It will attempt to block or win obvious setups - if you don't block it when its placed two on a line, it will attempt to win (unless you also have a win possible in which case it may decide to block rather than win).

Note that this is almost a byproduct of detecting the winning conditions for the board, as that would have a row, column, or diagonal that has an absolute value of its values of 3.


问:
Do I have to release the code of a MIT licensed software running a GPL library?
Lets say I'm using Node-Webkit, an MIT licensed app runtime. Now, let's say I decide to include a Javascript library which is GPL licensed: while I do not modify the downloaded JS file, I do write my own code making use of the library's functions. I plan to sell the final obfuscated executable and I'm wondering: what's the final license of the complete software? Do I only have to release the GPL library or does the GPL license apply for all the code I wrote? What happens to Node-Webkit's MIT license?</p>

答:
This is a question for your attorney.

I am not an attorney, and more importantly I'm not your attorney. This is not legal advice. This is merely my rumination on the topic.

The effect of the GPL on your code depends on the definition of the GPL's concept of linking and derivative works. Because this is JavaScript, the matter of linking is not entirely clear. But if your code uses the GPL'd library, then your program as a whole is dependent on it and is therefore bound by the terms of the GPL. Under those terms, any user can demand the full, unobfuscated source code (under the GPL requirement of source code being in the "preferred form of the work for making modifications"), and you are required to convey it.

If you wish to distribute your work under a "proprietary license," and in an obfuscated form, then your work will be in violation of the GPL if you include any GPL code and do not also offer the full original source code for your project.


问:
Desktop GUI Client - Remote RDBMS communication
Sorry if I am asking a trivial question but I have been searching for a while without any luck. I need to design a system and I am looking for advice on the technology that should be used.

The layout is very simple: it is a sales application with a centralized database and multiple clients. Each salesperson has GUI app installed on his/her laptop that should be able to connect to the database to retrieve data and upload data (i.e. register new orders).

My question is the following: how should the communication between the client and the server be implemented? I doubt that connecting directly to the RDBMS is a good idea... Should I use web-services? XML-RPC? How to implement authentication and encode the data?

Thanks for your advice!

答:
Based on what you are describing, a simple REST style interface should be more than sufficient.  You'd compile the orders up into a chunk of XML, and post it to your server to add them.  You can also respond to gets, puts, and deletes.  Most desktop langauges/tools should have the necessary client libraries available for this.

Any of the more common server side languages would be suitable for the corresponding server piece.  To secure the connection, set up SSL on the web server.  For authorization purposes (in app rights), there's a couple options.  You may want to look into how OAuth2 works.  Or pass the credentials on as part of the HTTP request.


问:
Design pattern for an ASP.NET project using Entity Framework
I'm building a website in ASP.NET (Web Forms) on top of an engine with business rules (which basically resides in a separate DLL), connected to a database mapped with Entity Framework (in a 3rd, separate project).

I designed the Engine first, which has an Entity Framework context, and then went on to work on the website, which presents various reports. I believe I made a terrible design mistake in that the website has its own context (which sounded normal at first).

I present this mockup of the engine and a report page's code behind:

Engine (in separate DLL):

```<code>public Engine
{
    DatabaseEntities _engineContext;

    public Engine()
    {
       // Connection string and procedure managed in DB layer
        _engineContext = DatabaseEntities.Connect();
    }

    public ChangeSomeEntity(SomeEntity someEntity, int newValue)
    {
        //Suppose there's some validation too, non trivial stuff
        SomeEntity.Value = newValue;
        _engineContext.SaveChanges();
    }
}
</code>```

And report:

```<code>public partial class MyReport : Page
{
    Engine _engine;
    DatabaseEntities _webpageContext;

    public MyReport()
    {
        _engine = new Engine();
        _databaseContext = DatabaseEntities.Connect();
    }

    public void ChangeSomeEntityButton_Clicked(object sender, EventArgs e)
    {
        SomeEntity someEntity;
        //Wrong way:
        //Get the entity from the webpage context
        someEntity = _webpageContext.SomeEntities.Single(s => s.Id == SomeEntityId);
        //Send the entity from _webpageContext to the engine
        _engine.ChangeSomeEntity(someEntity, SomeEntityNewValue); // <- oops, conflict of context

        //Right(?) way:
        //Get the entity from the engine context
        someEntity = _engine.GetSomeEntity(SomeEntityId); //undefined above
        //Send the entity from the engine's context to the engine
        _engine.ChangeSomeEntity(someEntity, SomeEntityNewValue); // <- oops, conflict of context
     }
}
</code>```

Because the webpage has its own context, giving the Engine an entity from a different context will cause an error. I happen to know not to do that, to only give the Engine entities from its own context. But this is a very error-prone design. I see the error of my ways now. I just don't know the right path.

I'm considering:

Creating the connection in the Engine and passing it off to the webpage. Always instantiate an Engine, make its context accessible from a property, sharing it. Possible problems: other conflicts? Slow? Concurrency issues if I want to expand to AJAX?

Creating the connection from the webpage and passing it off to the Engine (I believe that's dependency injection?)

Only talking through ID's. Creates redundancy, not always practical, sounds archaic. But at the same time, I already recuperate stuff from the page as ID's that I need to fetch anyways.

What would be best compromise here for safety, ease-of-use and understanding, stability, and speed?

答:
I don't think you are a million miles away from where you need to be.

What you need to do really depends on the level of abstraction that you need and what you foresee the future of this application to be.

You definitely do not want to be using multiple contexts in a single http request. That will cause you a lot of pain.

As a bare minimum I would alter your Engine to have the context dependency injected in (through the constructor or setter). That will allow you to isolate the engine for testing purposes by injecting in a mocked context.

I would then consider creating a BasePage class that new ups an Engine Instance in the constructor (passing in a new Context). Each subsequent page would then inherit from the BasePage and would therefore have an Engine instance by default.

I would then work on the Engine class to provide all the functionality that your pages require (possibly sub-classing if it starts to get a bit monolithic). You then make sure that all interaction between the UI and the underlying database is channelled through the Engine. This way you could extend the Engine as required say for instance Engine.Ajax.Get... or something along those lines.

Like I say the level of abstraction you require may reveal other design considerations that you will need to make. You may wish to implement a repository and unit of work pattern on top of the context (technically an EF context already gives you this but if you are not sure about sticking with EF or know that you will need to introduce alternative data access options then you will need to consider it).

If you are injecting dependencies and those dependencies are 'volatile' then you may look to use an Inversion of Control Container such as AutoFac or Windsor.


答:
I would guess you have a reason for using WebForms rather than MVC but my first tip would be this: If you possibly can, use ASP.Net MVC.

Right, Got that off my chest, lets continue.

You are right to suspect your architecture, having your entity store and then a second way of directly accessing your database when using Entity Framework is a big no-no. The simple rule to consider is this: Only one way to and from the database.

Even if you're stuck with a tired technology like WebForms, you can still take a useful page out of the MVC book by using the MVC architecture. You're half way there with your Engine which sounds like it is doing most of the work of the Model layer. In fact it sounds to me like you want to go a little further and use a ViewModel type approach - a ViewModel behaves like a Model, but has extra things that make it easier to work with from the front end, so it effectively behaves as a DTO, but if there are any  properties you don't want to be able to write on the front end or other view related logic it goes in the ViewModel class.

Then you make sure your entity layer can take a ViewModel object ( or probably you create an interface for your entities so if you had a BookRecord object you would create an IBookRecord interface that the BookRecord entity would implement and the BookRecordViewModel would also implement. If possible it is always nicer to pass around interfaces and it really facilitates DI, mocking and all that good stuff that helps build resilience in general.

The only real difference this makes is that you will have to handle logic to manage updates in your engine - when you push down a BookRecordViewModel from the interface you will need to check whether it has an Id field set and if it does query and update, if not add it as a new record. You may well have that all implemented already in your Engine project, in which case this should present no problem at all.

Title: Design pattern for an ASP.NET project using Entity Framework

Body:
I'm building a website in ASP.NET (Web Forms) on top of an engine with business rules (which basically resides in a separate DLL), connected to a database mapped with Entity Framework (in a 3rd, separate project).

I designed the Engine first, which has an Entity Framework context, and then went on to work on the website, which presents various reports. I believe I made a terrible design mistake in that the website has its own context (which sounded normal at first).

I present this mockup of the engine and a report page's code behind:

Engine (in separate DLL):

```<code>public Engine
{
    DatabaseEntities _engineContext;

    public Engine()
    {
       // Connection string and procedure managed in DB layer
        _engineContext = DatabaseEntities.Connect();
    }

    public ChangeSomeEntity(SomeEntity someEntity, int newValue)
    {
        //Suppose there's some validation too, non trivial stuff
        SomeEntity.Value = newValue;
        _engineContext.SaveChanges();
    }
}
</code>```

And report:

```<code>public partial class MyReport : Page
{
    Engine _engine;
    DatabaseEntities _webpageContext;

    public MyReport()
    {
        _engine = new Engine();
        _databaseContext = DatabaseEntities.Connect();
    }

    public void ChangeSomeEntityButton_Clicked(object sender, EventArgs e)
    {
        SomeEntity someEntity;
        //Wrong way:
        //Get the entity from the webpage context
        someEntity = _webpageContext.SomeEntities.Single(s => s.Id == SomeEntityId);
        //Send the entity from _webpageContext to the engine
        _engine.ChangeSomeEntity(someEntity, SomeEntityNewValue); // <- oops, conflict of context

        //Right(?) way:
        //Get the entity from the engine context
        someEntity = _engine.GetSomeEntity(SomeEntityId); //undefined above
        //Send the entity from the engine's context to the engine
        _engine.ChangeSomeEntity(someEntity, SomeEntityNewValue); // <- oops, conflict of context
     }
}
</code>```

Because the webpage has its own context, giving the Engine an entity from a different context will cause an error. I happen to know not to do that, to only give the Engine entities from its own context. But this is a very error-prone design. I see the error of my ways now. I just don't know the right path.

I'm considering:

Creating the connection in the Engine and passing it off to the webpage. Always instantiate an Engine, make its context accessible from a property, sharing it. Possible problems: other conflicts? Slow? Concurrency issues if I want to expand to AJAX?

Creating the connection from the webpage and passing it off to the Engine (I believe that's dependency injection?)

Only talking through ID's. Creates redundancy, not always practical, sounds archaic. But at the same time, I already recuperate stuff from the page as ID's that I need to fetch anyways.

What would be best compromise here for safety, ease-of-use and understanding, stability, and speed?


问:
Why do we use to talk about addresses and memory of variable in C?
Why do we use to talk about addresses and memory of variable in C, where in other languages (like in Java, .Net etc) we do not talk about variable address and memory in a program, we will directly use the variables.

But in C Language we are listening the word address and memory.

How to explain this?

I hope C is high level language designed over the assembly language. So C is a thin layer over assembly language (in assembly language we will use memory locations to store a variable and track a variable). But in other languages these addresses and memory related things are wrapped in that specific language, so that we will not listen these words.

答:
There wasn't a garbage collector for C. If there's no GC then
programmers need to allocate/deallocate memory themselves. A good
example is Objective-C, which until it gained a GC, programmers are
responsible to manage memory use.

There was pointer before references. It's like references but you can point it wherever you like, so there was no safety.

Liberal type casting, you can allocate a data type and treat it as a space in memory or another kind of data type.


答:
I believe these are the options to consider:

Java applications (SWING or SWT). Plenty of libraries like Spring and Hibernate for building multi-tiered architectures, excellent database connectivity.

Qt. Crossplatform, can work with data.

Web application with offline support.

Title: Desktop GUI Client - Remote RDBMS communication

Body:
Sorry if I am asking a trivial question but I have been searching for a while without any luck. I need to design a system and I am looking for advice on the technology that should be used.

The layout is very simple: it is a sales application with a centralized database and multiple clients. Each salesperson has GUI app installed on his/her laptop that should be able to connect to the database to retrieve data and upload data (i.e. register new orders).

My question is the following: how should the communication between the client and the server be implemented? I doubt that connecting directly to the RDBMS is a good idea... Should I use web-services? XML-RPC? How to implement authentication and encode the data?

Thanks for your advice!


答:
If security is an issue then you should consider the whole WS* web services SOA stack.

The specification is pretty daunting, and the , WSDL xml is frankly scary, however the complexity arises from the number of scenarios covered (different transports, different authentication methods, anti tampering, non-repudation etc. etc. ).

The good news is you mostly do not have to deal with this complexity most development environments have extensive and mature tooling and library support.

So a fairly simple WS service would more than cover your current requirements and any future requirements.


问:
Is it possible to implement an infinite IEnumerable without using yield with only C# code?

Motivation

The main idea is to explore and understand the limits of how far one can go with the basic LINQ primitives (Select, SelectMany, Concat, etc.). These primitives can all be considered functional operations on a theoretical sequence type. Taking examples from Haskell:

Select 'lifts' a function into the sequence (like fmap in Haskell)

Concat is composition

Aggregate is the sequence type's catamorphism (fold)

SelectMany 'extracts' information from the sequence (the Monad bind, >>= operation)

etc. (and I'm sure there are better abstractions for the above)

So the question is whether or not the basic sequence (Enumerable) operations in C# are enough to construct an infinite sequence. More concretely it is the following problem:

Problem

I'm curious to know if there's a way to implement something equivalent to the following, but without using yield:

```<code>IEnumerable<T> Infinite<T>()
{
    while (true) { yield return default(T); }
}
</code>```

Is it possible to do sue using the built-in LINQ operators only?

The short answer is that theoretically yes, but practically not because of how Linq is implemented (causing stack overflows).

That's why here are less restrictive rules:

Rules

Alternatively a less restrictive question would go by the rules

You can't use the yield keyword directly

Use only C# itself directly - no IL code, no constructing dynamic assemblies etc.

You can only use the basic .NET lib (only mscorlib.dll, System.Core.dll? not sure what else to include). However if you find a solution with some of the other .NET assemblies (WPF?!), I'm also interested.

Don't implement IEnumerable or IEnumerator.

Notes

An example theoretically correct definition is:

```<code>IEnumerable<int> infinite = null;
infinite = new int[1].SelectMany(x => new int[1].Concat(infinite));
</code>```

This is "correct" but hits a StackOverflowException after 14399 iterations through the enumerable (not quite infinite).

I'm thinking there might be no way to do this due to the C#'s compiler lack of tail recursion optimization. A proof would be nice :)

答:
Here is a practically infinite iterator:</p>

```<code>using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var infiniteIterator =
            Enumerable.Range(Int32.MinValue, Int32.MaxValue)
                      .SelectMany(i => Enumerable.Range(Int32.MinValue, Int32.MaxValue))
                      .SelectMany(i => Enumerable.Range(Int32.MinValue, Int32.MaxValue))
                      .SelectMany(i => Enumerable.Range(Int32.MinValue, Int32.MaxValue))
                      .Select(i => default(int));

        foreach (var infinite in infiniteIterator)
            Console.WriteLine(infinite);
    }
}
</code>```

Body:
Here is a practically infinite iterator:

using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var infiniteIterator =
            Enumerable.Range(Int32.MinValue, Int32.MaxValue)
                      .SelectMany(i => Enumerable.Range(Int32.MinValue, Int32.MaxValue))
                      .SelectMany(i => Enumerable.Range(Int32.MinValue, Int32.MaxValue))
                      .SelectMany(i => Enumerable.Range(Int32.MinValue, Int32.MaxValue))
                      .Select(i => default(int));

        foreach (var infinite in infiniteIterator)
            Console.WriteLine(infinite);
    }
}


问:
Design pattern to handle queries using multiple models
I am presented with a dilemma while trying to re-designing the class structure for my PHP/MySQL application to make it more elegant and conform it to the SOLID principle.

The problem goes like this:

Let as assume, there is an abstract class called person which has certain properties to define a generic person, such as name, age, date of birth etc.

There are two classes, student, and teacher, that implements this abstract class. They add their own unique properties to it.

I have designed all the three classes to include all the operational logic (details of which are not relevant in context of the question).

Now, I need to create views/reports/data grids which contain details from multiple classes, for example, say, a list of all students doing projects in Chemistry mentored by a teacher whose name is the parameter to the query.

This is just one example of a view, there are many different views in the application, which uses data from 3-4 tables, and each of them have multiple input parameters to generate them.

Considering this particular example, I have written the relevant query using JOIN and the results are as expected and proper, now here is the dilemma:

Keeping in mind the single responsibility principle, where should I keep this query? It does not belong to either Student class, or Teacher class or any other classes currently present.

a) Should I create a new class, say dataView class, and design it as a MVC pattern and keep the query there? What about the other views? how do they fit in this architecture?

b) Should I not keep the query in code at all, and make it DB View ?

c) Am I completely wrong in the approach? If so what is the right approach?

My considerations are as follows:

a) should be easy to add new views later on if requirement comes, without having to copy-paste-modify code

b) would like to make it as loosely coupled as possible so that if minor db structure changes happen, it does not break

I did google searches on report design and OOP report generators, but all the result seem to focus on the visual design of the report rather than fetching the data. I have already taken care of the visual aspect of the report using MVC with html templates.

I am sure this is a very fundamental problem with known solution, but I am somehow not able to find it (maybe searching with wrong keyword).

Edit1: Modified the title to make it more relevant

Edit2: The accepted answer got me thinking in the right direction and identify my design flaws, which eventually led me to find this question and the solution in Stack Overflow which gave me the detailed answer to clear the confusion.

答:
Well, if i understand the query, your dilemma is where to put this query and not whether the query is to be put in a model class considering you are following MVC pattern.

My take:
If you see the query, you are ultimately fetching students. Fetching students can be based on projects, male, female, class, age, teachers etc.

I feel, the model should be student_model.php which has various methods, where in your query would go

eg:
fetchMaleStudents(), fetchFemaleStudents(), fetchStudentsForProjects(projectName), fetchStudentsForTeacher(teachersName) and so on.


问:
How to approach scrum task burn down when tasks have multiple peoples involvement?
In my company, a single task can never be completed by one individual. There is going to be a separate person to QA and Code Review each task. What this means is that each individual will give their estimates, per task, as to how much time it will take to complete.

The problem is, how should I approach burn down? If I aggregate the hours together, assume the following estimate:

10 hrs - Dev time

4  hrs - QA

4  hrs - Code Review.

Task Estimate = 18hrs

At the end of each day I ask that the task be updated with "how much time is left until it is done". However, each person generally just thinks about their part of it. Should they mark the effort remaining, and then ADD the effort estimates to that? How are you guys doing this?

UPDATE

To help clarify a few things, at my organization each Task within a story requires 3 people.

Someone to develop the task. (do unit tests, ect...)

A QA specialist to review task (they primarily do integration and regression tests)

A Tech lead to do code review.

I don't think there is a wrong way or a right way, but this is our way ... and that won't be changing. We work as a team to complete even the smallest level of a story whenever possible. You cannot actually test if something works until it is dev complete, and you cannot review the quality of the code either ... so the best you can do is split things up into small logical slices so that the bare minimum functionality can be tested and reviewed as early into the process as possible.

My question to those that work this way would be how to burn down a "task" when they are setup this way. Unless a Task has it's own sub-tasks (which JIRA doesn't allow) ... I'm not sure the best way to accomplish tracking "what's left" on a daily basis.

答:
Divide the task into multiple tasks and enter them as tasks where each is handled by a different person.

Original Task: Fix something

New Tasks: (child of parent of original task)

Dev A - Fixing the issue

Dev B - Helping Dev A in fixing the issue (i.e. pair programming, code review)

Dev A - dev testing the fix using Dataset X

Dev B - dev testing the fix using Dataset Y


答:
Your title does not seem to mach your question, and your question has little to do with reporting, so that might explain why you couldn't find much.

Your problem start to emerge here:

I have designed all the three classes to include all the operational logic (details of which are not relevant in context of the question).

I don't think you should put "operational logic" (do you mean data access operations like get, update and delete?) in your model classes.

for example, say, a list of all students doing projects in Chemistry mentored by a teacher whose name is the parameter to the query.

To me, it sounds like you're looking for the repository pattern. Something like:

```<code>class StudentRepository
{
    private $_database;

    function GetStudentByID($id)
    {
        return $_database..[query with $id];
    }

    function GetStudentsForSubjectAndTeacher($subjectID, $teacherID)
    {
        return $_database..[query with $subjectID, $teacherID];
    }
}
</code>```

Now everywhere you want to find all students for a given subject and teacher, you just create an instance of this repository and call the appropriate method.

Title: Design pattern to handle queries using multiple models

Body:
I am presented with a dilemma while trying to re-designing the class structure for my PHP/MySQL application to make it more elegant and conform it to the SOLID principle.

The problem goes like this:

Let as assume, there is an abstract class called person which has certain properties to define a generic person, such as name, age, date of birth etc.

There are two classes, student, and teacher, that implements this abstract class. They add their own unique properties to it.

I have designed all the three classes to include all the operational logic (details of which are not relevant in context of the question).

Now, I need to create views/reports/data grids which contain details from multiple classes, for example, say, a list of all students doing projects in Chemistry mentored by a teacher whose name is the parameter to the query.

This is just one example of a view, there are many different views in the application, which uses data from 3-4 tables, and each of them have multiple input parameters to generate them.

Considering this particular example, I have written the relevant query using JOIN and the results are as expected and proper, now here is the dilemma:

Keeping in mind the single responsibility principle, where should I keep this query? It does not belong to either Student class, or Teacher class or any other classes currently present.

a) Should I create a new class, say dataView class, and design it as a MVC pattern and keep the query there? What about the other views? how do they fit in this architecture?

b) Should I not keep the query in code at all, and make it DB View ?

c) Am I completely wrong in the approach? If so what is the right approach?

My considerations are as follows:

a) should be easy to add new views later on if requirement comes, without having to copy-paste-modify code

b) would like to make it as loosely coupled as possible so that if minor db structure changes happen, it does not break

I did google searches on report design and OOP report generators, but all the result seem to focus on the visual design of the report rather than fetching the data. I have already taken care of the visual aspect of the report using MVC with html templates.

I am sure this is a very fundamental problem with known solution, but I am somehow not able to find it (maybe searching with wrong keyword).

Edit1: Modified the title to make it more relevant

Edit2: The accepted answer got me thinking in the right direction and identify my design flaws, which eventually led me to find this question and the solution in Stack Overflow which gave me the detailed answer to clear the confusion.

Body:
Your title does not seem to mach your question, and your question has little to do with reporting, so that might explain why you couldn't find much.

Your problem start to emerge here:

I have designed all the three classes to include all the operational logic (details of which are not relevant in context of the question).

I don't think you should put "operational logic" (do you mean data access operations like get, update and delete?) in your model classes.

for example, say, a list of all students doing projects in Chemistry mentored by a teacher whose name is the parameter to the query.

To me, it sounds like you're looking for the repository pattern. Something like:

class StudentRepository
{
    private $_database;

    function GetStudentByID($id)
    {
        return $_database..[query with $id];
    }

    function GetStudentsForSubjectAndTeacher($subjectID, $teacherID)
    {
        return $_database..[query with $subjectID, $teacherID];
    }
}

Now everywhere you want to find all students for a given subject and teacher, you just create an instance of this repository and call the appropriate method.


答:
Even if your assertion was true, proving it would be infeasible, because the proof would have to go through all implementations of IEnumerable in the framework and prove for each one of those that it can't be infinite.

And your assertion actually isn't true, there is at least one implementation of IEnumerable in the framework that can be infinite: BlockingCollection.GetConsumingEnumerable():

What you would do is to create a bounded BlockingCollection that's filled in an infinite loop from a separate thread. Calling GetConsumingEnumerable() will then return an infinite IEnumerable:

```<code>var source = new BlockingCollection<int>(boundedCapacity: 1);
Task.Run(() => { while (true) source.Add(1); });
return source.GetConsumingEnumerable();
</code>```

Title: Is it possible to implement an infinite IEnumerable without using yield with only C# code?

Body:
Motivation

The main idea is to explore and understand the limits of how far one can go with the basic LINQ primitives (Select, SelectMany, Concat, etc.). These primitives can all be considered functional operations on a theoretical sequence type. Taking examples from Haskell:

Select 'lifts' a function into the sequence (like fmap in Haskell)

Concat is composition

Aggregate is the sequence type's catamorphism (fold)

SelectMany 'extracts' information from the sequence (the Monad bind, >>= operation)

etc. (and I'm sure there are better abstractions for the above)

So the question is whether or not the basic sequence (Enumerable) operations in C# are enough to construct an infinite sequence. More concretely it is the following problem:

Problem

I'm curious to know if there's a way to implement something equivalent to the following, but without using yield:

```<code>IEnumerable<T> Infinite<T>()
{
    while (true) { yield return default(T); }
}
</code>```

Is it possible to do sue using the built-in LINQ operators only?

The short answer is that theoretically yes, but practically not because of how Linq is implemented (causing stack overflows).

That's why here are less restrictive rules:

Rules

Alternatively a less restrictive question would go by the rules

You can't use the yield keyword directly

Use only C# itself directly - no IL code, no constructing dynamic assemblies etc.

You can only use the basic .NET lib (only mscorlib.dll, System.Core.dll? not sure what else to include). However if you find a solution with some of the other .NET assemblies (WPF?!), I'm also interested.

Don't implement IEnumerable or IEnumerator.

Notes

An example theoretically correct definition is:

```<code>IEnumerable<int> infinite = null;
infinite = new int[1].SelectMany(x => new int[1].Concat(infinite));
</code>```

This is "correct" but hits a StackOverflowException after 14399 iterations through the enumerable (not quite infinite).

I'm thinking there might be no way to do this due to the C#'s compiler lack of tail recursion optimization. A proof would be nice :)

Body:
Even if your assertion was true, proving it would be infeasible, because the proof would have to go through all implementations of IEnumerable in the framework and prove for each one of those that it can't be infinite.

And your assertion actually isn't true, there is at least one implementation of IEnumerable in the framework that can be infinite: BlockingCollection.GetConsumingEnumerable():

What you would do is to create a bounded BlockingCollection that's filled in an infinite loop from a separate thread. Calling GetConsumingEnumerable() will then return an infinite IEnumerable:

var source = new BlockingCollection<int>(boundedCapacity: 1);
Task.Run(() => { while (true) source.Add(1); });
return source.GetConsumingEnumerable();

ContentLicense: CC BY-SA 4.0


问:
What are the steps to grouping related classes into packages
What are the steps needed to be taken to group related classes into packages in Java?

In my case, I have about a number of .java files that I'd like to group into 3 packages according to the MVC pattern. One package for Model classes, one package for View classes and one package for Controller classes. I've identified which belong in what package, but not sure of the next step.

I want to know how to seperate them into packages, do I make 3 folders and place the .java files in the folder that represents the package they belong in?

答: Java requires that the name of a class file reflects the class name but there's no such requirement for packages. Packages are just names that do not form hierarchies although it might appear so on the surface. It is still a good practice to separate different packages to different directories that reflect the package name. All development environment do this for you automatically.</p>


问:
VB6 general search form
I'm working on an old vb6/access2003 app which is used to handle orders, bills of materials and that sort of things. I'm thinking about creating a form that I call every time the users needs to search for something. This should work like these:

Click on the field to complete, let's say name of a buyer

Open new form, search for the client and click on it

Return the name of the buyer to the previous form (probably the header of the order)

So, I would need to pass to the new form something that identify the type of search I have to do (so what access table to open) and return some values.

Is my idea correct or there something better? I would like to use only one form for all the searches, now the app works with a lot of msflexgrid for every form.

答:
In a full object oriented language, one could apply the strategy pattern here. The idea is to have a base class SearchStrategy and for each kind of search a derived child class. The objects of this class should provide all meta data ("which table / columns to search for", "which parameters to enter from the user for this search"), or specific search methods. Then, one would pass the specific SearchStrategy object into the generic search form, and the form uses the strategy to do the search.

Though VB6 is not a full OO language like VB.NET, it provides indeed enough polymorphism capabilities to implement that pattern. See here or here, for example.

Title: VB6 general search form


问:
unit testing on ARM
We are developing application level code that runs on an ARM processor. The BSP (low level code) is being delivered by a 3d party so our code sits just on top of this abstraction layer (code is written in c++).

To do unit testing, I assume we will have to mock/stub out the BSP library(essentially abstracting out the HW), but what I'm not sure of is if I write/run the unit test on my pc, do I compile it with for example GCC? Normally we use Realview compiler to compile our code for the ARM. Can I assume that if I compile and run the code with x86 compiler and the unit tests pass that it will also pass when compiled with RealView compiler?

I'm not sure how much difference the compiler makes and if you can trust that if the x86 compiled code pass the unit tests that you can also be confident that the Realview compiled code is ok.

答:
Although compilers contain bugs just like any other piece of software, the chances that you encounter one of those bugs while creating your own software are close to zero and the chance that such a bug manifests itself as misbehaving software is even smaller.

Apart from compiler bugs, you could get different behavior because the two compilers interpret your code differently. As long as you stay away from the murky corners of the language and especially avoid using undefined or unspecified behavior or non-portable assumptions (such as the size of basic types), then all C++ compilers are actually very good at producing consistent behavior when compiling the same code with different compilers.

In general, unless you are doing something very special, if your code compiles with all the relevant compilers then you can be sure that the produced executables also show consistent behavior with each other.

Title: unit testing on ARM


问:
How to support a product built with agile development?
Two of the functions our company provides our customers are:

Our Development team of ~10 employees creates software products for businesses in a particular industry. The software is used on hundreds of our customers' computers. Although the product is, for most customers, off-the-shell, larger customers drive its development, so it's somewhere between shrinkwrap software and custom software.

Our Support team of ~25 employees provides technical support for both our own software and a few other software products for which we are the vendor.

Our Development team recently switched to Scrum for their development methodology, and while I support this change, I worry that our Support team is going to have more trouble in the future.  With a quicker release cycle, our customers will have features and products in production which Support isn't even aware of until the customer calls. We've never been particularly good at getting documentation and information from Development to Support, but I fear Scrum will just exacerbate the problem.

What are good references on how companies reconcile Development's desire to release frequently with Support's desire to have full documentation and support information before customers see the product?  How should a company structure their release and change management when using agile methods?

EDIT: What I'm interested are specifics on how companies structure themselves to deal with these issues. Does the scrum team push releases to customers? Does the software have to go through a release/change management team who will not deploy until Support has been given documentation and brought up to speed?  How do you get releases to customers quickly yet still keep everyone informed of changes and new features?

答: If you run a demonstration of stories completed in your sprint, get your Support crew into these sessions. The more interactive the demonstration, the better.</p>


问:
Relation between " lines of the longest working program " in a language and familiarity with it?
In some computer master program  online application, it says:

Please list the programming languages in which you have written
  programs. For each language, indicate the length in lines of the
  longest working program you have written in that language. You may
  approximate, but only count those parts of the program that you wrote
  yourself.

I don't quite remember that, and I have never counted the lines of
each program. Do programmers always know approximately how many
lines in each of his programs, and keep record of them?

What is the relation between " lines of the longest working program
" in a language and familiarity with it?  Typically, how many lines will indicate the programmer being excellent, good, fair, or unfamiliar with the language?

Is knowing  "lines of the longest working program" really helpful?

答:
There are three issues with this question.

1. LOC

Lines of code is a terrible measure, especially with the assumption that more lines is better than less.

Imagine two students who are asked to solve the same problem.

One starts writing code, and during the entire exercise, writes more and more of it, never reading it. At the end of the exercise, the code base is full of:

Dead code (code which is not used at any point),

Code duplication due to Ctrl+C/Ctrl+V abuse (one of the most important issues in software development),

Plain duplication because of the lack of organization (the method is written from scratch, while the pretty same one exists in an other class),

Stupid comments such as:

```<code>// Concatenate the first and the last name.
string displayName = this.firstName + " " + this.lastName;
</code>```

Pieces of code which should have been inlined, such as:

```<code>int age = this.Age;
int threshold = this.Threshold;
int temp = age - threshold;
int limit = 3;

if (temp == limit)
{
    return true;
}

bool tmp = temp > limit;
if (tmp == true)
{
    return true;
}
else
{
    return false;
}
</code>```

which should have been as simple as:

```<code>int ageWithoutThreshold = this.Age - this.Threshold;
return ageWithoutThreshold >= MIN_AGE_TO_APPLY;
</code>```

Another one adds new lines of code carefully: more code means more sources of errors. He regularly refactors the code, architectures it properly to be able to find very easily which method should be put in which class, avoids code duplication, and, in general, tries to do what is required to solve a given problem, and nothing more.

Which one should have a better grade?

2. Working program

What is a working program? How to determine whether it works or not?

If a working program is a program which has no bugs, then there are practically no working programs in the world (a few use formal proof to be able to guarantee that the code doesn't have bugs, but I can hardly find an example of such program).

If a working program is a program for which no bugs are known, then the spaghetti code I urgently wrote this morning is a working program. I haven't compiled it yet, so I'm unaware of any bugs, even if I'm pretty sure that such terrible mess would take weeks to correct.

If a working program is a program for which every requirement has a functional test which passes, then what do you do with most code base which is grown organically, often with no written functional and non-functional requirements, and no functional tests?

If a working program is a program that is assumed to work by the author, then the answer to the question is pretty irrelevant. I assume that an app of 5 000 LOC might work. So what?

3. Program ≠ system

Most large systems are assembled from smaller programs, often presented as web services. For example, a CRM may rely on a REST API for authentication of users, or on another API for the management of documents, or on a third API for the upload of the documents.

Those systems are not programs.

For a web developer, for example, it makes no sense to talk about a large program. It would even be alarming to see a web developer being proud of creating a single large program: a set of small services would need much less maintenance.

Measuring familiarity

Using metrics to have an idea of a familiarity of a developer with a language doesn't make sense. I've already explained why LOC measure is wrong. Let's consider a few other measurements.

Years of professional experience

I've spent two days working on a C# project doing work so basic that a monkey could do it. Does it make me more experienced in C# than somebody who haven't spent two days doing the same thing?

Take a young, not very smart coder who have spent five years doing e-commerce websites again and again using Ruby. Now take a talented software developer who, until now, worked only with Assembler, C, C++, Java, Haskell and Python. Two weeks ago, he started to learn Ruby. Who is more valuable for a company looking for a developer for a Ruby project?

Years of professional experience is a meaningless measure; the fact that HR department loves it so much makes it extremely dangerous.

Number of projects

The same arguments apply here. I can spend a year doing e-commerce websites, again and again. Or I can spend a year working on a technically-challenging project where I do learn stuff.

Sadly, this metric is popular among HR people a lot too.

So, how to measure the experience of a developer in a given language? Through a systemic approach, by considering multiple factors, without transforming them into metrics:

Implication of the person in the community, including contribution to open source projects,

Projects which were actually sold,

Open source projects which became popular,

Writings (publications, blogs, etc.),

Participation to the conferences,

Personal motivation,

Ease of speech when it comes to explaining language quirks and dark sides,

Awareness of language pitfalls and drawbacks compared to other languages,

Knowledge of tools related to the language or ecosystem (debugging tools, testing, continuous integration, continuous delivery, etc.),

etc.

Body:
There are three issues with this question.

1. LOC

Lines of code is a terrible measure, especially with the assumption that more lines is better than less.

Imagine two students who are asked to solve the same problem.

One starts writing code, and during the entire exercise, writes more and more of it, never reading it. At the end of the exercise, the code base is full of:

Dead code (code which is not used at any point),

Code duplication due to Ctrl+C/Ctrl+V abuse (one of the most important issues in software development),

Plain duplication because of the lack of organization (the method is written from scratch, while the pretty same one exists in an other class),

Stupid comments such as:

// Concatenate the first and the last name.
string displayName = this.firstName + " " + this.lastName;

Pieces of code which should have been inlined, such as:

int age = this.Age;
int threshold = this.Threshold;
int temp = age - threshold;
int limit = 3;

if (temp == limit)
{
    return true;
}

bool tmp = temp > limit;
if (tmp == true)
{
    return true;
}
else
{
    return false;
}

which should have been as simple as:

int ageWithoutThreshold = this.Age - this.Threshold;
return ageWithoutThreshold >= MIN_AGE_TO_APPLY;

Another one adds new lines of code carefully: more code means more sources of errors. He regularly refactors the code, architectures it properly to be able to find very easily which method should be put in which class, avoids code duplication, and, in general, tries to do what is required to solve a given problem, and nothing more.

Which one should have a better grade?

2. Working program

What is a working program? How to determine whether it works or not?

If a working program is a program which has no bugs, then there are practically no working programs in the world (a few use formal proof to be able to guarantee that the code doesn't have bugs, but I can hardly find an example of such program).

If a working program is a program for which no bugs are known, then the spaghetti code I urgently wrote this morning is a working program. I haven't compiled it yet, so I'm unaware of any bugs, even if I'm pretty sure that such terrible mess would take weeks to correct.

If a working program is a program for which every requirement has a functional test which passes, then what do you do with most code base which is grown organically, often with no written functional and non-functional requirements, and no functional tests?

If a working program is a program that is assumed to work by the author, then the answer to the question is pretty irrelevant. I assume that an app of 5 000 LOC might work. So what?

3. Program ≠ system

Most large systems are assembled from smaller programs, often presented as web services. For example, a CRM may rely on a REST API for authentication of users, or on another API for the management of documents, or on a third API for the upload of the documents.

Those systems are not programs.

For a web developer, for example, it makes no sense to talk about a large program. It would even be alarming to see a web developer being proud of creating a single large program: a set of small services would need much less maintenance.

Measuring familiarity

Using metrics to have an idea of a familiarity of a developer with a language doesn't make sense. I've already explained why LOC measure is wrong. Let's consider a few other measurements.

Years of professional experience

I've spent two days working on a C# project doing work so basic that a monkey could do it. Does it make me more experienced in C# than somebody who haven't spent two days doing the same thing?

Take a young, not very smart coder who have spent five years doing e-commerce websites again and again using Ruby. Now take a talented software developer who, until now, worked only with Assembler, C, C++, Java, Haskell and Python. Two weeks ago, he started to learn Ruby. Who is more valuable for a company looking for a developer for a Ruby project?

Years of professional experience is a meaningless measure; the fact that HR department loves it so much makes it extremely dangerous.

Number of projects

The same arguments apply here. I can spend a year doing e-commerce websites, again and again. Or I can spend a year working on a technically-challenging project where I do learn stuff.

Sadly, this metric is popular among HR people a lot too.

So, how to measure the experience of a developer in a given language? Through a systemic approach, by considering multiple factors, without transforming them into metrics:

Implication of the person in the community, including contribution to open source projects,

Projects which were actually sold,

Open source projects which became popular,

Writings (publications, blogs, etc.),

Participation to the conferences,

Personal motivation,

Ease of speech when it comes to explaining language quirks and dark sides,

Awareness of language pitfalls and drawbacks compared to other languages,

Knowledge of tools related to the language or ecosystem (debugging tools, testing, continuous integration, continuous delivery, etc.),

etc.


答:
It all depends how they intend to use your answer. One person might "bucket" responses as follows:

100 lines or less: all you have written is demos or school assignments. Unless it's a language designed for little scripts, you probably don't know it thoroughly or work with it regularly.

100,00 lines or less: you write normal sized programs and probably understand them all, and there's a good chance you've met all the features of the language, know how to debug in it, and know at least one framework

more than 100,000 lines: you are exaggerating or we need to discuss this in the interview

I would be ok with that. But another person might have a far more granular approach where they distinguish between having claimed a 2000 line program and a 10,000 line program. That's silly. It doesn't mean that there's no difference between writing ten programs, each less than a hundred lines, and one thousand line program, because there is, and if you've written a thousand line program (or 100,000 line) you know this.

Title: Relation between " lines of the longest working program " in a language and familiarity with it?

Body:
In some computer master program  online application, it says:

Please list the programming languages in which you have written
  programs. For each language, indicate the length in lines of the
  longest working program you have written in that language. You may
  approximate, but only count those parts of the program that you wrote
  yourself.

I don't quite remember that, and I have never counted the lines of
each program. Do programmers always know approximately how many
lines in each of his programs, and keep record of them?

What is the relation between " lines of the longest working program
" in a language and familiarity with it?  Typically, how many lines will indicate the programmer being excellent, good, fair, or unfamiliar with the language?

Is knowing  "lines of the longest working program" really helpful?


问:
What is meant by, "A user shouldn't decide whether it is an Admin or not. The Privileges or Security system should."
The example used in the question pass bare minimum data to a function touches on the best way to determine whether the user is an administrator or not.  One common answer was:

```<code>user.isAdmin()
</code>```

This prompted a comment which was repeated several times and up-voted many times:

A user shouldn't decide whether it is an Admin or not. The Privileges
  or Security system should. Something being tightly coupled to a class
  doesn't mean it is a good idea to make it part of that class.

I replied,

The user isn't deciding anything. The User object/table stores data
  about each user. Actual users don't get to change everything about
  themselves.

But this was not productive.  Clearly there is an underlying difference of perspective which is making communication difficult.  Can someone explain to me why user.isAdmin() is bad, and paint a brief sketch of what it looks like done "right"?

Really, I fail to see the advantage of separating security from the system that it protects.  Any security text will say that security needs to be designed into a system from the beginning and considered at every stage of development, deployment, maintenance, and even end-of-life.  It is not something that can be bolted on the side.  But 17 up-votes so far on this comment says that I'm missing something important.

答:
Think about the User as a key, and the permissions as a value.

Different contexts might have different permissions for each user. As the permissions are context-relevant, you would have to change the user for each context. So it's better you put that logic somewhere else (e.g. the context class), and just look up the permissions where needed.

A side-effect is that it might make your system more secure, because you cannot forget to clear the admin flag for places where it's not relevant.


问:
How to factor out data layer in nopCommerce and replace MS SQL with RavenDB?
I am new to nopCommerce and ecommerce in general but I am involved in an ecommerce project. Now from my past experiences with RavenDB (which mostly were absolutely pleasant) and based on the needs of the business (fast changes with awkward business workflows) It seemed to be an appealing option to have RavenDB handling all sort of things related to the database.

I do not understand design and architecture of nopCommerce fully so I did not reach to a conclusion on how to factor data parts, since it seems the services layer actually does not abstract data-layer concepts away; like bringing in EF working model to other layers.

I have found another project which used NuDB as it's database as a nopCommerce fork. But it did not help because NuDB still has the feeling of a RDBMS and is not as different as RavenDB.

Now first how can I learn about the internals of nopCommerce (other than investigating the code)? It's workflows? It's conventions?

Second has anyone tried something similar before with a NoSQL database (say like MongoDB or RavenDB)? Is it possible to achieve this in a 1 (~2) month time frame?

Thanks in advance;

答:
I've tried both MongoDB and RavenDB for NopCommerce's DB. However, as Matt said, it's not a good idea. Here are some reasons:

The shortest way is repository pattern, an anti-fan of RavenDB. It took me about 2 weeks.

The search function of Nop is optimized for SQL. Raven can do it better and more beautiful, but you must change many methods of Nop.

All paging and sorting functions will be rewritten.
To change the data layer, you'll have to change a half of the business layer, too!


答:
Sun / Oracle Java coding conventions abstain of providing concrete requirements on how to package.

Per my reading of related parts of conventions, this appears a deliberate decision: developers are expected to package at their discretion, following the general guidance and ideas provided by conventions.

Particular convention to keep in mind is 10.1 Providing Access to Instance and Class Variables

Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten-often that happens as a side effect of method calls.

Take into account that classes and methods referred from within the same package allow to avoid public access, this gives sort of a preference to larger packages.

But, if one follows above blindly, this may lead to unmantainable packages that are too large. To balance for that, one would better take into account the part of 3.1.3 Class and Interface Declarations that gives guidance on how to group things (bold font in below quote is mine):

...methods should be grouped by functionality rather than by scope or accessibility... The goal is to make reading and understanding the code easier.

You see, as soon as you feel (better yet, find in code-review) like package becomes somehow difficult to read and understand, it's time to reconsider the packaging ("grouping"), following above considerations.

Use your judgement, tests and code reviews to keep code readable and maintainable, and avoid using public without good reason - that's it.

Applied to your case, above means you are not strictly mandated to make three packages as you listed. For the reference, Martin Fowler gives strong recommendation to only separating the model:

Make a strong separation between presentation (view & controller) and domain (model) - Separated Presentation...

For view and controller, Fowler still recommends some degree of separation, but not in such strong terms:

Controller and view should (mostly) not communicate directly but through the model.

I have even seen a pretty compelling reasoning in favor of keeping controller and view close to each other:

...a view and controller are often intertwined - think of it as M(VC).

The controller is the input mechanism of the user interface, which is often tangled up in the view, particularly with GUIs. Nevertheless, view is output and controller is input. A view can often work without a corresponding controller, but a controller is usually far less useful without a view. User-friendly controllers use the view to interpret the user's input in a more meaningful, intuitive fashion. This is what it makes it hard separate the controller concept from the view.

Think of an radio-controlled robot on a detection field in a sealed box as the model...

Most user-friendly UI's coordinate the view with the controller to provide a more intuitive user interface. For example, imagine a view/controller with a touch-screen showing the robot's current position in 2-D and allows the user to touch the point on the screen that just happens to be in front of the robot. The controller needs details about the view, e.g. the position and scale of the viewport, and the pixel position of the spot touched relative to the pixel position of the robot on the screen) to interpret this correctly (unlike the guy locked in the closet with the radio controller)...

With above in mind, you have a reasonable option to start designing your code split to two packages instead of three (say, model and, if you prefer to follow Fowler's naming, presentation).

Further down the road, as you add more code, you need to keep an eye on keeping the code good for "reading and understanding", as suggested by Java coding conventions quoted above. Writing tests and going through code reviews provide good means for such a "complexity monitoring".

If you find that particular package becomes troublesome in that regard, consider splitting it or extracting some part of it into a new, separate package. It can happen that this will lead to splitting presentation package to view and controller, bringing it to exact match with MVC, but one can't tell beforehand whether it will be the case or not.

Title: What are the steps to grouping related classes into packages

Body:
What are the steps needed to be taken to group related classes into packages in Java?

In my case, I have about a number of .java files that I'd like to group into 3 packages according to the MVC pattern. One package for Model classes, one package for View classes and one package for Controller classes. I've identified which belong in what package, but not sure of the next step.

I want to know how to seperate them into packages, do I make 3 folders and place the .java files in the folder that represents the package they belong in?


问:
How to deal with the "programming blowhard"?
So I'm sure everyone has run into this person at one point or another, someone catches wind of your project or idea and initially shows some interest. You get to talking about some of your methods and usually around this time they interject stating how you should use method X instead, or just use library Y. But not as a friendly suggestion, but bordering on a commandment. Often repeating the same advice over and over like a overzealous parrot.

Personally, I like to reinvent the wheel when I'm learning, or even just for fun, even if it turns out worse than what's been done before. But this person apparently cannot fathom recreating ANY utility for such purposes, or possibly try something that doesn't strictly follow traditional OOP practices, and will settle for nothing except their sense of perfection, and thus naturally heave their criticism sludge down my ears full force. To top it off, they eventually start justifying their advice (retardation) by listing all the incredibly complex things they've coded single-handedly (usually along the lines of "trust me, I've made/used program X for a long time, blah blah blah").

Now, I'm far from being a programming master, I'm probably not even that good, and as such I value advice and critique, but I think advice/critique has a time and place. There is also a big difference between being helpful and being narcissistic. In the past I probably would have used a somewhat stronger George Carlin style dismissal, but I don't think burning bridges is the best approach anymore.

Do you have any advice on how to deal with this kind of verbal flogging?

答: I would tell them to f**k off (You could use more diplomatic verbiage if you wish.) or simply ignore them. There aren't many options beyond what I've said. (Murder could work but legality varies by locale.)


答: Sure.  IEnumerable is basically just a call to IEnumerator.  Implement an IEnumerator where the MoveNext function just sets an internal value to a random value, and Current returns that random value.</p>


问:
Is it considered bad practice to access a returned array by a key straight away?
I couldn't think of a good way to word the title, sorry. But what I mean is, is it considered bad practice to do:

```<code>print get_array()[2]
</code>```

over:

```<code>output=get_array()
print output[2]
</code>```

(where get_array() is a function that returns an array, if that wasn't clear). Which method is better? Why?

答:
Let me take a crack at this,

Think of the risks you're posing by accessing an array straight away.

Do you know for SURE, it's got data at the aforementioned index?

Is that data in the format you want?

If there was an Exception, like a null at that index, would your
program be able to recover?

I cannot tell off the bat what language you're using... but, in any language it's a good idea to just double check the input of your functions before using them.  This can save massive headaches when a codebase grows.


问:
What is the need of Odata when I have JSON?
I am trying to understand the point of Odata and when it would make sense. Right now how I work is I use ASP.NET and MVC/WebApi controller to serialize/deserialize objects into JSON and have javascript do something with it.

From what I can tell the benefit of OData is being able to query directly from the URL ... But since I am writing the client and server code there is no need for that.

Would anyone ever parse the results of a ODaya query in javascript??

Maybe OData is more about providing a generic endpoint for ALL clients to get detailed information from a query that JSON does not provide ? So if I was a provider of data then I suppose that is what odata is for ?

Help me understand the purpose and use of REST/JSON/ODATA.

答:
JSON or  JavaScript Object Notation is merely a format or standard for data.  It's an agreed upon format for transmitting something like a login name OR something that needs to be consumed by a REST Service.

See this part : http://en.wikipedia.org/wiki/JSON

Although originally derived from the JavaScript scripting language, JSON is a language-independent data format, and code for parsing and generating JSON data is readily available in a large variety of programming languages.

It's not a part of any particular programming language, so different systems can pass around data quite easily, if they know they are using JSON.

As for REST it's simply an style of architecture used for web services.

See this part : http://en.wikipedia.org/wiki/Representational_state_transfer

One way to think about this, is if you wanted to write a web service that many different computers can talk to.. and exchange information.  You could write your web service to accept data via the URL

```<code> http://www.myservice.com/specialRESTService?name=punkouter
</code>```

The response back could be a JSON object signaling your data was received.

```<code>{
    "name": "punkouter",
    "status": "service downloaded your data",
}
</code>```

I had never heard of OData, so I googled it :

OData is built on the AtomPub protocol and JSON where the Atom structure is the envelope that contains the data returned from each OData request. An OData request uses the REST model for all requests. Each REST command is a POST, GET, PUT, PATCH, or DELETE http request (mapping to CRUD) where the specifics of the command are in the url.

GET: Get a collection of entities (as a feed document) or a single entity(as an entry document).

POST: Create a new entity from an entry document.

PUT: Update an existing entity with an entry document.

PATCH: Update an existing entity with a partial entry document.

DELETE: Remove an entity.

Sounds like OData is something written to augment a vanilla REST style architecture..  But it looks like it can give you some added things to get you going, instead of having to write things from scratch in C# or whatever language you're using.

If you work is pushing you into using OData, you'd still be using JSON..but within the OData framework/standard written by Microsoft et al.

Would anyone ever parse the results of a OData (sic) query in javascript??

Yes, since (it sounds like) it's using JSON.  It'd be perfectly natural to use JS.

Maybe OData is more about providing a generic endpoint for ALL clients to get detailed information from a query that JSON does not provide ? So if I was a provider of data then I suppose that is what Odata is for ?

Odata would be providing a REST service.. but with some added standard services on top of a plain "generic" REST service endpoint.. clients don't care if you're using OData, or rolling your own C# service.. as long as the responses were in an agreed upon format (like JSON).  However, for your work maybe they want to use OData because it provides a lot of 'out of the box' features..

Body:
JSON or  JavaScript Object Notation is merely a format or standard for data.  It's an agreed upon format for transmitting something like a login name OR something that needs to be consumed by a REST Service.

See this part : http://en.wikipedia.org/wiki/JSON

Although originally derived from the JavaScript scripting language, JSON is a language-independent data format, and code for parsing and generating JSON data is readily available in a large variety of programming languages.

It's not a part of any particular programming language, so different systems can pass around data quite easily, if they know they are using JSON.

As for REST it's simply an style of architecture used for web services.

See this part : http://en.wikipedia.org/wiki/Representational_state_transfer

One way to think about this, is if you wanted to write a web service that many different computers can talk to.. and exchange information.  You could write your web service to accept data via the URL

 http://www.myservice.com/specialRESTService?name=punkouter

The response back could be a JSON object signaling your data was received.

{
    "name": "punkouter",
    "status": "service downloaded your data",
}

I had never heard of OData, so I googled it :

OData is built on the AtomPub protocol and JSON where the Atom structure is the envelope that contains the data returned from each OData request. An OData request uses the REST model for all requests. Each REST command is a POST, GET, PUT, PATCH, or DELETE http request (mapping to CRUD) where the specifics of the command are in the url.

GET: Get a collection of entities (as a feed document) or a single entity(as an entry document).

POST: Create a new entity from an entry document.

PUT: Update an existing entity with an entry document.

PATCH: Update an existing entity with a partial entry document.

DELETE: Remove an entity.

Sounds like OData is something written to augment a vanilla REST style architecture..  But it looks like it can give you some added things to get you going, instead of having to write things from scratch in C# or whatever language you're using.

If you work is pushing you into using OData, you'd still be using JSON..but within the OData framework/standard written by Microsoft et al.

Would anyone ever parse the results of a OData (sic) query in javascript??

Yes, since (it sounds like) it's using JSON.  It'd be perfectly natural to use JS.

Maybe OData is more about providing a generic endpoint for ALL clients to get detailed information from a query that JSON does not provide ? So if I was a provider of data then I suppose that is what Odata is for ?

Odata would be providing a REST service.. but with some added standard services on top of a plain "generic" REST service endpoint.. clients don't care if you're using OData, or rolling your own C# service.. as long as the responses were in an agreed upon format (like JSON).  However, for your work maybe they want to use OData because it provides a lot of 'out of the box' features..


答:
This entirely depends upon what you are planning on doing with the array and what you should/can do if the element you expect to be at a certain position isn't there.

Frequently, when this is done,  it is returning multiple values (such as a first, middle and last names) which are actually independent -- the array is an ad hoc structure.  The problem with this is that it isn't defined anywhere, and so is fragile.  If you add enums to make it less fragile, you've spent about as much time, for not much gain - better to just define a structure and be done with it.

That said, sometimes you have to consume a API where this has been done, in which case, directly accessing the value is fine if the contract says it will always be there.

If you don't do anything with the returned value except access it once, putting it in a temp variable doesn't gain you anything (except possibly during debugging, where knowing what result is passed to a function can be useful).

Title: Is it considered bad practice to access a returned array by a key straight away?

Body:
I couldn't think of a good way to word the title, sorry. But what I mean is, is it considered bad practice to do:

```<code>print get_array()[2]
</code>```

over:

```<code>output=get_array()
print output[2]
</code>```

(where get_array() is a function that returns an array, if that wasn't clear). Which method is better? Why?


问:
Micro finance in the programming industry
I've read quite a bit about the positive effects of micro finance in developing countries. Organizations exist that solicit capital from donations and then make micro loans to people for the purpose of setting up some kind of business.

The loans are usually quite small, with little to no interest and are well under ten thousand US Dollars, typically reaching only hundreds of dollars. The pay back rate is also excellent. The programs that exist seem to focus on retail and agricultural endeavours, I have yet to see an organization with a focus on technology sectors like software development.

Do you know of any established / credible micro finance organizations that supply micro loans to individuals in order to set up software related businesses? Have the loans been paid back as well as other sectors, such as agriculture and retail?

I'm looking globally, so organizations in any country would be appreciated.

答:
Community Driven Funding

The closest thing I know is called Kickstarter.

What is Kickstarter? We’re the largest funding platform for creative projects in the world

It is not specifically bound to software development. My understanding is that it is only available to the US market.

An alternative if you don't like Kickstarter: Ulule.com that is global.

Both of them are community driven. Money comes from people like you and me, and not funds or banks.

National or Regional Fundings

In many countries (especially europe) there is local help by governments. In Belgium there is called "Bourse de préactivité". They give up to 12.500 Euros to any individual that will come up with an innovative idea and want to create a business with it. It's a subsidy. There is Awex that promotes exportation and refund you up to 50% of your charges for your presence in international trade shows or the fact you build a multi-language e-commerce website.

I'm sure every country has his own programs.

Microsoft has a lot of Microsoft Innovation Centers in the world. Many of them are joint ventures with the local government. They are aware of all financial tools you could use in your local country, and they will certainly help, even if you are not in Microsoft eco-system.


答:
It is always good practice to separate your code's IO from its internal computations.  The coding-related StackExchange sites are littered with code that mixes Print (or Println or putStr or whatever is the local dialect) inside complex functions.  This is bad practice.

In the case of output (as in your example), mixing output statements with computation tends to make the final output of the program dependent on the internal structure of the code.  It then becomes difficult to alter that code without breaking the output.  For example, you might want to print out a sorted sequence of lines; you happen to extract them from some structure which automatically sorts them, so you naively add print statements as you compute each line.  This works.  Then you switch to storing the intermediate calculations in a structure which doesn't sort them.  Broken output which requires you to remove the print statements, add a sorting step and then put the print statements after that.

If you separate computation from presentation, you don't have this problem.

In your specific example, I don't think either choice is good, because both might fail.  Even if you get a valid array, what if it doesn't have a second row?  This is a problem you should resolve before your output step.  Your second example is actually worse, because it doesn't resolve the problem so adds a pointless extra step.

```<code>output=get_array()[2]
print output
</code>```

Would be better.  The retrieval of the data and its output can then be cleanly separated.

Body:
It is always good practice to separate your code's IO from its internal computations.  The coding-related StackExchange sites are littered with code that mixes Print (or Println or putStr or whatever is the local dialect) inside complex functions.  This is bad practice.

In the case of output (as in your example), mixing output statements with computation tends to make the final output of the program dependent on the internal structure of the code.  It then becomes difficult to alter that code without breaking the output.  For example, you might want to print out a sorted sequence of lines; you happen to extract them from some structure which automatically sorts them, so you naively add print statements as you compute each line.  This works.  Then you switch to storing the intermediate calculations in a structure which doesn't sort them.  Broken output which requires you to remove the print statements, add a sorting step and then put the print statements after that.

If you separate computation from presentation, you don't have this problem.

In your specific example, I don't think either choice is good, because both might fail.  Even if you get a valid array, what if it doesn't have a second row?  This is a problem you should resolve before your output step.  Your second example is actually worse, because it doesn't resolve the problem so adds a pointless extra step.

output=get_array()[2]
print output

Would be better.  The retrieval of the data and its output can then be cleanly separated.


问:
Tender vs. Requirements vs. Solution Design
Conventionally, which of the above documents is deemed to hold the most weight when it comes to system acceptance?

I recently had a conversation along these lines:

It was argued that the initial requirements / tender documentation should be used to determine system acceptance. It was said that the solution design only serves to describe the way in which the system will solve the problem, not the problem it will solve. Furthermore, it was argued that if requirements are missed during solution design, the requirements should be referenced during system acceptance and that if any requirements were missed then the original tender should be referenced.

Conversely, I suggested that - while requirements may be based on the original tender - they supersede it once agreed with the stakeholders. Furthermore, during solution design, analysis is performed to address and refine these initial requirements, translating them into a system capable of meeting the actual requirements. Once signed off by the relevant users, this solution design should absolutely represent the requirements (by virtue of the fact that it's designed upon them) but actually supersedes them as the basis for system acceptance.

Is one of the above arguments more valid than the other?

EDIT: Apologies for the ambiguous terms. In this situation, tender is the document the customer took to market when shopping for a provider - it includes details of all the high-level features they're looking for. Solution design is not a technical document, it's the functional specification.

答:
Passing acceptance testing is an indication that the system meets the users' requirements acceptably.  As such, the requirements document is generally considered the source of truth for acceptance criteria.

There will almost always be further elaboration of requirements during design.  If these are truly an expansion of scope, the requirements document should be updated to reflect this.  Depending on how formal your process is, this may involve change requests, blah blah blah.


问:
Side effect-free interface on top of a stateful library
In an interview with John Hughes where he talks about Erlang and Haskell, he has the following to say about using stateful libraries in Erlang:

If I want to use a stateful library, I usually build a side
  effect-free interface on top of it so that I can then use it safely in
  the rest of my code.

What does he mean by this? I am trying to think of an example of how this would look, but my imagination and/or knowledge is failing me.

答:
(I don't know Erlang, and I can't write Haskell, but I think I can answer nevertheless)

Well, in that interview the example of a random number generation library is given. Here is a possible stateful interface:

```<code># create a new RNG
var rng = RNG(seed)

# every time we call the next(ceil) method, we get a new random number
print rng.next(10)
print rng.next(10)
print rng.next(10)
</code>```

Output may be 5 2 7. To someone who likes immutability, this is plain wrong! It should be 5 5 5, because we called the method on the same object.

So what would a stateless interface be? We can view the sequence of random numbers as a lazily evaluated list, where next actually retrieves the head:

let rng = RNG(seed)
let n : rng = rng in
  print n
  let n : rng = rng in
    print n
    let n : rng in
      print n
```

<p>With such an interface, we can always revert to a previous state. If two pieces of your code refer to the same RNG, they will actually get the same sequence of numbers. In a functional mindset, this is highly desirable.</p>

<p>Implementing this in a stateful language isn't that complicated. For example:</p>

<pre class="lang-scala prettyprint-override"><code>import scala.util.Random
import scala.collection.immutable.LinearSeq

class StatelessRNG (private val statefulRNG: Random, bound: Int) extends LinearSeq[Int] {
  private lazy val next = (statefulRNG.nextInt(bound), new StatelessRNG(statefulRNG, bound))

  // the rest is just there to satisfy the LinearSeq trait
  override def head = next._1
  override def tail = next._2
  override def isEmpty = false
  override def apply(i: Int): Int = throw new UnsupportedOperationException()
  override def length = throw new UnsupportedOperationException()
}

// print out three nums
val rng = new StatelessRNG(new Random(), 10)
rng.take(3) foreach (n => println(n))
</code>```

Once you add a bit of syntactic sugar so that it feels like a list, this is actually quite nice.

Body:
(I don't know Erlang, and I can't write Haskell, but I think I can answer nevertheless)

Well, in that interview the example of a random number generation library is given. Here is a possible stateful interface:

# create a new RNG
var rng = RNG(seed)

# every time we call the next(ceil) method, we get a new random number
print rng.next(10)
print rng.next(10)
print rng.next(10)

Output may be 5 2 7. To someone who likes immutability, this is plain wrong! It should be 5 5 5, because we called the method on the same object.

So what would a stateless interface be? We can view the sequence of random numbers as a lazily evaluated list, where next actually retrieves the head:

let rng = RNG(seed)
let n : rng = rng in
  print n
  let n : rng = rng in
    print n
    let n : rng in
      print n

With such an interface, we can always revert to a previous state. If two pieces of your code refer to the same RNG, they will actually get the same sequence of numbers. In a functional mindset, this is highly desirable.

Implementing this in a stateful language isn't that complicated. For example:

import scala.util.Random
import scala.collection.immutable.LinearSeq

class StatelessRNG (private val statefulRNG: Random, bound: Int) extends LinearSeq[Int] {
  private lazy val next = (statefulRNG.nextInt(bound), new StatelessRNG(statefulRNG, bound))

  // the rest is just there to satisfy the LinearSeq trait
  override def head = next._1
  override def tail = next._2
  override def isEmpty = false
  override def apply(i: Int): Int = throw new UnsupportedOperationException()
  override def length = throw new UnsupportedOperationException()
}

// print out three nums
val rng = new StatelessRNG(new Random(), 10)
rng.take(3) foreach (n => println(n))

Once you add a bit of syntactic sugar so that it feels like a list, this is actually quite nice.