答:
Are there any practical uses of the assignment operator's return value that could not be trivially rewritten?

Generally speaking, no. The idea of having the value of an assignment expression be the value that was assigned means that we have an expression which may be used for both its side effect and its value, and that is considered by many to be confusing.

Common usages are typically to make expressions compact:

```<code>x = y = z;
</code>```

has the semantics in C# of "convert z to the type of y, assign the converted value to y, the converted value is the value of the expression, convert that to the type of x, assign to x".

But we are already in the realm of impertative side effects in a statement context, so there's really very little compelling benefit to that over

```<code>y = z;
x = y;
</code>```

Similarly with

```<code>M(x = 123);
</code>```

being a shorthand for

```<code>x = 123;
M(x);
</code>```

Again, in the original code we are using an expression both for its side effects and its value, and we are making a statement that has two side effects instead of one.  Both are smelly; try to have one side effect per statement, and use expressions for their values, not for their side effects.

I'm developing a language which I intend to replace both Javascript and PHP.

If you really want to be bold and emphasize that assignment is a statement and not an equality, then my advice is: make it clearly an assignment statement.

```<code>let x be 1;
</code>```

There, done. Or

```<code>x <-- 1;
</code>```

or even better:

```<code>1 --> x;
</code>```

Or even better still

```<code>1 → x;
</code>```

There's absolutely no way that any of those are going to be confused with x == 1.

Body:
Are there any practical uses of the assignment operator's return value that could not be trivially rewritten?

Generally speaking, no. The idea of having the value of an assignment expression be the value that was assigned means that we have an expression which may be used for both its side effect and its value, and that is considered by many to be confusing.

Common usages are typically to make expressions compact:

x = y = z;

has the semantics in C# of "convert z to the type of y, assign the converted value to y, the converted value is the value of the expression, convert that to the type of x, assign to x".

But we are already in the realm of impertative side effects in a statement context, so there's really very little compelling benefit to that over

y = z;
x = y;

Similarly with

M(x = 123);

being a shorthand for

x = 123;
M(x);

Again, in the original code we are using an expression both for its side effects and its value, and we are making a statement that has two side effects instead of one.  Both are smelly; try to have one side effect per statement, and use expressions for their values, not for their side effects.

I'm developing a language which I intend to replace both Javascript and PHP.

If you really want to be bold and emphasize that assignment is a statement and not an equality, then my advice is: make it clearly an assignment statement.

let x be 1;

There, done. Or

x <-- 1;

or even better:

1 --> x;

Or even better still

1 → x;

There's absolutely no way that any of those are going to be confused with x == 1.


问:
How to deal with a dev who asks too many questions
I've recently stepped in to a managing position which of course involves overseeing other people's work, and guiding juniors.

There's this guy who won't stop asking questions, and many times it's really basic stuff - which eats a lot of my time and breaks my in-the-zone mode. I tried the easy-going approach of sending him a link with "Let me Google that for you", but he only got excited about the joke, and didn't get the clue. Other times I'm just telling him I'm busy, and that he should go and research it himself.

The thing is, when I wasn't in the office he did a decent job on his own, so most of what he's assigned with he can handle.

The question is how can I make him filter the issues he comes to me with? I realize that I'm the professional authority he should be addressing when he needs help, I only wish he would do it on non-trivial matters.

答:
Have you tried just telling him?

You're trying subtle hints, and they aren't working.  Telling him about a joke site might get the point across to some people, but it didn't work on him.  Telling him you're busy at the moment might have sounded like you have something to get done right now, but if not you'd be happy to help.

Some people can read incredibly subtle hints.  Other people couldn't pick up on a subtle hint to save their lives.

I was in a work situation (not programming related) where I was shuffled from one place to another, working for different bosses.  I started worrying that maybe they didn't like my work and wanted me to approach it in a different way, but they never said so, and whenever they told me they were going to send me somewhere else, they were always smiling and friendly and never said a word about bad performance or anything like that.

Finally they sent me to a new boss who immediately told me that they'd sent me there because they thought I was terrible and useless.  They might have been sending all sorts of subtle hints, but they never once told me.  The new boss told me what he wanted me to do, and I did it, and he was quite happy with me.

You want him to filter the issues he comes to you with.  Have you tried, "I'd like for you to filter the issues you come to me with."?  You don't want him to interrupt you while you're in the zone for basic stuff.  Have you told him that?

ContentLicense: CC BY-SA 3.0


问:
License for my Software
I am nowhere near good at coming up with what type of license to use and I don't want to be sued or have my work stolen so I am going to ask. Here is my situation: I am creating a software for my boss and the YMCA which helps keep track of our employees, their students, and the amount of lessons they have remaining (In a nutshell but the program is much more extensive then that), I am spent almost 100 hours creating it and its not completely done. Some of the hours spent were at work while being paid (Not sure if that plays a factor). Here is a list of conditions that I desire:

My software to not be redistributed in any way without my knowledge and written consent.

To not be liable for any damage it causes, for maintaining the software, or for its success.

I do not want the software to be sold without my knowledge and consent either.

I want the software to be closed sourced.

If there is a way I can have all of these in my software licensed I would be grateful, also if someone could explain to me where I need the license displayed and if it needs to be in the source code (since I am having it closed sourced).

答:
Generally speaking, if you work for a company in an employer/employee relationship, and you write a program for them, they own it. (it's called a "work for hire"). So I don't see how you can assert any of your stated conditions. Yes, getting paid for some of the hours is a factor; it supports the idea that your software is a "work for hire."

You need to talk to the YMCA first and see if they will grant you these conditions. If they are willing, simply get a signed release from them and include those conditions in your software license.

Note that agreements and licenses don't actually prevent you from being sued, or prevent users from violating your stated conditions.  All they do is specify the terms and conditions under which you wish the software to be used.  The only way to eliminate all risk is to not release the software.

A lawyer that specializes in licensing law can help you draft a license that meets your stated conditions, and contains unambiguous verbiage that will stand up in a court of law.  You can also try cobbling together a license from other licenses that you find on the Internet, if you think you're smart enough to try that yourself.  Commercial licenses contain boilerplate language that limits liability and satisfies some or all of the conditions you specified in your question.

Title: License for my Software


答:
If you're the manager and 'professional authority', its your job to manage him... not tell him to get lost and figure it out himself.

So.. you need to consider why he's asking. Is it a political thing where he's brown-nosing the boss? Is it a confidence thing where he needs to ask in order to be reassured he's doing the right thing? Is it an authority thing where he feels he needs to make sure he has sign-off?

You need to sit down with him and have an adult conversation, including review and objectives for him, and in that formal chat you can give him some more authority to do what he feels is best. Bring up the good work he did and give praise for that, and tell him you were so impressed that you know he can do it, so he should not have any worries about doing it again without coming to you for guidance. Make it seem like a promotion to "independent worker" and he should be a happy, and more confident, puppy.

Don't overdo it, ask to see his designs maybe so you can "keep in touch with the new code that's going to go in" (nothing stopping you from reviewing it and giving feedback of course). As you're the design authority, you should make time for initial meetings to go over requirements and suggested implementations which should make him feel like he's done his bit in keeping you informed too.

Title: How to deal with a dev who asks too many questions

Body:
I've recently stepped in to a managing position which of course involves overseeing other people's work, and guiding juniors.

There's this guy who won't stop asking questions, and many times it's really basic stuff - which eats a lot of my time and breaks my in-the-zone mode. I tried the easy-going approach of sending him a link with "Let me Google that for you", but he only got excited about the joke, and didn't get the clue. Other times I'm just telling him I'm busy, and that he should go and research it himself.

The thing is, when I wasn't in the office he did a decent job on his own, so most of what he's assigned with he can handle.

The question is how can I make him filter the issues he comes to me with? I realize that I'm the professional authority he should be addressing when he needs help, I only wish he would do it on non-trivial matters.


问:
Multiple remote views of a C# application
I have a C# application (Desktop based application for Windows OS), which I wanted to use from Web browser.

The application is a kind of analyzing tool, which takes some input values and performs set of calculations over it then displays an animation of the results.

Since the application can't be coded again in a new language, Can anyone suggest me, how I can view and interact with this C# application from browser (like the way we interact with Java Applets)? Also the application can be used by more than one user at a time, so there must be multiple views for this web application.

答:
There are three main options available, and only two require no existing code to be changed or added, and zero meet all of your stated requirements.

Remote Desktop: A computer runs the application as normal, but to access it remotely you simply use a remote desktop client software or browser plugin/applet to access. Microsoft Remote Desktop is the most well known, though LogMeIn and other related services work similarly. It does not work with multiple users simultaneously.

Remote Desktop + Virtual Desktop/Virtual Machine: This works as the above, but on the backend instead of a normal operating system you remote desktop to a multi-user supporting desktop environment, such as that provided by Windows Server, VMWare, and others. Each user has their own virtual desktop (if you set them up that way and pay the appropriate fees, anyway), and you each person can run their own application. Downside: No, it does not scale as cheaply as internet applications. No, you can't really give the general public access to it this way.

Change/add code. As with other suggestions, one could adapt the code to ASP.NET, or similarly port it to being a Silverlight application which would run in the browser (like Flash). Downside: it requires coding/development.

To clarify and use your example of Java, a Java Application is not the same as an Applet. One cannot add a flag and deploy a java application the browser, it just doesn't work like that.

If it were possible, if this helps any, Microsoft would just do that instead of rewriting so many of their core Office programs as online applications. They can't just make an application run in a browser to unlimited users without one of the above classes of solution, and I'm afraid you won't be able to either.


问:
What are the advantages of myBatis over Hibernate?
I've done some research on my own and understand the basic concept. But some insights can only be gained through actual experience.

What are the advantages of myBatis that would make it worth learning a new framework?

In what case would you avoid using it?

答: I used Hibernate for a data loading and data transformation project 5 years ago using Hibernate 3 and I thought it was wonderful.  I am doing a small e-commerce application and I tried using Hibernate 4 and I was extremely disappointed.  They have removed the tools and tightly integrated to the IDE.  I tried MyBatis and I go everything working in a single night and I am very please with how easy it is to integrate into an application.  I think Hibernate has become too bloated and I would use EJB 3 over Hibernate at this point.</p>


问:
HTML markup vs programmatic JS
I've been thinking about the consequences of using programmatic JavaScript components versus HTML markup. For example I looked into the Enyo Framework, which has its power in composition. One can build components composed of simpler components, and at the end they may be built from tags, but one doesn't write HTML Markup with it.

I also thought that it would be possible to develop a swing-like UI library which renders itself on an HTML5 canvas. There also would be no need for any markup.

But is there a need for this? Isn't HTML5 capable enough for these goals? I did some brain storming on a webapp similar to draw.io where there would be many Items which need to be resizable and draggable. They would need to be connected, transformed, rotated, etc., and all of that needs to be obvious from varying the borders of items, and other UI clues.

Is it possible to achieve this with HTML5, or since I have to code a lot anyway, would there be any harm to use only Javascript components without HTML markup? What are the trade-offs and what yields more pain?

答:
Frameworks are all about managing the level of abstraction that you work in.

This Fiddle, for example, shows how you can use a few lines of Javascript to create an HTML5 toolbar.

```<code>enyo.kind({
    name: "MySample",
    components: [
        {kind: "onyx.Toolbar", content: "Your sample here"}
    ]
});

new MySample({fit:true}).write();
</code>```

The question becomes, "How much HTML5 and CSS3 would I have to write by hand to accomplish the same thing?"

Like all good software abstractions, frameworks like Enyo allow you to create something once, and then reuse that thing in new applications without having to write it again.

See Also

Enyo Showcase

Enyo Demo

Title: HTML markup vs programmatic JS

Body:
Frameworks are all about managing the level of abstraction that you work in.

This Fiddle, for example, shows how you can use a few lines of Javascript to create an HTML5 toolbar.

enyo.kind({
    name: "MySample",
    components: [
        {kind: "onyx.Toolbar", content: "Your sample here"}
    ]
});

new MySample({fit:true}).write();

The question becomes, "How much HTML5 and CSS3 would I have to write by hand to accomplish the same thing?"

Like all good software abstractions, frameworks like Enyo allow you to create something once, and then reuse that thing in new applications without having to write it again.

See Also

Enyo Showcase

Enyo Demo


问:
Can I get sued over duplicating another program's UI?
If I see something I like in another application, and create something similar from the ground up in a commercial product, could I get sued over it?

Of course it would be styled to look differently, however most of the functionality would be the same since the functionality is what I liked about it. It also would not be the entire system, just a part of one.

I live in the US.

答:
I'm not a lawyer, so I can not tell you for sure, but I believe it is possible to get sued for copying an existing UI, especially if parts of it are patented.  A good example of this is the Amazon 1-Click patent which means Amazon could sue any online shop that allows user to make purchases with one mouse click.

In reality, I think if you are modeling you UI after an existing program that uses pretty standard UI techniques I doubt they would come after you, but again I'm not a lawyer.

ContentLicense: CC BY-SA 2.5


问:
What is the benefit of having the assignment operator return a value?
I'm developing a language which I intend to replace both Javascript and PHP. (I can't see any problem with this. It's not like either of these languages have a large install base.)

One of the things I wanted to change was to turn the assignment operator into an assignment command, removing the ability to make use of the returned value.

```<code>x=1;          /* Assignment. */
if (x==1) {}  /* Comparison. */
x==1;         /* Error or warning, I've not decided yet. */
if (x=1) {}   /* Error. */
</code>```

I know that this would mean that those one-line functions that C people love so much would no longer work. I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation.

Or is it? Are there any practical uses of the assignment operator's return value that could not be trivially rewritten? (For any language that has such a concept.)

答:
The greatest benefit to my mind of having assignment be an expression is that it allows your grammar to be simpler if one of your goals is that "everything is an expression"--a goal of LISP in particular.

Python does not have this; it has expressions and statements, assignment being a statement.  But because Python defines a lambda form as being a single parameterized expression, that means you can't assign variables inside a lambda.  This is inconvenient at times, but not a critical issue, and it's about the only downside in my experience to having assignment be a statement in Python.

One way to allow assignment, or rather the effect of assignment, to be an expression without introducing the potential for if(x=1) accidents that C has is to use a LISP-like let construct, such as (let ((x 2) (y 3)) (+ x y)) which might in your language evaluate as 5.  Using let this way need not technically be assignment at all in your language, if you define let as creating a lexical scope.  Defined that way, a let construct could be compiled the same way as constructing and calling a nested closure function with arguments.

On the other hand, if you are simply concerned with the if(x=1) case, but want assignment to be an expression as in C, maybe just choosing different tokens will suffice.  Assignment: x := 1 or x <- 1.  Comparison: x == 1.  Syntax error: x = 1.


问:
Is node.js a good fit for background processing?
I'm slowly learning node.js and have a small project I want to start.  The project will have a lot of background processes (downloading data from external sites, parsing CSV files, etc.).

A big "win" for me and node is the fact it uses JavaScript for both client and server.  I code in Java and JavaScript in my day job but am also pretty good at Ruby.

But, like I said, it seems attractive to use one language everywhere and JS seems to fit that bill.

However, I haven't had much experience in using JS for running background jobs.  Ruby seems to excel at this.  And I'm not opposed to using it.  So what are your thoughts on going 100% JS for this?  I realize very large projects require custom solutions.  I'm just wondering if it's worth the effort.  Or, should I just stick with Ruby on those kind of chores?

Opinions appreciated.

Thanks

答: One issue to be aware of is what occurs when processing large files in an asynchronous environment: if your input stream (a file) is faster than your output stream (the db) then you won't be able to handle the input data events quick enough. This will either overwhelm some piece of your system (output stream or memory) or cause you to lose data. For this reason, data processing asynchronously can be a little tricky. But as the article I linked to explains, the ability to pause the input stream makes it possible to throttle in a manner that fits your situation.</p>


问:
MVC Widget optimization when accessing CSS and Resources
So we're trying to re-imagine our web solution in an MVC fashion. Going from an old webforms based solution to working with ASP.NET MVC with a bootstrap main menu and adding functionality in the forms of widgets using HTML.Action() that calls a controller and action to fill in the information on that part of the page.

We're now thinking of how the CSS and resources that we are going to be getting for each widget separately in their own controller can be effectively used in this scenario.

If we only use HTML.Action and letting a controller add our functionality to the page, we lose our connection to the page as a whole, and we could possibly load the resource package and CSS for the same type of objects over and over again. How would one solve this and make it possible for our web portal to have knowledge over which css and resource files have already been added to the solution?

答:
The browser will not request a resource from your server constantly with making some significant (and not easy to find) configuration changes. This goes for CSS, javascript files, images, etc. When the web server provides the initial request to a client, it also includes an expiration time for most objects. The browser will look at that expiration time when requesting updates from the server. If the time hasn't expired, the browser will not request the same object again. This is true of all of the big browsers.

If you configure your web server to set the timeout on everything being served to 0 or -1 (depending on what server you use),  then the client will request every item every time it needs to display something. That places a huge extra load on your server.

In an MS MVC scenario, the only place you may even want to think about setting the timeout to 0 is on your web services or web api. Most of your application is going to be sending the same thing to all of your users.  And MVC is smart enough to figure out what needs to be a 0 timeout for most things.

UPDATE

You can dynamically add CSS to the HEAD. See this answer on StackOverflow Dynamically Add CSS To Page Via Javascript.


问:
Is it a bad practice to include all the enums in one file and use it in multiple classes?
I'm an aspiring game developer, I work on occasional indie games, and for a while I've been doing something which seemed like a bad practice at first, but I really want to get an answer from some experienced programmers here.

Let's say I have a file called enumList.h where I declare all the enums I want to use in my game:

```<code>// enumList.h

enum materials_t { WOOD, STONE, ETC };
enum entity_t { PLAYER, MONSTER };
enum map_t { 2D, 3D };
// and so on.

// Tile.h
#include "enumList.h"
#include <vector>

class tile
{
    // stuff
};
</code>```

The main idea is that I declare all enums in the game in 1 file, and then import that file when I need to use a certain enum from it, rather than declaring it in the file where I need to use it. I do this because it makes things clean, I can access every enum in 1 place rather than having pages openned solely for accessing one enum.

Is this a bad practice and can it affect performance in any way?

答:
Yes, it is bad practice to do so on a big project.  KISS.

Young coworker renamed a simple variable in a core .h file and 100 engineers waited 45 minutes for all their files to rebuild, which affected everyone's performance.  ;)

All projects start small, balloon over the years, and we curse those who took early shortcuts for creating technical debt.
Best practices, keep global .h content limited to what's necessarily global.


问:
Is this a good example of open recursion?
I understand open recursion as the process of a method on a class calling another method on a class using a keyword such as this, but whereby the method call may actually be bound to a sub class at run time.

Is this a fair demonstration of open recursion?

```<code>class Sup {
    go() {
        alert('sup');
    }

    callGo() {
        this.go();
    }
}

class Sub extends Sup {
    go() {
        alert('sub');
    }
}

var sub = new Sub();
sub.callGo();
</code>```

答:
No, in this case Sub will simply override Sup.go() and so only Sub.go() is executed.

Open recursion is when a method in a class can call itself (i.e. its own signature) which is recursion, but due to dynamic dispatch (can) actually call a subclass, which is open recursion:

class A {
    protected int counter = 1;
    public void loop() {
        System.out.println("Looping " + counter + " times");
        counter++;
        this.loop();
    }
}

class B extends A {
    @Override
    public void loop() {
        if(counter == 1) {
             super.loop();
        }
    }
}
```

Now new A().loop() will loop indefinitly*, but new B().loop() will terminate.

* It will actually cause a stack overflow unless you have an inifinite stack or tail-call optimization

Body:
No, in this case Sub will simply override Sup.go() and so only Sub.go() is executed.

Open recursion is when a method in a class can call itself (i.e. its own signature) which is recursion, but due to dynamic dispatch (can) actually call a subclass, which is open recursion:

class A {
    protected int counter = 1;
    public void loop() {
        System.out.println("Looping " + counter + " times");
        counter++;
        this.loop();
    }
}

class B extends A {
    @Override
    public void loop() {
        if(counter == 1) {
             super.loop();
        }
    }
}

Now new A().loop() will loop indefinitly*, but new B().loop() will terminate.

* It will actually cause a stack overflow unless you have an inifinite stack or tail-call optimization


答:
From everything anyone (including lawyers) have told me, you can get sued for anything.  The real question is whether or not you will, and whether or not they'll win.

One lawyer told me, "if anyone thinks you're big enough to take a run at, then that means you're successful."  In other words, suing someone is a big undertaking.  It has to be worth someone's time and money.

That doesn't mean you won't get a strongly worded cease and desist letter.

(Of course, IANAL).

Assuming you didn't directly copy any code or screenshots or whatever, then you're probably not breaking copyright rules.  Patents, on the other hand, are overly broad, and if someone big enough to sue doesn't like you, they likely have a patent that covers anything you might be writing.

Further reading: it would be worth looking at the "look and feel" part of this case.

Title: Can I get sued over duplicating another program's UI?

Body:
If I see something I like in another application, and create something similar from the ground up in a commercial product, could I get sued over it?

Of course it would be styled to look differently, however most of the functionality would be the same since the functionality is what I liked about it. It also would not be the entire system, just a part of one.

I live in the US.


问:
Physics Engine with Fixed-Point Positions
Fixed-point object locations allow for worlds which are much more scale-able. Using a 64-bit integer (per dimension), and 0.1 millimeter precision, a world can be created which is 100% numerically stable, and 12,000 astronomical units across.

I have been looking all over the internet, and I can't seem to find a physics engine which supports this.

Is there a 3D physics engine in existence, which uses fixed-point (i.e. Integer, hopefully int-64) values for entities' positions?

It's for a really ambitious sci-fi game I'm working on.

答:
I've never heard of one.

And there are reasons why nobody does it that way.

First, numerically-intense computations moved to floating point decades ago because of the amount of headache involved in keeping track of the decimal point across multiplications, divisions, and exponentiations.  The moment you hit transcendental functions (sin, cos, exp), you die horribly.

Second, one light-year is about 63000 AU, so your "universe" is 1/5 of a light-year across.  Given that Alpha Centauri is 4.3 light-years from Sol, your Universe is limited to one (1) solar system.  AT THE MOMENT, it is summer on Pluto, meaning that it is just inside Neptune's orbit, and so the whole basic Solar system is 60 AU across (30 AU to Neptune's orbit, x 2).

You're proposing using 64 bits.  It only takes about 55 bits to represent the basic Solar system, to your desired precision.  Use another bit, and go out to 120 AU across.

Now, x86 extended precision (double) is 80 bits, with a sign bit, a 15-bit exponent, and a 64-bit mantissa.  Your suggestion uses a 64-bit mantissa, with NO exponent.  Bluntly, you aren't saving yourself any trouble by writing your own fixed-point math package.

My suggestion to you is this: Develop a prototype of your game, using plain vanilla extended precision floating point, and see whether you encounter numerical instabilities.


问:
Should I extract specific functionality into a function and why?
I have a large method which does 3 tasks, each of them can be extracted into a separate function. If I'll make an additional functions for each of that tasks, will it make my code better or worse and why?

Obviously, it'll make less lines of code in the main function, but there'll be additional function declarations, so my class will have additional methods, which I believe isn't good, because it'll make the class more complex.

Should I do that before I wrote all the code or should I leave it until everything is done and then extract functions?

答:
I'm sure you've heard the advice that variables should be scoped as tightly as possible, and I hope you agree with it.  Well, functions are containers of scope, and in smaller functions the scope of the local variables is smaller.  It's much clearer how and when they are supposed to be used and it's harder to use them in the wrong order or before they are initialized.

Also, functions are containers of logical flow.  There's only one way in, the ways out are clearly marked, and if the function is short enough, the internal flows should be obvious.  This has the effect of reducing cyclomatic complexity which is a reliable way to reduce the rate of defects.


问:
Why lifting of binary function into the list monads goes over all the element combinations?
Say, if I want to create a cartesian product of two lists, I could do (here in Haskell, but I can do the same e.g. in Scala or any other FP-able language)

```<code>cartesianProd = liftM2 (,)
</code>```

then

```<code>>cartesianProd [1,2] [3,4]
>[(1,3),(1,4),(2,3),(2,4)]
</code>```

Obviously, using (lifting) + instead of tuple pairing, will produce list of sums of all combinations.

By FP definition, "lifting is a concept which allows you to transform a function into a corresponding function within another (usually more general) setting." The way I understand it, if I have monadic arguments, I can transform my binary function to work with them via liftM2. Where does the cartesian product comes from, though? Intuitively, I would expect [(1,3), (2,4)] from the example above.

答:
I don't know much about Haskell but for your question I would recommend reading this section of Learn You a Haskell: http://learnyouahaskell.com/functors-applicative-functors-and-monoids#the-newtype-keyword .

The gist of it is that some types could satisfy classes such as functor or monad laws in more than one way. Lists for instance could be applicative functors in the way that they are in the haskell standard library (applies the function to every possibility from each list), or they could be applicative functors in the way that you expect them to (apply the function to corresponding elements in the lists).

The designers of haskell thought that the cartesian product version was more useful so they made that the default interpretation. They also however realized that your interpretation also satisfied appropriate laws and was also useful and so you should try running the below code.

```<code>module Main where

import qualified Control.Applicative as CA

prod :: (CA.Applicative f) => f a -> f b -> f (a, b)
prod = CA.liftA2 (,)

main :: IO ()
main = do
        print $ prod [1,2] [3,4]
        print . CA.getZipList $ prod (CA.ZipList [1,2]) (CA.ZipList [3,4])
</code>```

Body:
I don't know much about Haskell but for your question I would recommend reading this section of Learn You a Haskell: http://learnyouahaskell.com/functors-applicative-functors-and-monoids#the-newtype-keyword .

The gist of it is that some types could satisfy classes such as functor or monad laws in more than one way. Lists for instance could be applicative functors in the way that they are in the haskell standard library (applies the function to every possibility from each list), or they could be applicative functors in the way that you expect them to (apply the function to corresponding elements in the lists).

The designers of haskell thought that the cartesian product version was more useful so they made that the default interpretation. They also however realized that your interpretation also satisfied appropriate laws and was also useful and so you should try running the below code.

module Main where

import qualified Control.Applicative as CA

prod :: (CA.Applicative f) => f a -> f b -> f (a, b)
prod = CA.liftA2 (,)

main :: IO ()
main = do
        print $ prod [1,2] [3,4]
        print . CA.getZipList $ prod (CA.ZipList [1,2]) (CA.ZipList [3,4])


问:
How to improve upon Bloch's Builder Pattern, to make it more appropriate for use in highly-extendable classes
I have been greatly influenced by Joshua Bloch's Effective Java book (2nd edition), probably more so than with any programming book I've read. In particular, his Builder Pattern (item 2) has had the greatest effect.

Despite Bloch's builder getting me much farther in the couple of months than in my past ten years of programming, I am still finding myself hitting the same wall: Extending classes with self-returning method-chains is at best discouraging, and at worst a nightmare--especially when generics come into play, and especially with self-referential generics (such as Comparable<T extends Comparable<T>>).

There are two primary needs that I have, only the second of which I'd like to focus on in this question:

The first problem is "how to share self-returning method chains, without having to re-implement them in every...single...class?" For those who may be curious, I've addressed this part at the bottom of this answer-post, but it's not what I want to focus on here.

The second problem, which I am asking for comment on, is "how can I implement a builder in classes that are themselves intended to be extended by many other classes?" Extending a class with a builder is naturally more difficult than extending one without. Extending a class that has a builder that also implements Needable, and therefore has significant generics associated to it, is unwieldy.

So that is my question: How can I improve upon (what I call) the Bloch Builder, so I can feel free to attach a builder to any class--even when that class is meant to be a "base class" that may be extended and sub-extended many times over--without discouraging my future-self, or users of my library, because of the extra baggage the builder (and its potential generics) impose on them?

Addendum

My question focuses on part 2 above, but I wanted to elaborate a bit on problem one, including how I've dealt with it:

The first problem is "how to share self-returning method chains, without having to re-implement them in every...single...class?" This is not to prevent extending classes from having to re-implement these chains, which, of course, they must--rather, how to prevent non-sub-classes, that want to take advantage of these method chains, from having to re-implement every self-returning function in order for their users to be able to take advantage of them? For this I've come up with a needer-needable design that I'll print the interface skeletons for here, and leave it at that for now. It has worked well for me (this design was years in the making...the hardest part was avoiding circular dependencies):

```<code>public interface Chainable  {
    Chainable chainID(boolean b_setStatic, Object o_id);
    Object getChainID();
    Object getStaticChainID();
}
public interface Needable<O,R extends Needer> extends Chainable  {
    boolean isAvailableToNeeder();
    Needable<O,R> startConfigReturnNeedable(R n_eeder);
    R getActiveNeeder();
    boolean isNeededUsable();
    R endCfg();
}
public interface Needer  {
    void startConfig(Class<?> cls_needed);
    boolean isConfigActive();
    Class getNeededType();
    void neeadableSetsNeeded(Object o_fullyConfigured);
}
</code>```

答:
I have created what, for me, is a big improvement over Josh Bloch's Builder Pattern. Not to say in any way that it is "better", just that in a very specific situation, it does provide some advantages--the biggest being that it decouples the builder from its to-be-built class.

I have thoroughly documented this alternative below, which I call the Blind Builder Pattern.

Design Pattern: Blind Builder

As an alternative to Joshua Bloch's Builder Pattern (item 2 in Effective Java, 2nd edition), I have created what I call the "Blind Builder Pattern", which shares many of the benefits of the Bloch Builder and, aside from a single character, is used in exactly the same way. Blind Builders have the advantage of

decoupling the builder from its enclosing class, eliminating a circular dependency,

greatly reduces the size of the source code of (what is no longer) the enclosing class, and

allows the ToBeBuilt class to be extended without having to extend its builder.

In this documentation, I'll refer to the class-being-built as the "ToBeBuilt" class.

A class implemented with a Bloch Builder

A Bloch Builder is a public static class contained inside the class that it builds. An example:

public class UserConfig  {
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
   public UserConfig(UserConfig.Cfg uc_c)  {      //CONSTRUCTOR
      //transfer
         try  {
            sName  = uc_c.sName;
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_c");
         }
         iAge      = uc_c.iAge;
         sFavColor = uc_c.sFavColor;
      //VALIDATE ALL FIELDS HERE
   }
   public String toString()  {
      return  "name=" + sName + ", age=" + iAge + ", sFavColor=" + sFavColor;
   }
   //builder...START
   public static class Cfg  {
      private String sName    ;
      private int    iAge     ;
      private String sFavColor;
      public Cfg(String s_name)  {
         sName = s_name;
      }
      //self-returning setters...START
         public Cfg age(int i_age)  {
            iAge = i_age;
            return  this;
         }
         public Cfg favoriteColor(String s_color)  {
            sFavColor = s_color;
            return  this;
         }
      //self-returning setters...END
      public UserConfig build()  {
         return  (new UserConfig(this));
      }
   }
   //builder...END
}

Instantiating a class with a Bloch Builder

UserConfig uc = new UserConfig.Cfg("Kermit").age(50).favoriteColor("green").build();

The same class, implemented as a Blind Builder

There are three parts to a Blind Builder, each of which is in a separate source-code file:

The ToBeBuilt class (in this example: UserConfig)

Its "Fieldable" interface

The builder

1. The to-be-built class

The to-be-built class accepts its Fieldable interface as its only constructor parameter. The constructor sets all internal fields from it, and validates each. Most importantly, this ToBeBuilt class has no knowledge of its builder.

public class UserConfig  {
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
    public UserConfig(UserConfig_Fieldable uc_f)  {      //CONSTRUCTOR
      //transfer
         try  {
            sName  = uc_f.getName();
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f");
         }
         iAge      = uc_f.getAge();
         sFavColor = uc_f.getFavoriteColor();
      //VALIDATE ALL FIELDS HERE
   }
   public String toString()  {
      return  "name=" + sName + ", age=" + iAge + ", sFavColor=" + sFavColor;
   }
}

As noted by one smart commenter (who inexplicably deleted their answer), if the ToBeBuilt class also implements its Fieldable, its one-and-only constructor can be used as both its primary and copy constructor (a disadvantage is that fields are always validated, even though it is known that the fields in the original ToBeBuilt are valid).

2. The "Fieldable" interface

The fieldable interface is the "bridge" between the ToBeBuilt class and its builder, defining all fields necessary to build the object. This interface is required by the ToBeBuilt classes constructor, and is implemented by the builder. Since this interface may be implemented by classes other than the builder, any class may easily instantiate the ToBeBuilt class, without being forced to use its builder. This also makes it easier to extend the ToBeBuilt class, when extending its builder is not desirable or necessary.

As described in a below section, I do not document the functions in this interface at all.

public interface UserConfig_Fieldable  {
   String getName();
   int getAge();
   String getFavoriteColor();
}

3. The builder

The builder implements the Fieldable class. It does no validation at all, and to emphasize this fact, all of its fields are public and mutable. While this public accessibility is not a requirement, I prefer and recommend it, because it re-enforces the fact that validation does not occur until the ToBeBuilt's constructor is called. This is important, because it is possible for another thread to manipulate the builder further, before it is passed to the ToBeBuilt's constructor. The only way to guarantee the fields are valid--assuming the builder cannot somehow "lock" its state--is for the ToBeBuilt class to do the final check.

Finally, as with the Fieldable interface, I do not document any of its getters.

public class UserConfig_Cfg implements UserConfig_Fieldable  {
   public String sName    ;
   public int    iAge     ;
    public String sFavColor;
    public UserConfig_Cfg(String s_name)  {
       sName = s_name;
    }
    //self-returning setters...START
       public UserConfig_Cfg age(int i_age)  {
          iAge = i_age;
          return  this;
       }
       public UserConfig_Cfg favoriteColor(String s_color)  {
          sFavColor = s_color;
          return  this;
       }
    //self-returning setters...END
    //getters...START
       public String getName()  {
          return  sName;
       }
       public int getAge()  {
          return  iAge;
       }
       public String getFavoriteColor()  {
          return  sFavColor;
       }
    //getters...END
    public UserConfig build()  {
       return  (new UserConfig(this));
    }
}

Instantiating a class with a Blind Builder

UserConfig uc = new UserConfig_Cfg("Kermit").age(50).favoriteColor("green").build();

The only difference is "UserConfig_Cfg" instead of "UserConfig.Cfg"

Notes

Disadvantages:

Blind Builders cannot access private members of its ToBeBuilt class,

They are more verbose, as getters are now required in both the builder and in the interface.

Everything for a single class is no longer in just one place.

Compiling a Blind Builder is straight-forward:

ToBeBuilt_Fieldable

ToBeBuilt

ToBeBuilt_Cfg

The Fieldable interface is entirely optional

For a ToBeBuilt class with few required fields--such as this UserConfig example class, the constructor could simply be

public UserConfig(String s_name, int i_age, String s_favColor)  {

And called in the builder with

public UserConfig build()  {
   return  (new UserConfig(getName(), getAge(), getFavoriteColor()));
}

Or even by eliminating the getters (in the builder) altogether:

   return  (new UserConfig(sName, iAge, sFavoriteColor));

By passing fields directly, the ToBeBuilt class is just as "blind" (unaware of its builder) as it is with the Fieldable interface. However, for ToBeBuilt classes which and are intended to be "extended and sub-extended many times" (which is in the title of this post), any changes to any field necessitates changes in every sub-class, in every builder and ToBeBuilt constructor. As the number of fields and sub-classes increases, this becomes impractical to maintain.

(Indeed, with few necessary fields, using a builder at all may be overkill. For those interested, here is a sampling of some of the larger Fieldable interfaces in my personal library.)

Secondary classes in sub-package

I choose to have all builder and the Fieldable classes, for all Blind Builders, in a sub-package of their ToBeBuilt class. The sub-package is always named "z". This prevents these secondary classes from cluttering up the JavaDoc package list. For example

library.class.my.UserConfig

library.class.my.z.UserConfig_Fieldable

library.class.my.z.UserConfig_Cfg

Validation example

As mentioned above, all validation occurs in the ToBeBuilt's constructor. Here is the constructor again with example validation code:

public UserConfig(UserConfig_Fieldable uc_f)  {
   //transfer
      try  {
         sName  = uc_f.getName();
      }  catch(NullPointerException rx)  {
         throw  new NullPointerException("uc_f");
      }
      iAge      = uc_f.getAge();
      sFavColor = uc_f.getFavoriteColor();
   //validate          (should really pre-compile the patterns...)
      try  {
         if(!Pattern.compile("\\w+").matcher(sName).matches())  {
            throw  new IllegalArgumentException("uc_f.getName() (\"" + sName + "\") may not be empty, and must contain only letters digits and underscores.");
         }
      }  catch(NullPointerException rx)  {
         throw  new NullPointerException("uc_f.getName()");
      }
      if(iAge < 0)  {
         throw  new IllegalArgumentException("uc_f.getAge() (" + iAge + ") is less than zero.");
      }
      try  {
         if(!Pattern.compile("(?:red|blue|green|hot pink)").matcher(sFavColor).matches())  {
            throw  new IllegalArgumentException("uc_f.getFavoriteColor() (\"" + uc_f.getFavoriteColor() + "\") is not red, blue, green, or hot pink.");
         }
      }  catch(NullPointerException rx)  {
         throw  new NullPointerException("uc_f.getFavoriteColor()");
      }
}

Documenting Builders

This section is applicable to both Bloch Builders and Blind Builders. It demonstrates how I document the classes in this design, making setters (in the builder) and their getters (in the ToBeBuilt class) directly cross-referenced to each other--with a single mouse-click, and without the user needing to know where those functions actually reside--and without the developer having to document anything redundantly.

Getters: In the ToBeBuilt classes only

Getters are documented only in the ToBeBuilt class. The equivalent getters both in the _Fieldable and _Cfg classes are ignored. I don't document them at all.

/**

The user's age.

   @return  An int representing the user's age.
   @see  UserConfig_Cfg#age(int)
   @see  getName()
 **/
public int getAge()  {
   return  iAge;
}

The first @see is a link to its setter, which is in the builder class.

Setters: In the builder-class

The setter is documented as if it is in the ToBeBuilt class, and also as if it does the validation (which really is done by the ToBeBuilt's constructor). The asterisk ("*") is a visual clue indicating that the link's target is in another class.

/**

Set the user's age.

   @param  i_age  May not be less than zero. Get with {@code UserConfig#getName() getName()}*.
   @see  #favoriteColor(String)
 **/
public UserConfig_Cfg age(int i_age)  {
   iAge = i_age;
   return  this;
}

Further information

Why should a builder be an inner class instead of in its own class file?

Benefit of using static inner builder class

Putting it all together: The full source of the Blind Builder example, with complete documentation

UserConfig.java

import  java.util.regex.Pattern;
/**

Information about a user -- [builder: UserConfig_Cfg]

Validation of all fields occurs in this classes constructor. However, each validation requirement is document only in the builder's setter functions.

{@code java xbn.z.xmpl.lang.builder.finalv.UserConfig}

 **/
public class UserConfig  {
   public static final void main(String[] igno_red)  {
      UserConfig uc = new UserConfig_Cfg("Kermit").age(50).favoriteColor("green").build();
      System.out.println(uc);
   }
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
   /**

Create a new instance. This sets and validates all fields.

      @param  uc_f  May not be {@code null}.
    **/
   public UserConfig(UserConfig_Fieldable uc_f)  {
      //transfer
         try  {
            sName  = uc_f.getName();
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f");
         }
         iAge      = uc_f.getAge();
         sFavColor = uc_f.getFavoriteColor();
      //validate
         try  {
            if(!Pattern.compile("\\w+").matcher(sName).matches())  {
               throw  new IllegalArgumentException("uc_f.getName() (\"" + sName + "\") may not be empty, and must contain only letters digits and underscores.");
            }
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f.getName()");
         }
         if(iAge < 0)  {
            throw  new IllegalArgumentException("uc_f.getAge() (" + iAge + ") is less than zero.");
         }
         try  {
            if(!Pattern.compile("(?:red|blue|green|hot pink)").matcher(sFavColor).matches())  {
               throw  new IllegalArgumentException("uc_f.getFavoriteColor() (\"" + uc_f.getFavoriteColor() + "\") is not red, blue, green, or hot pink.");
            }
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f.getFavoriteColor()");
         }
   }
   //getters...START
      /**

The user's name.

         @return  A non-{@code null}, non-empty string.
         @see  UserConfig_Cfg#UserConfig_Cfg(String)
         @see  #getAge()
         @see  #getFavoriteColor()
       **/
      public String getName()  {
         return  sName;
      }
      /**

The user's age.

         @return  A number greater-than-or-equal-to zero.
         @see  UserConfig_Cfg#age(int)
         @see  #getName()
       **/
      public int getAge()  {
         return  iAge;
      }
      /**

The user's favorite color.

         @return  A non-{@code null}, non-empty string.
         @see  UserConfig_Cfg#age(int)
         @see  #getName()
       **/
      public String getFavoriteColor()  {
         return  sFavColor;
      }
   //getters...END
   public String toString()  {
      return  "getName()=" + getName() + ", getAge()=" + getAge() + ", getFavoriteColor()=" + getFavoriteColor();
   }
}

UserConfig_Fieldable.java

/**

Required by the {@link UserConfig} {@code UserConfig#UserConfig(UserConfig_Fieldable) constructor}.

 **/
public interface UserConfig_Fieldable  {
   String getName();
   int getAge();
   String getFavoriteColor();
}

UserConfig_Cfg.java

import  java.util.regex.Pattern;
/**

Builder for {@link UserConfig}.

Validation of all fields occurs in the UserConfig constructor. However, each validation requirement is document only in this classes setter functions.

 **/
public class UserConfig_Cfg implements UserConfig_Fieldable  {
   public String sName    ;
   public int    iAge     ;
   public String sFavColor;
   /**

Create a new instance with the user's name.

      @param  s_name  May not be {@code null} or empty, and must contain only letters, digits, and underscores. Get with {@code UserConfig#getName() getName()}{@code ()}.
    **/
   public UserConfig_Cfg(String s_name)  {
      sName = s_name;
   }
   //self-returning setters...START
      /**

Set the user's age.

         @param  i_age  May not be less than zero. Get with {@code UserConfig#getName() getName()}{@code ()}.
         @see  #favoriteColor(String)
       **/
      public UserConfig_Cfg age(int i_age)  {
         iAge = i_age;
         return  this;
      }
      /**

Set the user's favorite color.

         @param  s_color  Must be {@code "red"}, {@code "blue"}, {@code green}, or {@code "hot pink"}. Get with {@code UserConfig#getName() getName()}{@code ()}*.
         @see  #age(int)
       **/
      public UserConfig_Cfg favoriteColor(String s_color)  {
         sFavColor = s_color;
         return  this;
      }
   //self-returning setters...END
   //getters...START
      public String getName()  {
         return  sName;
      }
      public int getAge()  {
         return  iAge;
      }
      public String getFavoriteColor()  {
         return  sFavColor;
      }
   //getters...END
   /**

Build the UserConfig, as configured.

      @return  (new {@link UserConfig#UserConfig(UserConfig_Fieldable) UserConfig}(this))
    **/
   public UserConfig build()  {
      return  (new UserConfig(this));
   }
}

Body:
I have created what, for me, is a big improvement over Josh Bloch's Builder Pattern. Not to say in any way that it is "better", just that in a very specific situation, it does provide some advantages--the biggest being that it decouples the builder from its to-be-built class.

I have thoroughly documented this alternative below, which I call the Blind Builder Pattern.

Design Pattern: Blind Builder

As an alternative to Joshua Bloch's Builder Pattern (item 2 in Effective Java, 2nd edition), I have created what I call the "Blind Builder Pattern", which shares many of the benefits of the Bloch Builder and, aside from a single character, is used in exactly the same way. Blind Builders have the advantage of

decoupling the builder from its enclosing class, eliminating a circular dependency,

greatly reduces the size of the source code of (what is no longer) the enclosing class, and

allows the ToBeBuilt class to be extended without having to extend its builder.

In this documentation, I'll refer to the class-being-built as the "ToBeBuilt" class.

A class implemented with a Bloch Builder

A Bloch Builder is a public static class contained inside the class that it builds. An example:

public class UserConfig  {
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
   public UserConfig(UserConfig.Cfg uc_c)  {      //CONSTRUCTOR
      //transfer
         try  {
            sName  = uc_c.sName;
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_c");
         }
         iAge      = uc_c.iAge;
         sFavColor = uc_c.sFavColor;
      //VALIDATE ALL FIELDS HERE
   }
   public String toString()  {
      return  "name=" + sName + ", age=" + iAge + ", sFavColor=" + sFavColor;
   }
   //builder...START
   public static class Cfg  {
      private String sName    ;
      private int    iAge     ;
      private String sFavColor;
      public Cfg(String s_name)  {
         sName = s_name;
      }
      //self-returning setters...START
         public Cfg age(int i_age)  {
            iAge = i_age;
            return  this;
         }
         public Cfg favoriteColor(String s_color)  {
            sFavColor = s_color;
            return  this;
         }
      //self-returning setters...END
      public UserConfig build()  {
         return  (new UserConfig(this));
      }
   }
   //builder...END
}

Instantiating a class with a Bloch Builder

UserConfig uc = new UserConfig.Cfg("Kermit").age(50).favoriteColor("green").build();

The same class, implemented as a Blind Builder

There are three parts to a Blind Builder, each of which is in a separate source-code file:

The ToBeBuilt class (in this example: UserConfig)

Its "Fieldable" interface

The builder

1. The to-be-built class

The to-be-built class accepts its Fieldable interface as its only constructor parameter. The constructor sets all internal fields from it, and validates each. Most importantly, this ToBeBuilt class has no knowledge of its builder.

public class UserConfig  {
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
    public UserConfig(UserConfig_Fieldable uc_f)  {      //CONSTRUCTOR
      //transfer
         try  {
            sName  = uc_f.getName();
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f");
         }
         iAge      = uc_f.getAge();
         sFavColor = uc_f.getFavoriteColor();
      //VALIDATE ALL FIELDS HERE
   }
   public String toString()  {
      return  "name=" + sName + ", age=" + iAge + ", sFavColor=" + sFavColor;
   }
}

As noted by one smart commenter (who inexplicably deleted their answer), if the ToBeBuilt class also implements its Fieldable, its one-and-only constructor can be used as both its primary and copy constructor (a disadvantage is that fields are always validated, even though it is known that the fields in the original ToBeBuilt are valid).

2. The "Fieldable" interface

The fieldable interface is the "bridge" between the ToBeBuilt class and its builder, defining all fields necessary to build the object. This interface is required by the ToBeBuilt classes constructor, and is implemented by the builder. Since this interface may be implemented by classes other than the builder, any class may easily instantiate the ToBeBuilt class, without being forced to use its builder. This also makes it easier to extend the ToBeBuilt class, when extending its builder is not desirable or necessary.

As described in a below section, I do not document the functions in this interface at all.

public interface UserConfig_Fieldable  {
   String getName();
   int getAge();
   String getFavoriteColor();
}

3. The builder

The builder implements the Fieldable class. It does no validation at all, and to emphasize this fact, all of its fields are public and mutable. While this public accessibility is not a requirement, I prefer and recommend it, because it re-enforces the fact that validation does not occur until the ToBeBuilt's constructor is called. This is important, because it is possible for another thread to manipulate the builder further, before it is passed to the ToBeBuilt's constructor. The only way to guarantee the fields are valid--assuming the builder cannot somehow "lock" its state--is for the ToBeBuilt class to do the final check.

Finally, as with the Fieldable interface, I do not document any of its getters.

public class UserConfig_Cfg implements UserConfig_Fieldable  {
   public String sName    ;
   public int    iAge     ;
    public String sFavColor;
    public UserConfig_Cfg(String s_name)  {
       sName = s_name;
    }
    //self-returning setters...START
       public UserConfig_Cfg age(int i_age)  {
          iAge = i_age;
          return  this;
       }
       public UserConfig_Cfg favoriteColor(String s_color)  {
          sFavColor = s_color;
          return  this;
       }
    //self-returning setters...END
    //getters...START
       public String getName()  {
          return  sName;
       }
       public int getAge()  {
          return  iAge;
       }
       public String getFavoriteColor()  {
          return  sFavColor;
       }
    //getters...END
    public UserConfig build()  {
       return  (new UserConfig(this));
    }
}

Instantiating a class with a Blind Builder

UserConfig uc = new UserConfig_Cfg("Kermit").age(50).favoriteColor("green").build();

The only difference is "UserConfig_Cfg" instead of "UserConfig.Cfg"

Notes

Disadvantages:

Blind Builders cannot access private members of its ToBeBuilt class,

They are more verbose, as getters are now required in both the builder and in the interface.

Everything for a single class is no longer in just one place.

Compiling a Blind Builder is straight-forward:

ToBeBuilt_Fieldable

ToBeBuilt

ToBeBuilt_Cfg

The Fieldable interface is entirely optional

For a ToBeBuilt class with few required fields--such as this UserConfig example class, the constructor could simply be

public UserConfig(String s_name, int i_age, String s_favColor)  {

And called in the builder with

public UserConfig build()  {
   return  (new UserConfig(getName(), getAge(), getFavoriteColor()));
}

Or even by eliminating the getters (in the builder) altogether:

   return  (new UserConfig(sName, iAge, sFavoriteColor));

By passing fields directly, the ToBeBuilt class is just as "blind" (unaware of its builder) as it is with the Fieldable interface. However, for ToBeBuilt classes which and are intended to be "extended and sub-extended many times" (which is in the title of this post), any changes to any field necessitates changes in every sub-class, in every builder and ToBeBuilt constructor. As the number of fields and sub-classes increases, this becomes impractical to maintain.

(Indeed, with few necessary fields, using a builder at all may be overkill. For those interested, here is a sampling of some of the larger Fieldable interfaces in my personal library.)

Secondary classes in sub-package

I choose to have all builder and the Fieldable classes, for all Blind Builders, in a sub-package of their ToBeBuilt class. The sub-package is always named "z". This prevents these secondary classes from cluttering up the JavaDoc package list. For example

library.class.my.UserConfig

library.class.my.z.UserConfig_Fieldable

library.class.my.z.UserConfig_Cfg

Validation example

As mentioned above, all validation occurs in the ToBeBuilt's constructor. Here is the constructor again with example validation code:

public UserConfig(UserConfig_Fieldable uc_f)  {
   //transfer
      try  {
         sName  = uc_f.getName();
      }  catch(NullPointerException rx)  {
         throw  new NullPointerException("uc_f");
      }
      iAge      = uc_f.getAge();
      sFavColor = uc_f.getFavoriteColor();
   //validate          (should really pre-compile the patterns...)
      try  {
         if(!Pattern.compile("\\w+").matcher(sName).matches())  {
            throw  new IllegalArgumentException("uc_f.getName() (\"" + sName + "\") may not be empty, and must contain only letters digits and underscores.");
         }
      }  catch(NullPointerException rx)  {
         throw  new NullPointerException("uc_f.getName()");
      }
      if(iAge < 0)  {
         throw  new IllegalArgumentException("uc_f.getAge() (" + iAge + ") is less than zero.");
      }
      try  {
         if(!Pattern.compile("(?:red|blue|green|hot pink)").matcher(sFavColor).matches())  {
            throw  new IllegalArgumentException("uc_f.getFavoriteColor() (\"" + uc_f.getFavoriteColor() + "\") is not red, blue, green, or hot pink.");
         }
      }  catch(NullPointerException rx)  {
         throw  new NullPointerException("uc_f.getFavoriteColor()");
      }
}

Documenting Builders

This section is applicable to both Bloch Builders and Blind Builders. It demonstrates how I document the classes in this design, making setters (in the builder) and their getters (in the ToBeBuilt class) directly cross-referenced to each other--with a single mouse-click, and without the user needing to know where those functions actually reside--and without the developer having to document anything redundantly.

Getters: In the ToBeBuilt classes only

Getters are documented only in the ToBeBuilt class. The equivalent getters both in the _Fieldable and _Cfg classes are ignored. I don't document them at all.

/**
   <P>The user's age.</P>
   @return  An int representing the user's age.
   @see  UserConfig_Cfg#age(int)
   @see  getName()
 **/
public int getAge()  {
   return  iAge;
}

The first @see is a link to its setter, which is in the builder class.

Setters: In the builder-class

The setter is documented as if it is in the ToBeBuilt class, and also as if it does the validation (which really is done by the ToBeBuilt's constructor). The asterisk ("*") is a visual clue indicating that the link's target is in another class.

/**
   <P>Set the user's age.</P>
   @param  i_age  May not be less than zero. Get with {@code UserConfig#getName() getName()}*.
   @see  #favoriteColor(String)
 **/
public UserConfig_Cfg age(int i_age)  {
   iAge = i_age;
   return  this;
}

Further information

Why should a builder be an inner class instead of in its own class file?

Benefit of using static inner builder class

Putting it all together: The full source of the Blind Builder example, with complete documentation

UserConfig.java

import  java.util.regex.Pattern;
/**
   <P>Information about a user -- <I>[builder: UserConfig_Cfg]</I></P>
   <P>Validation of all fields occurs in this classes constructor. However, each validation requirement is document only in the builder's setter functions.</P>
   <P>{@code java xbn.z.xmpl.lang.builder.finalv.UserConfig}</P>
 **/
public class UserConfig  {
   public static final void main(String[] igno_red)  {
      UserConfig uc = new UserConfig_Cfg("Kermit").age(50).favoriteColor("green").build();
      System.out.println(uc);
   }
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
   /**
      <P>Create a new instance. This sets and validates all fields.</P>
      @param  uc_f  May not be {@code null}.
    **/
   public UserConfig(UserConfig_Fieldable uc_f)  {
      //transfer
         try  {
            sName  = uc_f.getName();
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f");
         }
         iAge      = uc_f.getAge();
         sFavColor = uc_f.getFavoriteColor();
      //validate
         try  {
            if(!Pattern.compile("\\w+").matcher(sName).matches())  {
               throw  new IllegalArgumentException("uc_f.getName() (\"" + sName + "\") may not be empty, and must contain only letters digits and underscores.");
            }
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f.getName()");
         }
         if(iAge < 0)  {
            throw  new IllegalArgumentException("uc_f.getAge() (" + iAge + ") is less than zero.");
         }
         try  {
            if(!Pattern.compile("(?:red|blue|green|hot pink)").matcher(sFavColor).matches())  {
               throw  new IllegalArgumentException("uc_f.getFavoriteColor() (\"" + uc_f.getFavoriteColor() + "\") is not red, blue, green, or hot pink.");
            }
         }  catch(NullPointerException rx)  {
            throw  new NullPointerException("uc_f.getFavoriteColor()");
         }
   }
   //getters...START
      /**
         <P>The user's name.</P>
         @return  A non-{@code null}, non-empty string.
         @see  UserConfig_Cfg#UserConfig_Cfg(String)
         @see  #getAge()
         @see  #getFavoriteColor()
       **/
      public String getName()  {
         return  sName;
      }
      /**
         <P>The user's age.</P>
         @return  A number greater-than-or-equal-to zero.
         @see  UserConfig_Cfg#age(int)
         @see  #getName()
       **/
      public int getAge()  {
         return  iAge;
      }
      /**
         <P>The user's favorite color.</P>
         @return  A non-{@code null}, non-empty string.
         @see  UserConfig_Cfg#age(int)
         @see  #getName()
       **/
      public String getFavoriteColor()  {
         return  sFavColor;
      }
   //getters...END
   public String toString()  {
      return  "getName()=" + getName() + ", getAge()=" + getAge() + ", getFavoriteColor()=" + getFavoriteColor();
   }
}

UserConfig_Fieldable.java

/**
   <P>Required by the {@link UserConfig} {@code UserConfig#UserConfig(UserConfig_Fieldable) constructor}.</P>
 **/
public interface UserConfig_Fieldable  {
   String getName();
   int getAge();
   String getFavoriteColor();
}

UserConfig_Cfg.java

import  java.util.regex.Pattern;
/**
   <P>Builder for {@link UserConfig}.</P>
   <P>Validation of all fields occurs in the <CODE>UserConfig</CODE> constructor. However, each validation requirement is document only in this classes setter functions.</P>
 **/
public class UserConfig_Cfg implements UserConfig_Fieldable  {
   public String sName    ;
   public int    iAge     ;
   public String sFavColor;
   /**
      <P>Create a new instance with the user's name.</P>
      @param  s_name  May not be {@code null} or empty, and must contain only letters, digits, and underscores. Get with {@code UserConfig#getName() getName()}{@code ()}.
    **/
   public UserConfig_Cfg(String s_name)  {
      sName = s_name;
   }
   //self-returning setters...START
      /**
         <P>Set the user's age.</P>
         @param  i_age  May not be less than zero. Get with {@code UserConfig#getName() getName()}{@code ()}.
         @see  #favoriteColor(String)
       **/
      public UserConfig_Cfg age(int i_age)  {
         iAge = i_age;
         return  this;
      }
      /**
         <P>Set the user's favorite color.</P>
         @param  s_color  Must be {@code "red"}, {@code "blue"}, {@code green}, or {@code "hot pink"}. Get with {@code UserConfig#getName() getName()}{@code ()}*.
         @see  #age(int)
       **/
      public UserConfig_Cfg favoriteColor(String s_color)  {
         sFavColor = s_color;
         return  this;
      }
   //self-returning setters...END
   //getters...START
      public String getName()  {
         return  sName;
      }
      public int getAge()  {
         return  iAge;
      }
      public String getFavoriteColor()  {
         return  sFavColor;
      }
   //getters...END
   /**
      <P>Build the UserConfig, as configured.</P>
      @return  <CODE>(new {@link UserConfig#UserConfig(UserConfig_Fieldable) UserConfig}(this))</CODE>
    **/
   public UserConfig build()  {
      return  (new UserConfig(this));
   }
}


答:
Well the reason is that the M in liftM2 means monad. In fact liftM2 is defined as

```<code> liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
 liftM2 f a b = do
   a' <- a
   b' <- b
   return (f a b)
</code>```

This relies on monadic bind operation >>= :: m a -> (a -> m b) -> m b. In a list, >>= is equivalent to concatMap, so your code is

```<code> cartProd f a b = concatMap (\a' -> concatMap (\b' -> f a b) b) a
</code>```

This applies (,) to each and every pair of as and bs in our list and so we get a cartesian product. Incidentally it would be better practice to use liftA2 which works over all monads + applicatives.

I'll skip over the thorny issue of why the list monad is concatMap and relegate that till you come across it in a nice book like LYAH or Real World Haskell. Instead the behavior you want is zip or the more general zipWith :: (a -> b -> c) -> [a] -> [b] -> [c].

Title: Why lifting of binary function into the list monads goes over all the element combinations?

Body:
Say, if I want to create a cartesian product of two lists, I could do (here in Haskell, but I can do the same e.g. in Scala or any other FP-able language)

```<code>cartesianProd = liftM2 (,)
</code>```

then

```<code>>cartesianProd [1,2] [3,4]
>[(1,3),(1,4),(2,3),(2,4)]
</code>```

Obviously, using (lifting) + instead of tuple pairing, will produce list of sums of all combinations.

By FP definition, "lifting is a concept which allows you to transform a function into a corresponding function within another (usually more general) setting." The way I understand it, if I have monadic arguments, I can transform my binary function to work with them via liftM2. Where does the cartesian product comes from, though? Intuitively, I would expect [(1,3), (2,4)] from the example above.

Body:
Well the reason is that the M in liftM2 means monad. In fact liftM2 is defined as

 liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
 liftM2 f a b = do
   a' <- a
   b' <- b
   return (f a b)

This relies on monadic bind operation >>= :: m a -> (a -> m b) -> m b. In a list, >>= is equivalent to concatMap, so your code is

 cartProd f a b = concatMap (\a' -> concatMap (\b' -> f a b) b) a

This applies (,) to each and every pair of as and bs in our list and so we get a cartesian product. Incidentally it would be better practice to use liftA2 which works over all monads + applicatives.

I'll skip over the thorny issue of why the list monad is concatMap and relegate that till you come across it in a nice book like LYAH or Real World Haskell. Instead the behavior you want is zip or the more general zipWith :: (a -> b -> c) -> [a] -> [b] -> [c].


问:
How does accumulating large amounts of business logic on the model objects make building strong service contracts harder?
I heard a couple of times that putting business logic in database models is bad down the road.

I just read this in blog of a Rackspace employee:
The Django ORM also tended to have us accumulate large amounts of business logic on the model objects, which made building strong service contracts even harder.

But it seems logical to me that if you have an Invoice model to encapsulate a lot of invoicing logic there. Seems very similar to what we've been taught in OOP. Could you show me how this is wrong? Please include a practical example if possible.

Benefit of "put logic in models"

What I see as a big benefit of putting logic in models is that users of the models don't have to worry about how they can use stuff, they just use it and it works, can't break anything.

Let me elaborate with an example:
So if you don't put logic in models, then you probably have this code elsewhere, let's say it's in api. If you want to change a state of an Invoice, what do you do? Do you do invoice.state = new_state or do you read the api code to see if there's some method there that changes the state?

This is confusing and error prone. How do you fix this issue then?

答:
Wrong is a big word.

The reason why you shouldn't put it in the DB, is because the vocabulary of (most) DB systems is incredibly limited. There is nothing about "SELECT", "INSERT", "UPDATE", "DELETE" that allows you to fluently express why something is happening and to what it is a reaction, in domain language terms.

As to the second part of your question: the problem with ORMs is that they usually force you to organize your domain objects in ways contrary to what you want.

A simple and common example is that you generally want to encapsulate a lot of stuff inside domain classes, but ORMs need access to the fields and properties of classes to be able to persist them, so you wind up exposing everything, potentially breaking encapsulation.

What I generally tend to find a good idea is to separate your ORM model from your domain model and create a way to inflate domain model objects from ORM model objects.


答:
Its a similar question to "should do you do validation in the presentation layer?"

And the answer is the same - generally business logic needs to go in the middle tier, but there are always exceptions where it is appropriate.

If you're putting a lot of logic in the data layer then you're doing it wrong, you're polluting the data access and retrieval code with a load of other stuff that doesn't belong there and you're writing a client-server style program.

In OO terms, your middle tier should be taking a "raw" Customer data object and a set of Product objects and combining them to produce an Invoice object that is sent downstream. Note that there is no Invoice data directly stored in the DB, just customers, products and their orders.

Its a little bit of a poor example, as apart from combining data into new object there's no business logic being applied (unless you have complicated tax rules maybe) and if all you're doing is jiggling data then its a great example of what should go into the Data layer. A rule of thumb could be "if you have to modify that data then it has to go in the middle tier"

Title: How does accumulating large amounts of business logic on the model objects make building strong service contracts harder?

Body:
I heard a couple of times that putting business logic in database models is bad down the road.

I just read this in blog of a Rackspace employee:
The Django ORM also tended to have us accumulate large amounts of business logic on the model objects, which made building strong service contracts even harder.

But it seems logical to me that if you have an Invoice model to encapsulate a lot of invoicing logic there. Seems very similar to what we've been taught in OOP. Could you show me how this is wrong? Please include a practical example if possible.

Benefit of "put logic in models"

What I see as a big benefit of putting logic in models is that users of the models don't have to worry about how they can use stuff, they just use it and it works, can't break anything.

Let me elaborate with an example:
So if you don't put logic in models, then you probably have this code elsewhere, let's say it's in api. If you want to change a state of an Invoice, what do you do? Do you do invoice.state = new_state or do you read the api code to see if there's some method there that changes the state?

This is confusing and error prone. How do you fix this issue then?


答:
The problem with Django models (or rails active record its the same pattern) its that this is not a behavior model of your application, its a data model, with this architectures your application are tightly coupled to the database. Problems of this types of applications:

The design of the database dominates the design of your application. Normally you end up with one table -> one class.

As a consequence of the previous design, when the application grows the "model" classes tend to grow and grow, the typical "fat model" problem.

Your business logic and your persistence technology are totally coupled, you cannot change one thing without changing the another.

You view the database as a global data storage, you can access every table/model from every point of the application. When the application grows this type of systems are really difficult to maintain because of the highly coupling. Kent Beck wrote about this a long time ago: http://www.threeriversinstitute.org/blog/?p=338 , he call this type of systems "connected" vs a more moduler approach.

For easy database centric applications with not complex domain models Django ORM (or rails active record) can do a good job. The problem is when your system grows, a lot of people in the rails and django community are looking at things like hexagonal architecture or Domain Driven Design for finding ways to deal with complex domain.

For an intro, this is a great talk from matt wayne (cucumber author): http://www.youtube.com/watch?v=CGN4RFkhH2M, its about rails, but, its exactly the same problem.


问:
Algorithm for searching images within images
I can't google this question, because I can't come up with a good query, so let me describe what I want and maybe someone will be able to suggest a way forward for me.

I need to solve the following problem: there is an list of jpg images. There is also one "source" jpg image. I need to find if this image is a cropped image from the list. I do not know what software was used to crop and have no control over what jpeg quality setting is used in the source image. I do realize that if the setting is to low the result can't be unrecognisable, but I still would like somehow be able to check the source image against each of the images in the list and get a "yes" if a match found.

Ideally I'd like a .net library for this, but I also could implement it myself if only I knew a proper algorithm (and it's description is not 100 pages long). Since jpeg is lossy format I can't do bit by bit comparison, and even if I could it's not immediately obvious how to find the correct part of image to compare so this does not take too long, since the crop can be of arbitrary size in arbitrary spot of the image.

In my case the crop is never resized or rotated, so it kind of makes it simpler, but I'm still not sure where to start.

答:
You will need some image pattern recognisation or comparing library.,

You should probably take a look at OpenCV and VLfeat.

For instance you can use SIFT to compare images, which also works pretty good on  rotated and cropped images (which you don't even need ).

VLfeat's SIFT is pretty cool

Note: You can also use other algoritms to compare, sift is just an example.


答:
To actually answer the question, yes there are numerous uses of this although they are slightly niche.

For example in Java:

```<code>while ((Object ob = x.next()) != null) {
    // This will loop through calling next() until it returns null
    // The value of the returned object is available as ob within the loop
}
</code>```

The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next().

It's already been mentioned that you can assign multiple variables in one step.

```<code>x = y = z = 3;
</code>```

This sort of thing is the most common use, but creative programmers will always come up with more.

Title: What is the benefit of having the assignment operator return a value?

Body:
I'm developing a language which I intend to replace both Javascript and PHP. (I can't see any problem with this. It's not like either of these languages have a large install base.)

One of the things I wanted to change was to turn the assignment operator into an assignment command, removing the ability to make use of the returned value.

```<code>x=1;          /* Assignment. */
if (x==1) {}  /* Comparison. */
x==1;         /* Error or warning, I've not decided yet. */
if (x=1) {}   /* Error. */
</code>```

I know that this would mean that those one-line functions that C people love so much would no longer work. I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation.

Or is it? Are there any practical uses of the assignment operator's return value that could not be trivially rewritten? (For any language that has such a concept.)

Body:
To actually answer the question, yes there are numerous uses of this although they are slightly niche.

For example in Java:

while ((Object ob = x.next()) != null) {
    // This will loop through calling next() until it returns null
    // The value of the returned object is available as ob within the loop
}

The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next().

It's already been mentioned that you can assign multiple variables in one step.

x = y = z = 3;

This sort of thing is the most common use, but creative programmers will always come up with more.


答:
There are certain elements, within any UI that any computer user is going to expect. You would be amazed (or not) at how many of those elements are patented, or have a patent pending. I'm sorry, but that has gotten so absurd that trying to work around them would be equally absurd.

When it comes to stuff that is actually original, you do have to be careful. Don't clone someone's artwork for menu icons. Obviously, don't clone a trademark logo and substitute your own slight changes to it.

A good programmer is going to do their best to make a very intuitive interface. Given the features of the software, there are only so many ways you can arrange all of those buttons while still keeping the program intuitive. This means, a programmer at foo is likely to make something remarkably similar to a programmer at bar, if both were given the same project specification.

In short, don't let other people's accomplishments stop you from innovating. If you are in doubt about something, you probably shouldn't be doing it.


答:
I know that this would mean that those one-line functions that C people love so much would no longer work. I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation.

Indeed. This is nothing new, all the safe subsets of the C language have already made this conclusion.

MISRA-C, CERT-C and so on all ban assignment inside conditions, simply because it is dangerous.

There exists no case where code relying on assignment inside conditions cannot be rewritten.

Furthermore, such standards also warns against writing code that relies on the order of evaluation. Multiple assignments on one single row x=y=z; is such a case. If a row with multiple assignments contains side effects (calling functions, accessing volatile variables etc), you cannot know which side effect that will occur first.

There are no sequence points between the evaluation of the operands. So we cannot know whether the subexpression y gets evaluated before or after z: it is unspecified behavior in C. Thus such code is potentially unreliable, non-portable and non-conformant to the mentioned safe subsets of C.

The solution would have been to replace the code with y=z; x=y;. This adds a sequence point and guarantees the order of evaluation.

So based on all the problems this caused in C, any modern language would do well to both ban assignment inside conditions, as well as multiple assignments on one single row.


答:
I'm not an expert on image processing or anything, but how about this:

first make sure you have tools available to extract pixel info out of your JPEG images. Stuff such as RGB values, for example should suffice (as you don't have an alpha channel in a JPEG). Depending on your platform of choice, this may already come bundled in (for example the Java JDK has the ImageIO and BufferedImage that can help you do this. For PHP, you can use imagecolorat)

You'll get a matrix for the pixels, where the values inside that matrix are a structure depicting the color values of each pixel.

In order to do the check you need, since we're talking about the posibility that the cropped image will no longer be identical in pixel color value to the original from which it was cropped, you can start of by finding a way to avearage the properties of the cropped image, and then try to find a similar average value (with a given tolerance) in a same-sized area on the possible "parent" picture. There's a good suggestion on how to do this kind of "sub-matrix" matching here

Title: Algorithm for searching images within images

Body:
I can't google this question, because I can't come up with a good query, so let me describe what I want and maybe someone will be able to suggest a way forward for me.

I need to solve the following problem: there is an list of jpg images. There is also one "source" jpg image. I need to find if this image is a cropped image from the list. I do not know what software was used to crop and have no control over what jpeg quality setting is used in the source image. I do realize that if the setting is to low the result can't be unrecognisable, but I still would like somehow be able to check the source image against each of the images in the list and get a "yes" if a match found.

Ideally I'd like a .net library for this, but I also could implement it myself if only I knew a proper algorithm (and it's description is not 100 pages long). Since jpeg is lossy format I can't do bit by bit comparison, and even if I could it's not immediately obvious how to find the correct part of image to compare so this does not take too long, since the crop can be of arbitrary size in arbitrary spot of the image.

In my case the crop is never resized or rotated, so it kind of makes it simpler, but I'm still not sure where to start.


问:
Fixing bugs may lead to delayed feedback
I worked in a group in Microsoft that developed the upgrade to the Microsoft Security Essentials antivirus. For a year we worked on the next version of the product. We had 6 milestones (milestone each two months). Most of the features were developed in the first few milestones, and for the second part of the year these features were refined and bugs were fixed. Each milestone a larger portion of users (subscribed to the various alpha/beta programs) would get the product and provide feedback.

I was told by the program managers in the project that the advantage of this approach is that there is more time for potential users to give feedback on the features, so it is preferable to ship all the features as soon as possible.

However Scrum doesn't advocate this approach. In Scrum are you advised to deliver completely tested and functional piece of software and not half baked and brittle features. This approach has various benefits, but it also has some drawbacks. One of them is that feedback is delayed.

So which approach do you prefer and why?

答:
It sounds like they main driver for this is requirements.

The user are providing "real life" feature and usability information.

So they get the basic feature out there and make it better by getting input on it, as opposed the get it right first approach which maybe assumes more requirement analysis has been put in up front.


答:
"In Scrum are you advised to deliver completely tested and functional piece of software and not half baked and brittle features"

You seem to be conflating user feedback - do they like the features that have been delivered, do they find it useful, does it meet a need, does it have arcane bugs when (mis)used in ways the developers didn't anticipate - with basic performance, stability and functional correctness. Scrum is echoing the agile manifesto claim to value working software, with the emphasis on WORKING in the sense that it does what the product owner asked of you. User feedback is only then valuable in that it aligns the product owner's vision with the market. If you ship non-working software the user feedback will rather predictably be "WTF?".

Title: Fixing bugs may lead to delayed feedback

Body:
I worked in a group in Microsoft that developed the upgrade to the Microsoft Security Essentials antivirus. For a year we worked on the next version of the product. We had 6 milestones (milestone each two months). Most of the features were developed in the first few milestones, and for the second part of the year these features were refined and bugs were fixed. Each milestone a larger portion of users (subscribed to the various alpha/beta programs) would get the product and provide feedback.

I was told by the program managers in the project that the advantage of this approach is that there is more time for potential users to give feedback on the features, so it is preferable to ship all the features as soon as possible.

However Scrum doesn't advocate this approach. In Scrum are you advised to deliver completely tested and functional piece of software and not half baked and brittle features. This approach has various benefits, but it also has some drawbacks. One of them is that feedback is delayed.

So which approach do you prefer and why?


问:
Should I save a simple list cookie in Javascript or PHP?
I am currently making a simple list tool. You can click a checkbox to mark it as done and if you navigate away from the page/close the browser and reload, it will still be saved. So it's pretty much just a visual difference.

For this, I'm wondering, should I use PHP or Javascript to set a cookie to save the data on whether or not the item was checked?

If not, should I use $_SESSION? I haven't been able to find a simple solution relevant to my concern, from my searches almost all of them are related to saving usernames/passwords, which of course have an added security aspect too.

Thanks.

答:
For the choice there are multiple questions to be asked. How "relevant"is the data, is it shared across browsers, howl on should it live etc.

Cookies are bound to a specific browser. The lifetime can be set from "during this browser session" to some arbitrary date in future. This doesn't mean the lifetime will be reached as there are different events at which a browser might kill the cookies. If its only you and your browser this might work .. ut the list might suddenly be lost.

PHP Session storage is stored on a server and referenced by a cookie or URL parameter. It has a relatively short lifetime (by default 24 hours) as by default the session files reside in the /tmp directory a cleanup process (ie. on server reboot after power failure or update) might delete them. Still not persistent. (PHP session handling could be configured in a quite persistent way but that's ignoring the purpose)

So both probably aren't good. Alternatives? Yes there are!

HTML 5 introduces browser local storage for more data. That is useful to have nicer access to the data and more flexibility in usage. Downside is that this still depends on using the same browser all the time and somecleanup miht free it unexpectedly.

A more robust solution is to use some server-side (PHP) script which stores the list in a database (or simple file) in a place where it is unaffected from cleanup tasks. By that the list can be access from different browsers (i.e desktop and mobile device) and won't easily go away.


问:
Is there a name for the 'break n' construct?
In a conversation earlier this week I was discussing certain language features, and I realized I don't have a good word / phrase to describe a particular feature.

Some languages, such as PHP, have a language construct which allows break and continue statements to accept a numeric parameter indicating which block should be affected. For example:

for ($i = 0; $i < 10; $i++)
    for ($j = 10; $j > 0; $j--)
        if ($j == $i)
            break 2;
echo $i;
```

<p>Because <code>break 2;</code> causes the outer loop to break, the output is <code>1</code>. If this were <code>break 1;</code> or just <code>break;</code> the output would be <code>10</code>. </p>

<p>C# does not have any such construct. The equivalent would something like this:</p>

<pre class="lang-cs prettyprint-override"><code>for (i = 0; i < 10; i++) {
    bool broken = false;
    for (j = 10; j > 0; j--) {
        if (j == i) {
            broken = true;
            break;
        }
    }
    if (broken)
        break;
}
Console.WriteLine(i);
</code>```

But of course, this could also be accomplished using a goto.

So my question is, what do you call this? Is there a specific name for this "break n" construct? I'd like to be able to say "Language X has parametric break and continue statements", or something like that.

答:
Java has this and it is called a "labelled break" from what I've seen.

From Oracle's Java Tutorial on Branching Statements:

The break statement has two forms: labeled and unlabeled. ... An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.

In your PHP example it's not really "labelled" per-se (although you could consider the 2 an implicit label) but more like a "relative" or "nested" break. Any of those adjectives should work.

PS - I'm surprised C# didn't steal that from Java since they took just about everything else.


问:
Live share prices for a side project
Me and some of my friends would want to start a side project which we will work at our spare time. Here is our criteria

1) A challenging project which will teach us skills which has business value in the future.

2) A potential to make money from the project itself.

Quite obvious targets.

We are looking into the possibility to create a live price feed. We understand we cannot match the ones in the market now. But we are looking into the possibility to provide a feed which could at least provide a "live" feed, even though it cannot match the real time performance provided by the insane hardware and software resources the "biggies" could provide.

If we could host the feed in a website which can show prices even 5 minutes late, that could do.

The current skills pool is C++ and C#.

We have WPF, asp.net, silverlight skills for UI (UI doesn't matter much anyway)

The questions

1)How is it possible to get the raw price feeds for cheap(or free)?

2)Is it possible to do this idea at least as proof of concept(which means it might not have any commercial value) in a year by 3 developers working 20 hours a week?

3)Is there any information available in the internet to start with?

4)Is there any open source projects in this area?

答:
OK, things might have changed but this is what I can tell from working in the business of providing that data (albeit several years ago):

it doesn't come cheap

delayed data is cheaper than live data (that's one big reason why most stock quotes you find on website tickers are delayed by 15 minutes to over an hour, the cost that way is radically lower)

I can't see how you're going to create something new here as your plan seems to be to take a feed from a provider and just repost that through some other channel without doing anything with it. That's going to be a problem with most providers as they won't allow you to resell their data as is.

There are unlikely to be open source projects about this as the data is proprietary and not publicly available (you might find some screen scrapers that steal data from a website listing prices, but those mechanisms are a) unreliable (those websites change regularly) and b) a violation of the terms of use of those websites

To provide a full service platform would likely take you more than 3 people and more than a year, but you could create the raw basics in less than that if your skills with your chosen tools are good enough.

If I were you I'd start by creating my own feed, using some trending algorithm seeded with maybe real stock data you pull from say Euronext or NYSE websites for start values. That way you simulate real data without having to buy it (of course it won't be at all accurate or reflecting reality, but it's going to be free and as a simulation it works fine).

Store the incoming feed data in some database and you have your dataset that's constantly getting new data points for you to work with.

Title: Live share prices for a side project