问:
Should testers be equivalent to programmers?
I've been reading Joel Spolsky's old article about "Top Five (Wrong) Reasons You Don't Have Testers". it's an old article date back to 2000, but it's insightful as most of its content make sense after a decade.

I cant agree more about the importance of test in order to produce qualify software.

But there is one paragraph talking about what to deal with when top testers moved on and causing tester shortage, I really can't agree with Joel, although what he stated is still the case even today.

In his analysis, I clearly felt a sense that Joel is saying "testers are inferior to programmers". A lot of people around me have this kind of prejudice. I don't know where does this come from, but I don't think this right. even myself is not willing to be a tester( but that's not because I think testers are inferior but rather testers are treated inferior ).  but I don't think this is right.

The way I think to prevent the out-flow of top testers is to treat them equivalently as top programmers, are they not qualified in terms of contributions to the project ? another important aspect is that we know testers have to work intimately with devs to better fulfill their job, in a culture where Managers inherently demeaning testers how would they fulfill their job ?

答:
I work in QA dong testing.  Testing today is moving from 'the temp goes to the web site and tries to break it' to 'QA technical developer is embedded with the engineering group and is writing automated tests with them."

So yes, the way to retain good testers is use them as engineers.

You will now see this in top companies.  For example google "google quality engineer" to look at what Google is doing in this area.  You will see positions that list quality engineers - rather than "software testers".

How to get this going at your company?  This is hard because you're actually trying to change some set opinions.

My advice is to become an expert and an evangelist in Testing.  You should study and learn the latest techniques and terms and approaches, then work within your company to slowly start introducing them.  Ask to give informal demos and do them filled with enthusiasm.  You have to also be consistent.  talking about the right way constantly and repeatedly - but without being annoying and irritating.  Obviously soft skills are key here!

Another obstacle btw is getting management buy-in for salary.  You need to consider paying a top quality engineer $100k-$150k (Boston,MA market, you salary mileage may vary).  This can be a shock for companies paying $40k for a manual tester!


问:
UI design and confirmation paradigm
I just saw this lecture by Spolsky, where he questions the need for choices and confirmation dialogs. At some point he has a MacOS settings window and he mentions that "now some are getting rid of the OK button". The window indeed has no OK (or cancel) button. Changing a setting makes it change, when you're done configuring, you close that window, period.

Being a long time Windows user and a recent Mac owner, the difference is noticeable at first. I looked for the OK button for a while, only to find out, quite naturally and painlessly, that there was none. I expressed satisfaction and went on my merry way.

However, I'm curious to know if this UI design pattern would succeed in the Windows-based world. Granted that if Microsoft brought it out with say Windows-8 (fat chance, I know), people would get used to it eventually. But is there some experience out there of such an approach, of changing the "confirmation paradigm" on a platform where it's so prevalent? Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?

TL;DR: Remove OK/cancel confirmation, what happens?

EDIT:

Mac GUI for appearance settings.

答:
But is there some experience out there of such an approach, of changing the "confirmation paradigm" on a platform where it's so prevalent?

Introducing a total change of paradigm in an established environment and for just a routine operation would stall a great number of users.

Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?

If the change does not address a known problem, but just introduces something different "to try it out", then this change will likely invoke all of the mentioned emotions except for happiness.

For me this sort of dialogs is one thing that I strongly dislike. Why? Because it's not immediately clear how it works. You have to learn and adopt this way of thinking. Meaning it's not good for inexperienced users.

Look at the meaning of the word "dialog". It's the two-way communication between the machine and the user in this case. The natural way would be:

```<code>U: Change the setting
M: I changed it (text message or something)
</code>```

or

```<code>U: Change the setting
U: Click the save button
M: Indicates reaction (message, dialog disappearance, page refresh)
</code>```

How the Mac dialog spins off:

```<code>U: Change the setting
M: ..... (silence)
</code>```

The user is perplexed. Did it work or not? Unknown. The user checks the things out.
Dialog didn't happen.

ContentLicense: CC BY-SA 2.5

Title: UI design and confirmation paradigm

Body:
But is there some experience out there of such an approach, of changing the "confirmation paradigm" on a platform where it's so prevalent?

Introducing a total change of paradigm in an established environment and for just a routine operation would stall a great number of users.

Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?

If the change does not address a known problem, but just introduces something different "to try it out", then this change will likely invoke all of the mentioned emotions except for happiness.

For me this sort of dialogs is one thing that I strongly dislike. Why? Because it's not immediately clear how it works. You have to learn and adopt this way of thinking. Meaning it's not good for inexperienced users.

Look at the meaning of the word "dialog". It's the two-way communication between the machine and the user in this case. The natural way would be:

U: Change the setting
M: I changed it (text message or something)

or

U: Change the setting
U: Click the save button
M: Indicates reaction (message, dialog disappearance, page refresh)

How the Mac dialog spins off:

U: Change the setting
M: ..... (silence)

The user is perplexed. Did it work or not? Unknown. The user checks the things out.
Dialog didn't happen.


问:
Problems with Facades and then evolution in software
I initially started a project with Facades and Polymorphism as a way to create simple extensible design following SOLID Principles.
Here is a sample code:

```<code>public interface IInterface
{
    void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects);
}

public class SampleClass : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //some data layer code
        //and a for loop to fill OutputPocoObject object and add it to list
    }
}
</code>```

I have number of classes such as above which are created in runtime with the help of factory( not shown here for the sake of simplicity)

Recently after couple of months I see that there are different requirements emerging in my project, which I attempted to solve by the help of Polymorphism and I see that I am stuck with violating DRY principles.

Here is a sample code of this situation:

```<code>public class SampleClass2 : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //some data layer code
        //and a for loop to fill OutputPocoObject object and add it to list
        // there is a property in OutputPocoObject which is set to 1
    }
}

public class SampleClass3 : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //same code as above
        //with only one difference that  property in OutputPocoObject is set to 5 here
    }
}
</code>```

One Simple solution will be to add a control parameter to interface such as:

```<code>public interface IInterface
{
    void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects, int controlParameter);
}
</code>```

but I don't know whether this is such a better idea? Or whether it might introduce some complexity in my design?

答: Create a class that converts InputPocoObject into an OutputPocoObject (an adapter class) and pass it - or multiple instances of it - into the FillList method.

ContentLicense: CC BY-SA 3.0


答:
There are many ways to solve your problem. The most obvious is to create abstract base class under SampleClass2 and 3. This abstract class will implement FillList in a way that is common between those two and will also call GetNumberX() abstract method, that will return number to assign and then will be implemented accordingly in SampleClass 2 and 3.

But I'm noticing you are repeating yourself in one more thing : actually having to write the loop. Why not just have :

```<code>public interface IConverter{
    void InitializeData(); //some data layer code
    OutputPocoObject Convert(InputPocoObject in); // called for every converted object
}
</code>```

And have the looping somewhere else.

Title: Problems with Facades and then evolution in software

Body:
I initially started a project with Facades and Polymorphism as a way to create simple extensible design following SOLID Principles.
Here is a sample code:

```<code>public interface IInterface
{
    void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects);
}

public class SampleClass : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //some data layer code
        //and a for loop to fill OutputPocoObject object and add it to list
    }
}
</code>```

I have number of classes such as above which are created in runtime with the help of factory( not shown here for the sake of simplicity)

Recently after couple of months I see that there are different requirements emerging in my project, which I attempted to solve by the help of Polymorphism and I see that I am stuck with violating DRY principles.

Here is a sample code of this situation:

```<code>public class SampleClass2 : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //some data layer code
        //and a for loop to fill OutputPocoObject object and add it to list
        // there is a property in OutputPocoObject which is set to 1
    }
}

public class SampleClass3 : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //same code as above
        //with only one difference that  property in OutputPocoObject is set to 5 here
    }
}
</code>```

One Simple solution will be to add a control parameter to interface such as:

```<code>public interface IInterface
{
    void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects, int controlParameter);
}
</code>```

but I don't know whether this is such a better idea? Or whether it might introduce some complexity in my design?

Body:
There are many ways to solve your problem. The most obvious is to create abstract base class under SampleClass2 and 3. This abstract class will implement FillList in a way that is common between those two and will also call GetNumberX() abstract method, that will return number to assign and then will be implemented accordingly in SampleClass 2 and 3.

But I'm noticing you are repeating yourself in one more thing : actually having to write the loop. Why not just have :

public interface IConverter{
    void InitializeData(); //some data layer code
    OutputPocoObject Convert(InputPocoObject in); // called for every converted object
}

And have the looping somewhere else.


问:
What are proven advantages of tools like GWT over pure JavaScript frameworks?
GWT is a software stack that translates Java code and a sub-set of the Java Runtime's class library to JavaScript code.

In comparison with JavaScript toolkits, GWT can seem alienating, by nature and by usage, and overly complex to do even simple things, taking away much of the fine-grained control you'd have by using JavaScript directly.

Why would a web-developer choose to use a tool like GWT, which uses a language originally not targeted for the web, instead of using pure JavaScript and JavaScript frameworks and toolkits?

Is it measurably better, and based on what criteria?

答:
After spending years developing a web application in GWT my opinion is that GWT has so serious disadvantages that I would never use it again if I am not forced to.

DOM tree

While JavaScript performance may be better, the rendered DOM tree is often unnecessarily complex. For example, the Tree implementation uses 13+ DOM elements including a
 for each individual item. Using large trees (around 10000 items) simply freezes the browser. A pure JavaScript/HTML/CSS tree was able to handle the same amount of items easily.

Development

The modify-try cycle of pure JavaScript/HTML/CSS source can not be beaten. You just save your source file and refresh the page in the browser. This is a key factor in productivity and GWT just can not compete even by using code server.

Debugging JavaScript is absolutely easy and pleasure with the debugger of Chrome or Firebug.

Hammer Experts

The idea of using Java for everything is for developers who are "hammer experts". They are masters of their hammer so everything is a nail. I think this approach is very wrong. Using GWT also requires knowledge of CSS and HTML. Without this GWT developers often bump into problems that they find almost impossible to solve, while someone with HTML/CSS experience can come up with a solution. If the developers need this competence they can get it easier with developing in HTML.

My opinion is that most of the advantages provided by GWT are at least questionable while the disadvantages are far more serious compared to developing in pure JavaScript/HTML/CSS.

Body:
After spending years developing a web application in GWT my opinion is that GWT has so serious disadvantages that I would never use it again if I am not forced to.

DOM tree

While JavaScript performance may be better, the rendered DOM tree is often unnecessarily complex. For example, the Tree implementation uses 13+ DOM elements including a <table> for each individual item. Using large trees (around 10000 items) simply freezes the browser. A pure JavaScript/HTML/CSS tree was able to handle the same amount of items easily.

Development

The modify-try cycle of pure JavaScript/HTML/CSS source can not be beaten. You just save your source file and refresh the page in the browser. This is a key factor in productivity and GWT just can not compete even by using code server.

Debugging JavaScript is absolutely easy and pleasure with the debugger of Chrome or Firebug.

Hammer Experts

The idea of using Java for everything is for developers who are "hammer experts". They are masters of their hammer so everything is a nail. I think this approach is very wrong. Using GWT also requires knowledge of CSS and HTML. Without this GWT developers often bump into problems that they find almost impossible to solve, while someone with HTML/CSS experience can come up with a solution. If the developers need this competence they can get it easier with developing in HTML.

My opinion is that most of the advantages provided by GWT are at least questionable while the disadvantages are far more serious compared to developing in pure JavaScript/HTML/CSS.


问:
Is SOA as a concept intended to function within code or between machines over a network?
As the question states:  When implementing "SOA", is it a concept intended for communication between systems over a network or is it intended as a concept that operates within the language as a pattern?</p>

答:
If you use it within a language as a pattern, you won't need some of the features of SOA:

loose coupling

mediated communication option

asynchronous communication (fire & forget messages)

So if you just want to have a clean contract between components, you can also do it without SOA. Write a design document instead.

If you suspect  that you will need to replace some components with 3rd party components later, SOA is a viable way. However, because of the performance impact of the XML serialization/deserialization, you might need to consider using a shortcut option for internal communication. That can be done within a wrapper which uses the shortcut for internal and SOA for external communication.


答:
Service Oriented Architecture is an architecture, so the answer is neither.

It's not a design pattern within a language because it governs decisions far, far outside of the program design - notably, how all your business data is organized into services, which has a close relationship with your organizational structure. Even some of the technical concepts like fire-and-forget messaging are generally language-agnostic.

And it's not specifically related to communication between systems over a network because you could implement an entire SOA in a single process if you wanted to. The preferred method of service interaction in an SOA is in-process, and data or messages should only cross process boundaries when you specifically need to scale out. Even then, SOA is concerned with the logical rather than physical deployment. If you have a "billing service", the architecture says nothing about where that service is located, and parts of it may in fact be located in several different physical endpoints.

SOA lends itself well to distributed systems because of some of the other technical constraints it tends to impose, such as asynchrony and loose coupling. Distributed systems generally behave better when they treat the network as a network (i.e. don't depend on low latency/high bandwidth) and when components can all operate autonomously. But that's an outcome of SOA, not its goal.

An SOA is very simply the opposite of a canonical data model; in other words, each Service is like a little dictatorship that guards its data ferociously and won't share anything with any other service except what it absolutely needs in order to function. You can implement that in any programming language, and with (almost) any physical infrastructure.

Title: Is SOA as a concept intended to function within code or between machines over a network?

Body: As the question states:  When implementing "SOA", is it a concept intended for communication between systems over a network or is it intended as a concept that operates within the language as a pattern?</p>


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

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

答:
Using a framework is like choosing a library: you get some features for "free", but you also get the limitations of this code (for example, using a data-access library might prevent you to write a five-way join query).

The problem with choosing a framework is that it is harder to revert your choice once you have started using it. The reason is that frameworks usually have lots of responsibilities, and often use shortcuts (e.g. "convention over configuration") to make things easier to write. So your code ends up tightly coupled with the framework, and moving to another framework implies a total rewrite.

So it is not unprofessional to use a framework. I heard some good success stories with symfony. But it is an important choice to make. And it should be a well informed decision (you should build a small/medium project with a given framework before considering to use it for a big business).

Title: Are frameworks used for "big" websites?


答:
There are different kind of Framework:

Data frameworks (ORM) which provide basic functionalities to manage
data : eg. Doctrime2

Kernel frameworks which provide basic functionalities to manage
components : eg. cuteflow

Application frameworks provide user functionalities: eg. eZ Comps

using framework is a big choice, because they solve common problems and help the developer to make more readable and self-documented code, but they require a lot of time and experience to be dominated.

For java developer it's a little bit different because Oracle defines standard (JSR) and different framework's producer adapt their framework and it's (relatively) easy to jump from a frameowrk to another.

In PHP framework is like a diamond ... it is forever (+ or -)

Title: Are frameworks used for "big" websites?

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

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


问:
How to estimate cost with very little information?
I have a client who wants a web app that will let him do the following (as he told me word for word):

User registration

Recurring payments for users

Online conference room reservation

I am supposed to give him a cost estimate very fast and I don't have any time to do any deeper requirements analysis! How would you deal with that kind of situation? Should I just give a very broad estimate and work out the exact requirements once he has accepted the estimate? At which point do you usually gather requirements, after or before getting a contract?

答:
Welcome to the real world.

I would advise your customer that you use a daily rate of £x per day to calculate your prices, and could produce something that met that specification in a few hours by reconfiguring Outlook - but that you are not confident that its what your customer is actually after. Suggest that you meet up and spend around an hour going through the details.

If your customer is not prepared to put the time in to actually define what their needs are when they are looking for an implementer, its only going to deteriorate as the project progresses.


问:
Which concepts are pertinent to plan a “end-user documentation” strategy?
I am writing a lot of software and I feel that writing good documentation is very difficult.  Since I am not aware of any structured theory about software documentation I started to organise my knowledge in this field and hope that doing this will help me to break down information in sensible units and organise documentation efficiently.

First, I would like to make a complete list of relevant concepts, that I will investigate in other questions.

Which concepts are useful or relevant when describing user documentation? How does these concepts interact with each other? Is there any methodology I can use to analyse my software and devise a pertinent documentation strategy?

I identified the following concepts:

Information categories like recipes (“how do I…?”), references (like UNIX man pages) or expert knowledge.

User role like normal user, power user, system administrator and any other roles that the system defines like security officer, data officer, etc.

Medium like a hardcopy manual, contextual help, editable wiki.

These concepts interact one with the other and lead to a variety of questions: When is it useful to write a handbook for each role?  What should go in hard copies and what in the on-line reference?  When is it useful to run a wiki gathering “recipes”?  With these examples, I hope I could provide a useful explanations of what I understand under “concept” and “interaction” in my questions.

答:
Any strategy for providing end-user documentation is going to run headlong into the following universal law of nature:

```<code>People don't read.
</code>```

I assume that, by going to the trouble of providing end-user documentation, you wish to provide additional value to the customer, in the form of improved understanding about your software product. There are a number of ways to do that.  By far, the best way is to

```<code>Write the software so that it can be understood without any documentation.
</code>```

Failing that, there are a number of other strategies you can employ.  The traditional method of writing a manual is certainly one way, but what about:

Video tutorials

Quick-start guides

Walkthroughs

Have you ever bought a piece of furniture from Ikea or one of those online stores and put it together using instructions from the kit?  What was that experience like?  If you've done one recently, you may have noticed that it consists mostly of pictures now, with very little words.  Why?  Because people don't read, and as they say, a picture really is worth a thousand words.

I once worked for a company that struggled with this.  People would call support instead of reading the manual.  How did we finally solve it?  With several PowerPoint presentations that were page after page of simply walking the customer through each screen, dropdown and check box.  It took about four months to do it all, but our customers loved them.  They much preferred the PowerPoints over any other form of documentation that we gave them.

Video tutorials are good too, but the problem with those is they are hard to make, and they are hard to use; they have to be very short, because they're not randomly-accessible like a manual is; you kinda have to watch the whole thing.  But they're great to get the lay of the software land, so to speak.

Finally, write a manual if you need a reference guide (not a how-to).  That's what manuals are best at.

Body:
Any strategy for providing end-user documentation is going to run headlong into the following universal law of nature:

People don't read.

I assume that, by going to the trouble of providing end-user documentation, you wish to provide additional value to the customer, in the form of improved understanding about your software product. There are a number of ways to do that.  By far, the best way is to

Write the software so that it can be understood without any documentation.

Failing that, there are a number of other strategies you can employ.  The traditional method of writing a manual is certainly one way, but what about:

Video tutorials

Quick-start guides

Walkthroughs

Have you ever bought a piece of furniture from Ikea or one of those online stores and put it together using instructions from the kit?  What was that experience like?  If you've done one recently, you may have noticed that it consists mostly of pictures now, with very little words.  Why?  Because people don't read, and as they say, a picture really is worth a thousand words.

I once worked for a company that struggled with this.  People would call support instead of reading the manual.  How did we finally solve it?  With several PowerPoint presentations that were page after page of simply walking the customer through each screen, dropdown and check box.  It took about four months to do it all, but our customers loved them.  They much preferred the PowerPoints over any other form of documentation that we gave them.

Video tutorials are good too, but the problem with those is they are hard to make, and they are hard to use; they have to be very short, because they're not randomly-accessible like a manual is; you kinda have to watch the whole thing.  But they're great to get the lay of the software land, so to speak.

Finally, write a manual if you need a reference guide (not a how-to).  That's what manuals are best at.


问:
When to use (Or not) C# myVariable { set; get; }
I have been trying to wrap my head around the finer points of this today.

Essentially I have fallen in love with this format for booleans:

```<code>Class {
public static bool myBool {set; get;}
    private static void Method()
    {
        if (!myBool)
         {
            myBool = !myBool;
            // stuff that needs to be done
         }
    }
}
</code>```

Obvious things like do not use a public when a private will work and scoping properly applies. But when is this a best practice vs using a simpler:

```<code>Class {
bool myBool = true;
    private static void Method()
    {
        if (!myBool)
         {
            myBool = !myBool;
            // stuff that needs to be done
         }
    }
}
</code>```

Or do I have this backwards completely?

I understand that by using the format public static bool myBool {set; get;} I doing the following:

```<code>public static bool myBool
{
   get
   {
       return myBool;
   }
   set
   {
       myBool = valuePassedIn;
   }
}
</code>```

I feel like the first method is the best approach, but I have no idea why I think this. Is there a best from these choices? Am I doing something horribly wrong, or all three methods equivalent?

答:
The key here is the static keyword

By using static bool, your class is effectively non-threadsafe, its also prone to race conditions where the state of that boolean may be changed by other areas of the code that you are not expecting to have downstream dependency issues.

Personally, I'd avoid static variables unless you have a very good reason for using them. I'd also avoid using static functions that change state. Static functions should be stateless (and you need a good reason for using them too!)

As for using the inbuilt syntactic sugar for get/set. Its really just there to avoid boilerplate. Do users of the class need to access this member? If they do, then a public interface with get/set will probably be useful. It also allows you to change the internal representation of what those accessors do without breaking interfacing code. But thinking about what the interface to external users should be should drive your decisions to use the syntatical helpers and public status of your members.


问:
How to test the data access layer?
I have a DAO method that utilizes Spring for JDBC access. It calculates a seller's success rate of selling an item.

Here is the code:

```<code>public BigDecimal getSellingSuccessRate(long seller_id) {
    String sql = "SELECT SUM(IF(sold_price IS NOT NULL, 1, 0))/SUM(1)
                  FROM transaction WHERE seller_id = ?";
    Object[] args = {seller_id};
    return getJdbcTemplate().queryForObject(sql, args, BigDecimal.class);
}
</code>```

How should I go about testing this method or any DAO method with JUnit? What are some best practices to test the data access logic? I am thinking of testing it against an embeddable database loaded with some data, but shouldn't we do integration tests similar to a production environment in terms of RDBMS and the schema?

答:
The problem with using a 'real' database for unit testing is the setup, take down, and isolation of the tests.  You don't want to have to spin up an entirely new MySQL database and create tables and data just for one unit test.  The problems with this have to do with the external nature of the database and your test database is down, your unit tests fail.  There are also issues with making sure you have a unique database for testing with.  They can be overcome, but there is a simpler answer.

Mocking the database is one option however it doesn't test the actual queries that are run.  It can be used as a much simpler solution when you want to make sure the data from the DAO goes through the system properly.  But for testing the DAO itself you need something behind the DAO has the data and the queries run properly.

The first thing to do is use a in memory database.  HyperSQL is an excellent choice for this because it has the ability to emulate the dialect of another database - so that the minor differences between databases stays the same (data types, functions and the like).  hsqldb also has some nice features for unit testing.

```<code>db.url=jdbc:hsqldb:file:src/test/resources/testData;shutdown=true;
</code>```

This loads the state of the database (the tables, initial data) from the testData file.  shutdown=true will automatically shut down the database when the last connection closes.

Using dependency injection, have the unit tests select a different database than what the production (or test, or local) builds use.

Your DAO then uses the injected database for which you can launch tests against the database.

The unit tests will then look something like (bunch of boring stuff not included for brevity):

```<code>    @Before
    public void setUpDB() {
        DBConnection connection = new DBConnection();
        try {
            conn = connection.getDBConnection();
            insert = conn.prepareStatement("INSERT INTO data (txt, ts, active) VALUES (?, ?, ?)");
        } catch (SQLException e) {
            e.printStackTrace();
            fail("Error instantiating database table: " + e.getMessage());
        }
    }

    @After
    public void tearDown() {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void addData(String txt, Timestamp ts, boolean active) throws Exception {
        insert.setString(1, txt);
        insert.setTimestamp(2, ts);
        insert.setBoolean(3, active);
        insert.execute();
    }

    @Test
    public void testGetData() throws Exception {
        // load data
        Calendar time = Calendar.getInstance();
        long now = time.getTimeInMillis();
        long then1h = now - (60 * 60 * 1000);  // one hour ago
        long then2m = now - (60 * 1000 * 2);   // two minutes ago
        addData("active_foo", new Timestamp(then1h), true);     // active but old
        addData("inactive_bar", new Timestamp(then1h), false);  // inactive and old
        addData("active_quz", new Timestamp(then2m), true);     // active and new
        addData("inactive_baz", new Timestamp(then2m), false);  // inactive and new

        DataAccess dao = new DataAccess();
        int count = 0;
        for (Data data : dao.getData()) {
            count++;
            assertTrue(data.getTxt().startsWith("active"));
        }

        assertEquals("got back " + count + " rows instead of 1", count, 1);
    }
</code>```

And thus, you've got a unit test that calls the DAO and is using the data that was set up in an on the fly database that exists for the duration of the test.  You don't have to worry about external resources or the state of the database before the run, or restoring to a known state (well, the 'known state' is 'does not exist' which is trivial to revert to).

DBUnit can make much of what I described a simpler process in setting up the database, creating the tables and loading the data.  If you were going to need to use the actual database for some reason, this is by far the better tool to use.

The above code is part of a maven project I wrote for proof of concept TestingWithHsqldb on github

Title: How to test the data access layer?

Body:
The problem with using a 'real' database for unit testing is the setup, take down, and isolation of the tests.  You don't want to have to spin up an entirely new MySQL database and create tables and data just for one unit test.  The problems with this have to do with the external nature of the database and your test database is down, your unit tests fail.  There are also issues with making sure you have a unique database for testing with.  They can be overcome, but there is a simpler answer.

Mocking the database is one option however it doesn't test the actual queries that are run.  It can be used as a much simpler solution when you want to make sure the data from the DAO goes through the system properly.  But for testing the DAO itself you need something behind the DAO has the data and the queries run properly.

The first thing to do is use a in memory database.  HyperSQL is an excellent choice for this because it has the ability to emulate the dialect of another database - so that the minor differences between databases stays the same (data types, functions and the like).  hsqldb also has some nice features for unit testing.

db.url=jdbc:hsqldb:file:src/test/resources/testData;shutdown=true;

This loads the state of the database (the tables, initial data) from the testData file.  shutdown=true will automatically shut down the database when the last connection closes.

Using dependency injection, have the unit tests select a different database than what the production (or test, or local) builds use.

Your DAO then uses the injected database for which you can launch tests against the database.

The unit tests will then look something like (bunch of boring stuff not included for brevity):

    @Before
    public void setUpDB() {
        DBConnection connection = new DBConnection();
        try {
            conn = connection.getDBConnection();
            insert = conn.prepareStatement("INSERT INTO data (txt, ts, active) VALUES (?, ?, ?)");
        } catch (SQLException e) {
            e.printStackTrace();
            fail("Error instantiating database table: " + e.getMessage());
        }
    }

    @After
    public void tearDown() {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void addData(String txt, Timestamp ts, boolean active) throws Exception {
        insert.setString(1, txt);
        insert.setTimestamp(2, ts);
        insert.setBoolean(3, active);
        insert.execute();
    }

    @Test
    public void testGetData() throws Exception {
        // load data
        Calendar time = Calendar.getInstance();
        long now = time.getTimeInMillis();
        long then1h = now - (60 * 60 * 1000);  // one hour ago
        long then2m = now - (60 * 1000 * 2);   // two minutes ago
        addData("active_foo", new Timestamp(then1h), true);     // active but old
        addData("inactive_bar", new Timestamp(then1h), false);  // inactive and old
        addData("active_quz", new Timestamp(then2m), true);     // active and new
        addData("inactive_baz", new Timestamp(then2m), false);  // inactive and new

        DataAccess dao = new DataAccess();
        int count = 0;
        for (Data data : dao.getData()) {
            count++;
            assertTrue(data.getTxt().startsWith("active"));
        }

        assertEquals("got back " + count + " rows instead of 1", count, 1);
    }

And thus, you've got a unit test that calls the DAO and is using the data that was set up in an on the fly database that exists for the duration of the test.  You don't have to worry about external resources or the state of the database before the run, or restoring to a known state (well, the 'known state' is 'does not exist' which is trivial to revert to).

DBUnit can make much of what I described a simpler process in setting up the database, creating the tables and loading the data.  If you were going to need to use the actual database for some reason, this is by far the better tool to use.

The above code is part of a maven project I wrote for proof of concept TestingWithHsqldb on github


问:
Is it possible to be good at both programming and graphic design?
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends

答: Its more like Jack of all trades vs Master of one. I do both quite well but its tough to be an expert/up to date in both. Most of the times one is primary and the other is secondary. </p>


问:
Parallel.For Inconsistency results
I am using VB.net to write a parallel based code. I use Parallel.For to generate pairs of 500 objects or in combination C(500,2) such as the following code; but I found that it didn't always generate all combinations which should be 124750 (shown from variable Counter). No other thread was runing when this code was run. I am using a Win-7 32 Bit desktop with Intel Core i5 CPU 650@3.2GHz, 3.33 GHz and RAM 2GB. What's wrong with the code and how to solve this problem? Thank You.

```<code>    Dim Counter As Integer = 0
    Parallel.For(0, 499, Sub(i)
                     For j As Integer = i + 1 To 499
                         Counter += 1
                         Console.Write(i & ":" & j)
                     Next
                 End Sub)
    Console.Writeline("Iteration number: " & Counter)
</code>```

答:
thanks for all responds and now I have the answer.</p>

```<code>Dim total As Integer = 0
Dim numbers() = Enumerable.Range(1, 500).ToArray
Parallel.For(Of Integer)(0, numbers.Length, Function() 0,
                         Function(j, [loop], subtotal)
                           For k = j + 1 To numbers.Count - 1
                             subtotal += 1
                           Next
                           Return subtotal
                         End Function,
                         Function(x) Interlocked.Add(total, x))
</code>```

Title: Parallel.For Inconsistency results

Body:
thanks for all responds and now I have the answer.

Dim total As Integer = 0
Dim numbers() = Enumerable.Range(1, 500).ToArray
Parallel.For(Of Integer)(0, numbers.Length, Function() 0,
                         Function(j, [loop], subtotal)
                           For k = j + 1 To numbers.Count - 1
                             subtotal += 1
                           Next
                           Return subtotal
                         End Function,
                         Function(x) Interlocked.Add(total, x))


问:
How does browsing speed differ in native apps, web apps, and websites?
I read an article online which I give the reference to below which compare between Native apps and web apps, in addition to standard website. It seems from that article that native apps are faster than web apps and websites. However, that was not clear for me.

Could a native app be built to be used exactly as a website? meaning could the functions in a social website, for example, be programmed as a native app? In this case isn't that going to use a server-side language? Then what make it faster if even the website and the web app use the same thing?

http://www.mobi-cart.com/native-vs-web.jsp

答:
To me, the table on the website you mentioned has a somewhat-naïve representation of these differences. It seems to focus on pushing a native app as the best possible solution because of "browsing speed" and access to device functionality, but this may not always be what you actually want to achieve. They haven't taken into consideration other factors which can contribute to your decision on how to implement your mobile solution.

Native, Hybrid and Web apps all come with their own advantages and disadvantages that need to be considered when choosing how you will develop your mobile application. No single choice will give you everything you want. Both functional and non-functional requirements really need to be taken into consideration and "browsing speed" and access to device functionality might not always be the primary focus.

I think "browsing speed" is an ambiguous term. I would define it as "how quickly a user can find what they want" - but that might not be how their table defines it. They might be thinking of pure render time or how fast the application "feels" to a user. In either case, your website/app design as well as implementation approach both contribute to this.

In regards to "could a native app be built to be used exactly as a website?": A native application can be built essentially however you want it. You will use the device's OS-specific language to develop the application (e.g. Java for Android or Objective-C for iOS) rather than a "server-side language" like PHP or ASP.NET. It wouldn't make sense to build a native application to render HTML/Javascript though - if you wanted to take that approach a "Hybrid" application might be what you're looking for.

To clear up your confusion (and hopefully make things clear) about the development approaches - I should define the differences between the implementations:

Native

Uses OS-specific language/development approach and standard OS features and functions.

Hybrid Web

Runs in browser component (e.g. Apache Cordova)

Uses standard HTML/Javascript development approach

Bridges to native layer through plugins (in Cordova these are Java plugins exposed via Javascript)

Mobile Web

Runs in device browser

Uses standard HTML/Javascript development approach

Content delivered from Web server

As I mentioned before, each approach to mobile application development comes with advantages and disadvantages and choosing which way to go can be a tough choice. You need to consider the pro's and con's to each implementation type (this isn't an exhaustive list):

Native

Pro's

Ultimately the best UI experience, you have full control over what happens and how it happens.

You get the best performance from the device (providing your code is good)

You have access to all of the features of the device

You get OS vendor support

There's quite a large, vibrant ecosystem of developers for each device

Allows deployment to an app store (discoverability)

Con's

Device and OS specific and sensitive. You need to develop for Android, iOS, etc - individually.

Can be a steep learning curve if you've never developed a native application before.

Skill set availability in developers may be an issue in your area

Total Cost of Deployment (TCD) and Total Cost of Ownership (TCO) may be an issue

Hybrid Web

Pro's

HTML/Javascript widely used and understood, plenty of support and developers available

Browser UI is relatively easy to generate (the platform you use provides these tools usually)

Performance gain in comparison to mobile web

Gives options not available to mobile web apps (e.g. access to device hardware - depending on framework used)

Access to Push / APNs

Plugins can generally be written for frameworks to do what you like

Allows deployment to an app store (discoverability)

Con's

UI experience depends on the container's rendering of your HTML and Javascript

Performance can be an issue depending on the container and its support for what you're trying to do

An over-reliance on plugins could cause issues.

You can potentially limit your device and OS support because of container architecture complexities, bugs and compatibilities.

Mobile Web

Pro's

Almost all smartphones have a browser

No deployment issues

HTML/Javascript is widely used and understood and there's plenty of support and developers available

Single development paradigm (e.g. no need to learn Java and Objective-C)

Con's

Network issues can impact user experience (page load, etc.)

Variations across browsers

UI experience can be disappointing (especially in bad browsers)

Performance can suffer (limited access to hardware acceleration from the device)

Device feature access is limited

Discoverability can be an issue (cannot be deployed to an app store)

If you ask yourself these questions, it might also help you:

What do you want your users to be able to do?

What skills do you have access to?

What devices do you want to support?

How long do you have?

I hope this provides you with a little more clarity on the differences between the mobile development approaches, and also why more than just "speed" should impact your choice implementation.


问:
Implementing multiple generic Interfaces in java
I've need an interface that assures me a certain method, including specific signature, is available. So far his is what I have:

```<code>public interface Mappable<M> {
    M mapTo(M mappableEntity);
}
</code>```

The problem arises when a class should be mappable to multiple other entities. The ideal case would be this (not java):

```<code>public class Something implements Mappable<A>, Mappable<B> {
    public A mapTo(A someObject) {...}
    public B mapTo(B someOtherObject) {...}
}
</code>```

What would be the best way to achieve this remaining as "generic" as possible?

答:
As you saw, you can't implement the same interface twice with different type parameters (because of erasure: at runtime they are the same interfaces).

Also, this approach violates the single responsibility principle: your class should focus on being a Something (whatever that means) and should not do the mapping to A or B in addition that task.

It sounds like you really should have a Mapper<Something,A> and a Mapper<Something,B>. This way each class has a single clearly-defined responsibility and you don't run into the problem of implementing the same interface twice.


答:
This is, of course, not something you can do due to Type Erasure. At runtime, you have two methods public Object mapTo(Object), which obviously cannot coexist.

Unfortunately, what you are trying to do is simply beyond Java's type system.

Assuming your generic type is always a first class type, and not itself generic, you could achieve similar outward-facing behaviour by having the method mapTo(Object, Class), which would allow you to do runtime inspection of the given class and decide which behaviour to use. Obviously this is pretty inelegant--and will require manual casting of the return value--but I think it's the best you can do. If your generic types are themselves generic, then their generic parameters will be erased too and their Classes will be equal, so this method won't work.

However, I would point towards @Joachim's answer as well, this may be a case where you can split the behaviour out into separated components and sidestep the whole issue.

Title: Implementing multiple generic Interfaces in java

Body:
I've need an interface that assures me a certain method, including specific signature, is available. So far his is what I have:

```<code>public interface Mappable<M> {
    M mapTo(M mappableEntity);
}
</code>```

The problem arises when a class should be mappable to multiple other entities. The ideal case would be this (not java):

```<code>public class Something implements Mappable<A>, Mappable<B> {
    public A mapTo(A someObject) {...}
    public B mapTo(B someOtherObject) {...}
}
</code>```

What would be the best way to achieve this remaining as "generic" as possible?


答:
```<code>public interface IMappable<S, T> {
    T MapFrom(S source);
}

// T - target
// S - source
</code>```

If you want to map User to UserDTO and map User to UserViewModel, then you'll need two separate implementations. Don't pile up all this logic into a single class - it doesn't make sense to do that.

Update to keep Joachim happy

```<code>public interface ITypeConverter<TSource, TDestination>
{
    TDestination Convert(TSource source);
}
</code>```

But now we are in the Automapper realm (http://automapper.codeplex.com/wikipage?title=Custom%20Type%20Converters)

Body:
public interface IMappable<S, T> {
    T MapFrom(S source);
}

// T - target
// S - source

If you want to map User to UserDTO and map User to UserViewModel, then you'll need two separate implementations. Don't pile up all this logic into a single class - it doesn't make sense to do that.

Update to keep Joachim happy

public interface ITypeConverter<TSource, TDestination>
{
    TDestination Convert(TSource source);
}

But now we are in the Automapper realm (http://automapper.codeplex.com/wikipage?title=Custom%20Type%20Converters)


问:
How to use apache license in my project which will be LGPL
I want to use LGPL for my project, can I use some source code which is apache licensed ?

If I only use the apache licensed component as library in my project, how should I make the clarification in my project ? Do I need to put some information about apache license at the beginning of source code which uses the library?

答:
As the Apache license is deemed compatible with the (L)GPL v3, you can use Apache licensed code in your LGPL project.

If you use the Apache licensed code only in the form of a library, the conventional way is

keep the Apache licensed library in a separate directory/sub-tree of the project

mention in your documentation (readme) that you use such-and-such library and under which license it is being distributed.

In your source code, you don't need to mention that a function/class comes from a separate library. The fact that it has a different license should be obvious from the copyright statements in the respective source files.


答:
In SOA your business logic is broken down into logical components where each component is exposed as a service. Hence why it's an architectural concept. It's common for these components to be distributed across multiple physical devices, but it doesn't have to be that way. You may have multiple services running on a single machine.

SOA allows for horizontal scalability, as opposed to just vertical scalability (more horse power). SOA is often applied when working with enterprise applications. Imagine a large organization with multiple unrelated applications written in various programming languages. In order for you to get these applications talking to each other (integrate), you might want to expose their functionality through services.

A range of service standards is available on the internet: http://en.wikipedia.org/wiki/List_of_web_service_specifications#Web_Service_Standards_Listings

Development frameworks such as .NET hide the complexity of these standards by offering you tools such as ASMX web services and WCF (http://keithelder.net/blog/archive/2008/10/17/WCF-vs-ASMX-WebServices.aspx)

To summarise, it would be very difficult to integrate enterprise applications if standards and frameworks that I have mentioned above didn't exist.


答:
When projects scale to a certain size, a framework is inevitable. You can explicitly choose a framework, or you can implicitly accrete it. If you do not explicitly choose to design / adopt a framework or architecture, you will still have one, it will just be a very badly designed one, and it will be much harder to add new functionality without introducing bugs (as you have already experienced). If you do not yet have the skill to design your own framework, it is better to choose a well-known framework, as it will save you time in the long run.

Specifically about your examples:

Youtube uses python for its front-end, but it spends most of its time in back-end services. In large sites you typically find this architecture where everything that takes up considerable time is moved out of the front-end servers and into a back-end service layer which can be scaled independently from the front-end. From what I can find they seem to have rolled their own framework. For more info, see http://highscalability.com/youtube-architecture

Facebook uses PHP for its front-end, and they also spend a lot of time dispatching to back-end services. Again their framework is home-grown, but they have even gone so far as to build their own PHP engine and development tools. They've open-sourced some of their framework code as well.

Architecture info: http://highscalability.com/blog/category/facebook

Facebook's PHP engine: http://www.hiphop-php.com/category/blog

Facebook's development tools: https://www.phacility.com/phabricator

Open-source: https://opensource.facebook.com

Title: Are frameworks used for "big" websites?

ContentLicense: CC BY-SA 4.0


问:
Infrastructure-related additions in commit comments
For the sake of this question, let's agree on this definition of "good commit message" from here:

Your comment should be brief and to the point, describing what was changed and possibly why.

and accept that referencing a bug/issue in a commit message is a good thing.

Now, there are a lot of tools that integrate with VCS repositories and, for them to function, require commit messages to contain various "control information" which generally does not add value in the historical sense? Think,

Amount of time spent fixing an issue ([Spent: 4h])

A /cc to notify other team members of the changeset (/cc john, jill)

A tag to the CI server to deploy the changeset to development/staging/production ([deploy: production])

Setting a reviewer (R: jill)

Granted, this is all very convenient for developers in the short term (why leave console to push a button in the CI interface when I can add a short string to commit message), but I find these messages to clutter changelog too much and way too infrastructure-specific (what if we change to a Time Tracker which uses slightly different syntax?).

What's your take on these messages and where do you draw the line on what to accept and what to forbid?

答: If the messages are compact and standardized enough for some tool to parse and act on them, then they are compact and standardized enough for another tool or plug-in to detect them when you want to read the purely technical stream of development. In other words, you should keep the messages and educate your VCS log viewer to filter them out.</p>


问:
Documenting the effect of std::move
As my team move towards embracing the new features in C++11, I'm struggling with how to make the side-effects of std::move self-documenting in the code.

The issue is that an object that has been moved should no longer be used after that point. All I can come up with is a comment:

```<code>std::string x = Func();
Other(x);   // x is zombied.
</code>```

Obviously this is error-prone and will not handle the cases where deeper code might unwittingly do a std::move.

Has anyone else dealt with this issue?

I have a feeling that diagnosing the use of zombied objects could be as much a pain as tracking down leaks or heap corruption.

答:
Don't hide the move, write it like this:</p>

```<code>std::string x = Func();
Other(std::move(x));
</code>```

Title: Documenting the effect of std::move

Body:
Don't hide the move, write it like this:

std::string x = Func();
Other(std::move(x));


问:
Should companies consider remote employees or stick to local employees?
Elite developers can be 10x more productive than an average developer.

Clearly it's easier to find an elite developer around the whole world than in a company's backyard.

If a company is not located in a programming hot spot, should they consider hiring people who work from home?

答:
There are awesome technologies today that make it easy to act as a team without being seated close to each other.

IRC, Jabber or similar chat-type software makes it really easy to keep everyone in the team aware of each other, what they're doing, and feeling free to discuss issues immediately. I use IRC with freenode's groups often and it's like having one big group of developers at hand, acting like a giant collective brain. Apple's got a nice chat client build into Mac OS that also supports video conferencing, especially effective with their laptops.

Imagine how it would be if the company had their own internal chat server, with groups for departments, projects, and work-related interest groups. A developer could ask a question where it would be seen across the company, so another developer anywhere else could see it and answer. The office walls disappear, communication skyrockets and best-practices and code sharing can happen all on their own without someone wielding a big stick.

One of our load-test engineers works remotely about 1/3 of the year, sometimes from his home which is about 30 miles from our office, other times from out of state. He is as effective in the office as he is outside it because he keeps his chat software running, and calls in for our conference calls.

My coworkers on my team sit down the hall so I can't see or hear them. I don't know when they are in their cubes so I send them a chat message, and they respond as soon as possible. I do team programming with one of our engineers at another site. The same thing occurs; We ping each other regularly with questions and/or inane thoughts, and if we need to pick up the pace we'll share a screen and get on the phone. I can't tell if he's in the office or at home, and it doesn't matter. We work the same either way.

Our QA department is split between two different cities in different states, our engineers are spread across our city at about four different locations, but it's difficult to tell because we use our phones and chat regularly. We're all working remotely from each other in reality, so what's the difference? The difference is the corporate mindset.

There are a lot of big advantages to working remotely, and mostly it takes a change in mindset for the employer to try and find out that employees respond positively to it.


问:
Is it ethical to use personal code at work?
I am working on a side project at work where I find it beneficial to use some of my code that I have developed personally (outside of work) to speed my development. My side project is developing a C++ GUI application to let our power users run queries (built by me) against databases on several different platforms (DB2, Oracle, SQL Server and MySQL). In the past, I would usually just run these myself on request or build an Excel VBA application for them. Now that I have built several VBA applications for several different people, I find the need to build one central application that just reads in custom .sql files and executes against various databases.

The application that I am building is in C++ and uses an LGPL cross-platform GUI toolkit. However, I have a lot of code that in my own libraries that I have built over the years on leisure, non-work related projects. Is it okay to use this code at work, thus saving me (and the company) time? If so, can I port any bug fixes and enhancements back to my personal library? There seems to be a line that I do not know when I am going to cross it.

I just want to add that none of the personal code has anything to do with any business logic. They are just basic utility classes/wrappers.

答:
It is not ethical to steal from your company - and, if you agreed that all of your work, while at work, belongs to them, then it's unethical to surreptitiously move code back into your codebase.

Asking for your manager's permission may not be enough - he may not be in a position to negotiate this with you. So, depending on circumstance, asking may not relieve you from your commitment - and may instead earn you an accomplice.

The correct way to do this sort of thing, is to be clear that you're bringing an outside project you own into the company, and then sign (or verbally agree) on a separate contract or arrangement, specifically for the outside project. Do this in advance.

Note that the legal and ethical aspects are different and don't completely agree. Even if ethical, it's sometimes not legal to bring your code into work without a contract (while, under other circumstances, it's not legal for you to keep the code at home - you're legally bound to bring it in and use it, if you, to the best of your ability, think it would benefit the company).

OwnerDisplayName: CodeBlew


答:
The r-value reference only binds to rvalues. In the above code, Other(std::string &&) will not be considered. So only problem might be if the function std::string & but moved it internally.

The only way to get r-value out of l-value is a std::move. So as long as you take care not to use std::move on function argument you received by l-value reference, there will be no surprises.

Moving something you received by l-value reference should be considered a bug. Unfortunately the rules of the language itself are unable to catch it, so it's a job for a static checker. I don't know whether any of them does already though.

Of course a function taking a non-const l-value reference could always screw up the passed object and the move just adds another way to do it, but the problem already existed.

I would generally recommend avoiding functions taking non-const l-value references, because functions modifying their argument are never particularly readable. A method is expected to modify it's invocant (unless it's a getter), but modifying other arguments makes the data flow more complicated and less obvious. In C++11 move makes returning objects almost as efficient as modifying reference and std::tuple with std::tie allow returning multiple values, so most uses of argument modifying can be rewritten without significant loss of efficiency.

As for proper use of std::move note that most efficient way to write setters that were previously written taking const reference and copied from it should now take by value and move from it. The argument construction in caller will do move if possible and copy otherwise.

Title: Documenting the effect of std::move

Body:
As my team move towards embracing the new features in C++11, I'm struggling with how to make the side-effects of std::move self-documenting in the code.

The issue is that an object that has been moved should no longer be used after that point. All I can come up with is a comment:

```<code>std::string x = Func();
Other(x);   // x is zombied.
</code>```

Obviously this is error-prone and will not handle the cases where deeper code might unwittingly do a std::move.

Has anyone else dealt with this issue?

I have a feeling that diagnosing the use of zombied objects could be as much a pain as tracking down leaks or heap corruption.


问:
Application qos involving priority and bandwidth
Our manager wants us to do applicaiton qos which is quite different from the well-known system qos. We have many services of three types, they have priorites, the manager wants to suspend low priority services requests when there are not enough bandwidth for high priority services. But if the high priority services requests decrease, the bandwidth for low priority services should increase and low priority service requests are allowed again.

There should be an algorithm involving priority and bandwidth. I don't know how to design the algorithm, can anyone assist in getting this right?

All these services are within a same process. We are setting the maximum bandwidth for the three types of services via ports of services via TC (TC is the linux qos tool whose name means traffic control).

答:
I don't see anything that wouldn't be already solved by the existing queueing "disciplines".

All you need to do is rate-limit the root and sort the traffic into appropriate queues by priority.

Normally you QoS traffic before it enters the narrowest link. But if you want to prioritize download, it is still possible with sacrificing a bit of total bandwidth. If you rate-limit the incoming traffic to a bit less than the total bandwidth (say 5-10%), the low priority traffic will get more discarded packets than the high priority one which will make the TCP congestion algorithm retract faster for the low priority traffic and it will after short while grind to halt if there is enough high-priority traffic.


答: Those should not be part of the commit message, they should be attached to the commit as metadata. See git notes for example, which allow you to attach arbitrary metadata to any Git object, including blobs, trees, commits, annotated tags, signed tags, and even notes (which would make this metametadata, I guess). Other version control systems have similar capabilities.</p>

Title: Infrastructure-related additions in commit comments

Body:
For the sake of this question, let's agree on this definition of "good commit message" from here:

Your comment should be brief and to the point, describing what was changed and possibly why.

and accept that referencing a bug/issue in a commit message is a good thing.

Now, there are a lot of tools that integrate with VCS repositories and, for them to function, require commit messages to contain various "control information" which generally does not add value in the historical sense? Think,

Amount of time spent fixing an issue ([Spent: 4h])

A /cc to notify other team members of the changeset (/cc john, jill)

A tag to the CI server to deploy the changeset to development/staging/production ([deploy: production])

Setting a reviewer (R: jill)

Granted, this is all very convenient for developers in the short term (why leave console to push a button in the CI interface when I can add a short string to commit message), but I find these messages to clutter changelog too much and way too infrastructure-specific (what if we change to a Time Tracker which uses slightly different syntax?).

What's your take on these messages and where do you draw the line on what to accept and what to forbid?


问:
taxonomy of software project resourcing models
I would like to understand the impact of different resourcing models for software projects.  First, I would like to identify the different resourcing approaches that are used to resource software projects. Here are some models that I can think of based in my own experiences:

Product centred resourcing

Planned resource pooling

Chaotic resource pooling

Model 1 - has resources that are product focused. In this model the project team is dedicated to a product (e.g. a SOA service). In this model, the product is the central concept and the team stays and grows with the product.  This model promotes continuous learning for the team in the product domain, and facilitates rapid development of new features because the project team is intimately knowledgeable about the product. This model seems to be very effective for evolving existing products in product centered companies.

Model 2 - pulls resources from a resource pool when starting up new projects.  This model appears to be most suitable when developing new products from scratch.  In this model team members need to acquire the domain knowledge required before starting the project.  The model does not seem to be effective for product based companies because product domain knowledge is lost when resources disband after the project completes.  This model is typical in consulting organisations.

Model 3 - is really an extension of Model 2.  In Model 3, resources are replaced with other resources mid-project.  Thus model treats resources as commodities where new project team members are expected to acquire the same knowledge as the resource that they replaced.  This model leaks the most domain knowledge, and is is characterised by low morale and low productivity. This model is usually found in organisations that are constantly fire-fighting.

Question: Is there a taxonomy of software resourcing models that I can use rather than creating my own?

答: Model 1 is the divisional organization, Model 2 the matrix organization. Model 3 would be a weak matrix based organization. Note for IT organizations functional type is not best suited when each job is different and are projects. </p>


问:
Is the Java package name convention flawed?
We're all familiar with the Java package name convention of turning the domain name around. I.e. www.evilcorp.com would, by convention, chose to have their java packages com.evilcorp.stuff.

Increasingly I'm getting fed up with this. As a commercial programmer, I encounter time and again that the software package name is completely irrelevant due to some rebrand, acquisition or similar.

In the opensource world there's less name changes so there it makes sense. However it seems to me the shelf life of many pieces of (commercial/internal) software are much longer than that of the organisation making them.

The problem is often made worse by software projects taking the marketing department's lead to use the name du jour they use refer to a certain project. A name that will, without fail, change 3 months down the line to make the emperor's new clothes feel fresh and new.

Because of this, I've mostly stopped using the reverse domain as package name. Granted, if this is done on a large scale, there's risk of name collisions, but surely this is mitigated by either using "unique" software names, avoiding generic words, or use the reverse domain for projects intended to be sold/released as libraries.

Other thoughts?

答:
You are looking at the solution to a different problem, namely how do we avoid that programmer X and programmer Y step on each others toes by putting files in the same package.

The "just reverse your domain name" solve this in an elegant way, as you then are pretty certain that if X and Y are unrelated they will not pick the same package name space.


问:
How does the Scrum Master participate in Daily Stand-Ups?
We have a professional Scrum Master consultant [*] who recently joined our project. Unfortunately, we don't know her name (she never introduced herself to us, she just came in one day and said "we are having a daily stand-up"), and she doesn't seem to do much else except chair a daily stand up meeting  - when I half-jokingly asked her to also give daily feedback in the meeting, she was quite affronted, saying it's the Scrum Master's job to "facilitate, not participate".

This seems fairly anti-Agile (having worked on other agile projects, where the teams were self directed), which is supposed to be egalitarian, but I am not sure about how it works in the Scrum Methodology. I suspect she doesn't do much all day, and that's the reason for her defensiveness on this issue.

Does the Scrum Master take part in the "yesterday, today, impediments" spiel during the stand-up meeting, or is their role to just chair ("facilitate") the meeting?

[*] We weren't actually told what her job is, we just assume, since she calls herself the Scrum Master

答:
I've been an SM for many years, I defer to the team in this. If they would like me to participate then I do that as well as facilitate.

The idea is to be one of a 'servant leader'.

The team should have the ability to "hire/fire" the SM, not have them sweep in, demand a stand up without introducing themselves.


问:
Consequences of "naïve" vs "naive"?
While using IE autocorrect "naive" got transformed to "naïve"!
My regional settings are Au English, from a Unicode search point of view the two are nothing alike. I am not even sure whether there are other characters that are being replaced, but from a programmers point of view what are the consequences and remedies in such cases? In SQL is there a way to return results containing both "naïve" and "naive"? (without hardcoding or explicit programming of course).

Are there other instances of automatic transliteration that one should be aware of? Or is there a method to handle such sameness of characters in other languages? e.g. umlats in German and lack/inclusion of vowels in Arabic script based words.

Thanks for any observations on this matter

答:
In general, if people misspell words when entering data, there can be challenges as to querying for the data. In the specific example, you can find the data if you explicitly use an 'accent insensitive' collation.

```<code>if 'naive' = 'naïve' collate Latin1_General_CI_AS
    print 'TRUE'
else
    print 'FALSE'
</code>```

Prints out FALSE

```<code>if 'naive' = 'naïve' collate Latin1_General_CI_AI
    print 'TRUE'
else
    print 'FALSE'
</code>```

Prints out TRUE

p.s. The SQL syntax is MS SQL Server syntax. I don't know if or how this applies to other relational databases

Title: Consequences of "naïve" vs "naive"?

Body:
In general, if people misspell words when entering data, there can be challenges as to querying for the data. In the specific example, you can find the data if you explicitly use an 'accent insensitive' collation.

if 'naive' = 'naïve' collate Latin1_General_CI_AS
    print 'TRUE'
else
    print 'FALSE'

Prints out FALSE

if 'naive' = 'naïve' collate Latin1_General_CI_AI
    print 'TRUE'
else
    print 'FALSE'

Prints out TRUE

p.s. The SQL syntax is MS SQL Server syntax. I don't know if or how this applies to other relational databases


问:
WCF Versioning, Naming and Endpoint URL
I have a WCF Service and a Main Lib1.

Say, I have a Save Profile Service. WCF gets data (with predefined data contract) from client and pass the same to the Main Class Lib1, generate response and send it back to client.

WCF Method : SaveProfile(ProfileDTO profile)

Current Version 1.0 ProfileDTO have the following
UserName
Password
FirstName
DOB (In string yyyy-mm-dd)
CreatedDate (In string yyyy-mm-dd)

Next Version (V2.0)
ProfileDTO have the following
UserName
Password
FirstName
DOB (In UnixTimeStamp)
CreatedDate (In UnixTimeStamp)

Version 3.0
ProfileDTO have the following (With change in UserName and Password length validation)
UserName
Password
FirstName
DOB (In UnixTimeStamp)
CreatedDate (In UnixTimeStamp)

In simple we have DataContract and Workflow change between each version
1.  How do I name the methods in WCF Service and Main Class Lib1?
2.  Do I have to go with any specific pattern for ease development and maintenance?
3.  Do I have to have different endpoints for different version?

In the above example I have a method named “SaveProfile”.
Do I have to name the methods like “SaveProfile1.0”, “SaveProfile2.0”, etc. If that is the case when there is no change between Version “3.0” and “4.0” then there will difficult in maintenance.
I’m looking for a approach that will help in ease maintenance

答:
There are two ways to have different versions of the same contact. The first is to use namespaces and the second to use different service names. Personally, I prefer the different namespace approach simply because it encapsulates the "version" with a namespace title and allows callers to be specific about their contract requirements.

However, creating new contract versions has the risk of breaking backward compatibility with existing callers.

Title: WCF Versioning, Naming and Endpoint URL


问:
Can I use the code for responsive video on this github link under a license?
This is the link: https://gist.github.com/jgarber/2302238

I am new to github and web development.So please bear with my questions.
I would like to use the responsive video code on the link mentioned above,
for a commercial website I am building.

I see that the code is posted under the 'public' section but there is a
copyright attached as well.

And, the file name is MIT-LICENSE.txt. Does this have any connection with the MIT-License?

Two questions:

a) Can I use this code by giving an attribution?

b) And, if I can, under which license can I use the code and what sort of attribution is required?

答:
What you need to do is to read over the license itself to understand more.

In order to help you though, here is a short excerpt from Wikipedia:

"The MIT License is a free software license originating at the
  Massachusetts Institute of Technology (MIT). It is a permissive free
  software license, meaning that it permits reuse within proprietary
  software provided all copies of the licensed software include a copy
  of the MIT License terms. Such proprietary software retains its
  proprietary nature even though it incorporates software under the MIT
  License. The license is also GPL-compatible, meaning that the GPL
  permits combination and redistribution with software that uses the MIT
  License."

Here is the Wikipedia link:

http://en.wikipedia.org/wiki/MIT_License

and the MIT license page link:

http://opensource.org/licenses/MIT

Based on your questions, it looks like you can use the software in your own proprietary software, but you need to provide the MIT license too (what the excerpt says).


问:
Implement Haskell typeclass with C# interface
I'm trying to compare Haskell's type classes and C#'s interfaces. Suppose there is a Functor.

Haskell:

```<code>class Functor f where
  fmap :: (a -> b) -> f a -> f b
</code>```

How to implement this type class as interface in C#?

What I have tried:

```<code>interface Functor<A, B>
{
    F<B> fmap(Func<A, B> f, F<A> x);
}
</code>```

This is invalid implementation and I'm actually stucked with generic F type that should be returned by fmap. How it should be defined and where?

Is it impossible to implement Functor in C# and why? Or maybe there is another approach?

答:
C#'s type system lacks a couple features necessary to properly implement type classes as an interface.

Let's start with your example, but the key is showing a fuller account of what a typeclass is and does, and then trying to map those to C# bits.

```<code>class Functor f where
  fmap :: (a -> b) -> f a -> f b
</code>```

This is the type class definition, or similar to the interface. Now let's look at a definition of a type and it's implementation of that type class.

```<code>data Awesome a = Awesome a a

instance Functor Awesome where
  fmap f (Awesome a1 a2) = Awesome (f a1) (f a2)
</code>```

Now we can see very obviously one distinct fact of type classes that you cannot have with interfaces. The implementation of the type class is not a part of the definition of the type. In C#, to implement an interface, you must implement it as a part of the definition of the type that implements it. This means you may not implement an interface for a type which you do not implement yourself, however in Haskell you may implement a type class for any type you have access to.

That's probably the largest immediately, but there's another fairly significant difference that makes the C# equivalent really not work nearly as well, and you are touching on it in your question. It's about Polymorphism. Also there's some relatively generic things Haskell allows you to do with type classes which outright do not translate especially when you start looking at the amount of genericism in existential types or other GHC extensions like Generic ADTs.

You see, with Haskell you can define the functors

```<code>data List a = List a (List a) | Terminal
data Tree a = Tree val (Tree a) (Tree a) | Terminal

instance Functor List where
  fmap :: (a -> b) -> List a -> List b
  fmap f (List a Terminal) = List (f a) Terminal
  fmap f (List a rest) = List (f a) (fmap f rest)

instance Functor Tree where
  fmap :: (a -> b) -> Tree a -> Tree b
  fmap f (Tree val Terminal Terminal) = Tree (f val) Terminal Terminal
  fmap f (Tree val Terminal right) = Tree (f val) Terminal (fmap f right)
  fmap f (Tree val left Terminal) = Tree (f val) (fmap f left) Terminal
  fmap f (Tree val left right) = Tree (f val) (fmap f left) (fmap f right)
</code>```

Then in consumption you can have a function:

```<code>mapsSomething :: Functor f, Show a => f a -> f String
mapsSomething rar = fmap show rar
</code>```

Herein lies the problem. In C# how do you write this function?

```<code>public Tree<a> : Functor<a>
{
    public a Val { get; set; }
    public Tree<a> Left { get; set; }
    public Tree<a> Right { get; set; }

    public Functor<b> fmap<b>(Func<a,b> f)
    {
        return new Tree<b>
        {
            Val = f(val),
            Left = Left.fmap(f);
            Right = Right.fmap(f);
        };
    }
}
</code>```

```<code>public string Show<a>(Showwable<a> ror)
{
    return ror.Show();
}

public Functor<String> mapsSomething<a,b>(Functor<a> rar) where a : Showwable<b>
{
    return rar.fmap(Show<b>);
}
</code>```

So there's a couple things wrong with the C# version, for one thing I'm not even certain it will allow you to use the  qualifier like I did there, but without it I am certain it wouldn't dispatch Show<> appropriately (feel free to try and compile to find out; I didn't).

The bigger problem here however is that unlike above in Haskell where we had our Terminals defined as part of the type and then usable in place of the type, due to C# lacking appropriate parametric polymorphism (which becomes super obvious as soon as you try to interop F# with C#) you can't clearly or cleanly distinguish whether Right or Left are Terminals. Best you can do is use null, but what if you're trying to make a value type a Functor or in the case of Either where you're distinguishing two types that both carry a value? Now you have to use one type and have two different values to check and switch between to model your discrimination?

The lack of proper sum types, union types, ADTs, whatever you want to call them really makes a lot of what typeclasses give you fall away because at the end of the day they let you treat multiple types (constructors) as a single type, and .NET's underlying type system simply has no such concept.

Body:
C#'s type system lacks a couple features necessary to properly implement type classes as an interface.

Let's start with your example, but the key is showing a fuller account of what a typeclass is and does, and then trying to map those to C# bits.

class Functor f where
  fmap :: (a -> b) -> f a -> f b

This is the type class definition, or similar to the interface. Now let's look at a definition of a type and it's implementation of that type class.

data Awesome a = Awesome a a

instance Functor Awesome where
  fmap f (Awesome a1 a2) = Awesome (f a1) (f a2)

Now we can see very obviously one distinct fact of type classes that you cannot have with interfaces. The implementation of the type class is not a part of the definition of the type. In C#, to implement an interface, you must implement it as a part of the definition of the type that implements it. This means you may not implement an interface for a type which you do not implement yourself, however in Haskell you may implement a type class for any type you have access to.

That's probably the largest immediately, but there's another fairly significant difference that makes the C# equivalent really not work nearly as well, and you are touching on it in your question. It's about Polymorphism. Also there's some relatively generic things Haskell allows you to do with type classes which outright do not translate especially when you start looking at the amount of genericism in existential types or other GHC extensions like Generic ADTs.

You see, with Haskell you can define the functors

data List a = List a (List a) | Terminal
data Tree a = Tree val (Tree a) (Tree a) | Terminal

instance Functor List where
  fmap :: (a -> b) -> List a -> List b
  fmap f (List a Terminal) = List (f a) Terminal
  fmap f (List a rest) = List (f a) (fmap f rest)

instance Functor Tree where
  fmap :: (a -> b) -> Tree a -> Tree b
  fmap f (Tree val Terminal Terminal) = Tree (f val) Terminal Terminal
  fmap f (Tree val Terminal right) = Tree (f val) Terminal (fmap f right)
  fmap f (Tree val left Terminal) = Tree (f val) (fmap f left) Terminal
  fmap f (Tree val left right) = Tree (f val) (fmap f left) (fmap f right)

Then in consumption you can have a function:

mapsSomething :: Functor f, Show a => f a -> f String
mapsSomething rar = fmap show rar

Herein lies the problem. In C# how do you write this function?

public Tree<a> : Functor<a>
{
    public a Val { get; set; }
    public Tree<a> Left { get; set; }
    public Tree<a> Right { get; set; }

    public Functor<b> fmap<b>(Func<a,b> f)
    {
        return new Tree<b>
        {
            Val = f(val),
            Left = Left.fmap(f);
            Right = Right.fmap(f);
        };
    }
}

public string Show<a>(Showwable<a> ror)
{
    return ror.Show();
}

public Functor<String> mapsSomething<a,b>(Functor<a> rar) where a : Showwable<b>
{
    return rar.fmap(Show<b>);
}

So there's a couple things wrong with the C# version, for one thing I'm not even certain it will allow you to use the <b> qualifier like I did there, but without it I am certain it wouldn't dispatch Show<> appropriately (feel free to try and compile to find out; I didn't).

The bigger problem here however is that unlike above in Haskell where we had our Terminals defined as part of the type and then usable in place of the type, due to C# lacking appropriate parametric polymorphism (which becomes super obvious as soon as you try to interop F# with C#) you can't clearly or cleanly distinguish whether Right or Left are Terminals. Best you can do is use null, but what if you're trying to make a value type a Functor or in the case of Either where you're distinguishing two types that both carry a value? Now you have to use one type and have two different values to check and switch between to model your discrimination?

The lack of proper sum types, union types, ADTs, whatever you want to call them really makes a lot of what typeclasses give you fall away because at the end of the day they let you treat multiple types (constructors) as a single type, and .NET's underlying type system simply has no such concept.


问:
Unit Testing Wrapper (Facade?) Method
I have to write unit tests for some classes my group is developing.  The classes are fairly simple, and I'm not sure how to best test them.

```<code>public class MyObjectRegistry
{
    private myDataSetMapper = new MyDataSetMapper();

    public boolean StoreObjects(list<MyObject> myObjectList)
    {
        myDataSetMapper.StoreObjects(myObjectList);
    }
}

public class  MyDataSetMapper
{
    public boolean StoreObjects(list<MyObject> myObjectList)
    {
        for(MyObject myObj: myObjectList)
        {
            boolean result = StoreObject(myObj);
        }
    }

    private boolean StoreObject(MyObject myObject)
    {
        //Store the object in a database
    }
}
</code>```

So my question is how to test the MyObjectRegistry.StoreObjects and MyDataSetWrapper.StoreObjects methods since there's no real logic other than a foreach loop and calling out to another method.

I've looked around the web and found that I think I'm looking at a "facade" class/method, but I'm still unclear on what would I should test/assert in the test method.

答:
The problem you are facing is the result of "bad" class design.  Specifically MyObjectRegistry was not designed to facilitate unit testing.  Luckily, reflection allows you to set private values of classes.

Here is what I would do in your situation:

Create a mock version of MyObjectRegistry; probably using a List, a Map, or, perhaps, a Map of List ojects.

At the start of your junit test (perhaps in class setup) create a MyObjectRegistry instance then set the myDataSetMapper member to the mock version of the MyDataSetMapper class.

Call the storeObjects method then check to see that the values which were passed to the storeObjects method were added to the mocked MyObjectRegistry object.

Assuming that the database access code in not inside the MyDataSetMapper.storeObject() method, do the same thing for MyDataSetMapper with a mocked data access object.

Title: Unit Testing Wrapper (Facade?) Method


问:
Architecting Python application consisting of many small scripts
I am building an application which, at the moment, consists of many small Python scripts.

Each Python script processes items from one Amazon SQS queue. Emails come into an initial queue and are processed by a script, and typically the script will do a small unit of processing (for example, parse email and store some database fields), then an item will be placed on the next queue for further processing, until eventually the email has finished going through the various scripts and queues.

What I like about this approach is that it is very loosely coupled.

However, I'm not sure how I should implement live.  Should I make each script a daemon which is constantly polling its inbound queue for things to do? Or should there be some overarching orchestration program or process? Or maybe I should not have lots of small Python scripts but one large application?

Specific questions:
How should I run each of these scripts - as a daemon with some sort or restart monitor to restart them in case they stop for any reason? If yes, should I have some program which orchestrates this?

Or is the idea of many small script not a good one, would it make more sense to have a larger python program which contains all the functionality and does all the queue polling and execution of functionality for each queue?
What is the current preferred approach to daemonising Python scripts?

Broadly I would welcome any comments or opinions on any aspect of this.

thanks

答:
I'd propose turning scripts into standalone, atomic services (yeah, I know, services SHOULD be atomic, whatever). Then, you can find some ESB and glue it all together. Most popular (I think, "citation needed") ESB for python is zato.io, but I haven't tried it. Instead, I've seen MuleESB (Java solution), and it works like charm.

"Java solution for python scripts?" you'd ask. Yeah, that will work. Services are language-agnostic, they are little black boxes, that do only one thing - like you wanted. You glue them together with ESB and some queue system (ZeroMQ? ActiveMQ? your choice), and there is no difference, if you're gonna write services in python2, python3, Java, C(++), Smalltalk or even damn Brainfuck.


问:
Who should provide the Requirement doc / SRS?
I am creating a Mobile application (CRM) for another software company. They told me they need these these stuff from here and there, within 15-30 minutes. But they never provided a detailed client requirement document in writing. I have been asking this for number of times, but still no. As soon as I started working I realized what they told by mouth is not even 10% of the work. They first asked me to come up with my own design which is similar to another app they mentioned. I did, 100% similar design to the app they mentioned. Then they said they don't like it so they gave me their design. I completed there design and submitted it. Now they again say they don't like their own design and asking me to do another design! Apart from that, they are asking for some "Activity Sliding Animations", "Windows Like UI" etc now. In order to do this, I need to remove the entire work I did and start from the scrach, because it can be done by Fragments and mine contains Activities. I even have no idea how the backend will be. Even after one month, we are still designing and changing the designing (Because you have to send at least 3-4 mails, contact at least 2 of their team via phone to get an answer. Very slow communication).

And will they pay for the trashed designs? I don't think so. So what about the other customers of mine which I said 'no' due to the lack of time I am going to have because of this project? I feel almost crazy.

They always say come up with your own idea, but that is very risky in this situation. If my idea is not accepted, waste of time and money.

I am so tired of this, I wasted lot of time designing two 100% different designing, and about to proceed to 3. Since I don't know how the software will be, I haven't done a cost estimation as well. So my question is, client is not supposed to give you any documented requirement? May be an SRS? (What I meant by SRS is, complete detailed document about functionality they need. Including these 'animation' stuff, because I have no super power to guess) The requirement doc they provided is useless, it only says "update", "delete", "edit". All my other clients did provide complete data, some even provided drafts of the design process, except this one. They should at lease ptovide me their requirements in details, in writing,  I need some advice here.

答:
This is essentially a contract  dispute, and should be covered in the contract.

Would a builder start building a house without knowing how many bedrooms and what the budget was? What would a builder do - he would help the customer by drawing up some plans, agree to the plans, then start building. Would he charge for those plans - that depends, but he would tell the customer.

Every professional software developer knows not to start a project that does not have requirements (Even Agile - the anti-Requirements evangelists, has User stories and backlogs).

Given where you are today, you have several options, not all palatable, an most will depend on your contract. If there contract is as loose as there requirements, (quite common), you have a leg to stand on insisting on payment. One option always is walk away- always be prepared to do this, or you will dig a deeper hole. Learn the meaning of "Sunk costs" if you do not know it.

You could invoice the client for you time, depending on the contract he may or may not pay. If they refuse to pay, what are you prepared to do about it?

My preference in your situation would be meet with your client, with accurate records of what you have spent, and discuss with them a way forward, basted on "fair and reasonable". The contract will define where you stand, however I have had clients pay more than contracted on a project that blew out, they wanted to maintain an ongoing business relationship. If the relationship is not fair and reasonable on both sides, walk away.