问:
When is type coercion a good idea?
When do you want (on purpose) to coerce type in JavaScript? I mean, beyond comparing strings and numbers, when does it benefit something you're building?

Examples of type coercion:

```<code>"The answer is " + 42
//=> "The answer is 42"

"37" - 7
//=> 30

"37" + 7
//=> "377"

var foo = [0];
console.log(foo == foo);
//=> true

console.log(foo == !foo);
//=> true
</code>```

答:
The fundamental principle that most affects type coercion is be liberal in what you accept.  For a language with argument types are part of a function signature, you could handle, say, a log function by requiring string parameters and having overloads for object and integer and whatnot.

In JavaScript, which is so loosely typed that you should treat function arguments as simply a naming suggestion for the first X arguments passed, type coercion can be used to help quickly handle most argument types.  And, of course, it's a fundamental aspect of feature inspection.  Consider the following, which will take any number of arguments and pass them to console.log as a single space-seperated string:

```<code>function toLog() {
    if(arguments.length && window.console && window.console.log) {
        var ArgString = "";
        for(var a = 0; a < arguments.length; a++) {
            ArgString += arguments[a];
        }
        console.log(ArgString);
    }
}
</code>```

The above uses type coercion in three ways that are extremely useful for JavaScript:

The arguments.length property is coerced from a number to a boolean value to see if there are elements in the arguments pseudo-array.

Both the global console object and its log method are coerced from objects to boolean if they are not null, which prevents an (old?) IE bug where console.log would cause errors if called without the developer console open.

By setting ArgString to an empty string "" on initialization, we signal to the interpreter to coerce all arguments to strings as well.  Which isn't all that useful on a modern browser, but works for the sake of our example.

Title: When is type coercion a good idea?

Body:
The fundamental principle that most affects type coercion is be liberal in what you accept.  For a language with argument types are part of a function signature, you could handle, say, a log function by requiring string parameters and having overloads for object and integer and whatnot.

In JavaScript, which is so loosely typed that you should treat function arguments as simply a naming suggestion for the first X arguments passed, type coercion can be used to help quickly handle most argument types.  And, of course, it's a fundamental aspect of feature inspection.  Consider the following, which will take any number of arguments and pass them to console.log as a single space-seperated string:

function toLog() {
    if(arguments.length && window.console && window.console.log) {
        var ArgString = "";
        for(var a = 0; a < arguments.length; a++) {
            ArgString += arguments[a];
        }
        console.log(ArgString);
    }
}

The above uses type coercion in three ways that are extremely useful for JavaScript:

The arguments.length property is coerced from a number to a boolean value to see if there are elements in the arguments pseudo-array.

Both the global console object and its log method are coerced from objects to boolean if they are not null, which prevents an (old?) IE bug where console.log would cause errors if called without the developer console open.

By setting ArgString to an empty string "" on initialization, we signal to the interpreter to coerce all arguments to strings as well.  Which isn't all that useful on a modern browser, but works for the sake of our example.


问:
return Trivial booleans?
I am writing a simple piece of code. Its a function that allowed the user to withdraw some money. There are some restrictions to this though.

The user can't withdraw more than the given withdraw limit.

The user cannot withdraw more money they that have.

The script will terminate if this happens, and let the users know. Otherwise they user can withdraw the money and the balance updates, they also get a confirmation message.

Now my question is should I return False if they hit either case 1 or 2? And should I return True if the transactions completes successfully?

I do not have any current plans where I will need the booleans from the function call. But I wonder is it good coding practice to return something in a case like where the function could take different paths.

Some example code (Python):

```<code>limit = 500
balance = 5000

def withdraw_money(amount):
    if amount > limit:  # above the limt
        print('You cannot withdraw more than ${}'.format(balance))
        return False
    elif amount > balance:  # not enough money
        print('Insuffecient funds')
        return False
    else:  # actually worked
        balance -= amount
        print('Your new balance is ${}'.format(balance))
        return True
</code>```

答:
There is no standard convention as far as returning booleans from functions. If the function returns true or false, it is up to you, the author of that function, to determine what the meaning of each value is and how the caller should react to each one.

However, one thing I would strongly recommend is that your function should ONLY return a boolean if you expect the caller to look at the result and act accordingly as part of normal workflow (in other words, False is no more a failure than True is).

On the other hand if your intention is to return a boolean as a way of indicating whether or not the function call succeeded, there's a convention for that.  Do not return anything in that case.  Instead, if the caller calls your function and your function returns, that would be considered a success.  If anything within your function fails, just raise an exception.

The benefits of doing it this way is that you don't have to write code that looks like this:

```<code>if not withdraw_money():
    .... handle error ....
    return

if not do_something():
    ... handle error ...
    return

if not do_something_else():
    ... handle error
    return
</code>```

Instead, you'd be able to write:

```<code>try:
    withdraw_money()
    do_something()
    do_something_else()
except:
    ... handle all errors in one place ...
</code>```

So now your actual logic isn't intermingled with error handling. And if you use exception handling throughout your application, a lot of times you'll be able to define try-except block at a higher level and all function calls from that point down can just focus on implementation of the actual feature, not checking for success/failure at every single step.

The other benefit is that your failure conditions are much more expressive.  If the caller gets back "False" he knows something failed, but it could be just about anything.  If a caller gets back InsufficientFundsError() as the exception type, he knows much more about what error condition caused the problem.

Update:
As Robert Harvey pointed out, the use of exceptions is somewhat of a controversial in the developer community and in different programming languages the use of exceptions will vary. I am gearing this answer towards python because that's is what OP is learning.

Even in python, you will get arguments that exceptions should only be for truly exceptional situations but then you get a very subjective territory as to what is considered truly exceptional.  Clearly if a RAM chip flips a bit due to hardware error, that's an exceptional condition. What about missing config file?

So a lot of this will come down to your personal programming style and this answer definitely reflects mine, so read it with a grain of salt. Just like Robert's example with python dictionary "that is required to return a valid object (as in a dictionary lookup)" I tend to write most of my code such that if a function returns a value, I require it to return a value.  I don't have to, but that's my choice in how I define the signature of that function and how I intend for it to be used.

If you are new to programming, I'd definitely recommend for you to try different things and alter how you structure code just so you can see for yourself which constructs/conventions work better and make the most sense for you.

ContentLicense: CC BY-SA 3.0

Title: return Trivial booleans?

Body:
There is no standard convention as far as returning booleans from functions. If the function returns true or false, it is up to you, the author of that function, to determine what the meaning of each value is and how the caller should react to each one.

However, one thing I would strongly recommend is that your function should ONLY return a boolean if you expect the caller to look at the result and act accordingly as part of normal workflow (in other words, False is no more a failure than True is).

On the other hand if your intention is to return a boolean as a way of indicating whether or not the function call succeeded, there's a convention for that.  Do not return anything in that case.  Instead, if the caller calls your function and your function returns, that would be considered a success.  If anything within your function fails, just raise an exception.

The benefits of doing it this way is that you don't have to write code that looks like this:

if not withdraw_money():
    .... handle error ....
    return

if not do_something():
    ... handle error ...
    return

if not do_something_else():
    ... handle error
    return

Instead, you'd be able to write:

try:
    withdraw_money()
    do_something()
    do_something_else()
except:
    ... handle all errors in one place ...

So now your actual logic isn't intermingled with error handling. And if you use exception handling throughout your application, a lot of times you'll be able to define try-except block at a higher level and all function calls from that point down can just focus on implementation of the actual feature, not checking for success/failure at every single step.

The other benefit is that your failure conditions are much more expressive.  If the caller gets back "False" he knows something failed, but it could be just about anything.  If a caller gets back InsufficientFundsError() as the exception type, he knows much more about what error condition caused the problem.

Update:
As Robert Harvey pointed out, the use of exceptions is somewhat of a controversial in the developer community and in different programming languages the use of exceptions will vary. I am gearing this answer towards python because that's is what OP is learning.

Even in python, you will get arguments that exceptions should only be for truly exceptional situations but then you get a very subjective territory as to what is considered truly exceptional.  Clearly if a RAM chip flips a bit due to hardware error, that's an exceptional condition. What about missing config file?

So a lot of this will come down to your personal programming style and this answer definitely reflects mine, so read it with a grain of salt. Just like Robert's example with python dictionary "that is required to return a valid object (as in a dictionary lookup)" I tend to write most of my code such that if a function returns a value, I require it to return a value.  I don't have to, but that's my choice in how I define the signature of that function and how I intend for it to be used.

If you are new to programming, I'd definitely recommend for you to try different things and alter how you structure code just so you can see for yourself which constructs/conventions work better and make the most sense for you.


问:
Significance of many-to-many relationships?
How important are to-many relationships in iOS programming? Do you often hold a list of pointers to objects in an array in your codes?

I don't think I fully understand the concept of to-many relationships, let alone how to implement them into code. From my current understanding, to-many relationships holds a list of pointers to one or more class objects and their corresponding properties and instance variables?

答:
They are important when you have to simulate a real-world many-to-many relationship.

Examples of many-to-many relationships:

Order details

Product/Vendor relationships

Hotel Room bookings

School Class Registration


问:
Designing a fitness / weight lifiting routine database
I'd like to create an app similar to Barbell Pro for Android, for practice / interest / educational purposes really.  Or even as another example for database purposes, Fitocracy

The problem is, I have no idea how the database could be designed... For example:

We have a 1000 Persons using the app

Each Person could have 1-7 individualised WorkoutRoutines, depending on the day.  (Perhaps even more -> AM workouts / PM workouts)

Each WorkoutRoutine has an individual set of Exercises, with some crossover e.g. someone could do Bench Press on Monday and on Friday afterall.

Each Exercise has a number of Sets

Each Set has a number of Reps

Now to me, this seems like it could potentially be a large amount of information to store for Each Person, and maybe pretty complicated to do so.

I only have some experience with relational databases and I don't know how I'd go about designing that in an efficient matter for a relational database.

I'm not asking for a design, just how I'd begin to go about it.  The potential complexity is daunting for me due to lack of database experience.

Maybe it's not even that complicated, but like I say, ignorance from myself.

答: Here is a prototype database schema.  It allows the creation of different exercise routines, assigns those routines to a person by date, and even has a place to log the exercises executed, and the number of reps.


答:
Don't start designing from the database.  You'll just lock yourself into a schema that's all wrong, once you figure out who uses it and how.  Just start with requirements, write tests that prove them, write code that passes the tests, and let the schema fall out the bottom.

You might decide, after a few iterations of development, that JSON/MongoDB is better for your requirements.  Or you might find an excellent schema already written for you.  Or you might decide that HTML5 local storage is all you need.

For a greenfields (new) application, the schema is an implementation detail.  Don't fret about it.

Title: Designing a fitness / weight lifiting routine database

Body:
I'd like to create an app similar to Barbell Pro for Android, for practice / interest / educational purposes really.  Or even as another example for database purposes, Fitocracy

The problem is, I have no idea how the database could be designed... For example:

We have a 1000 Persons using the app

Each Person could have 1-7 individualised WorkoutRoutines, depending on the day.  (Perhaps even more -> AM workouts / PM workouts)

Each WorkoutRoutine has an individual set of Exercises, with some crossover e.g. someone could do Bench Press on Monday and on Friday afterall.

Each Exercise has a number of Sets

Each Set has a number of Reps

Now to me, this seems like it could potentially be a large amount of information to store for Each Person, and maybe pretty complicated to do so.

I only have some experience with relational databases and I don't know how I'd go about designing that in an efficient matter for a relational database.

I'm not asking for a design, just how I'd begin to go about it.  The potential complexity is daunting for me due to lack of database experience.

Maybe it's not even that complicated, but like I say, ignorance from myself.


问:
How does database connection pooling improve application performance?
I can't understand why connection pooling improves application performance.

I suppose connection establishment would cause latency. But reusing an established connection requires more complex error handling. Application server need track state of every connection to set connection to initial state before reusing (such as discarding all transactions, switching to the default isolation level), which also costs time.

答:
The complex error handling is usually provided by libraries, and if your application is well-behaved, it shouldn't be needed too much anyway.  The complex error handling required during attempting to create a new connection is far more likely to be invoked.

Reseting the state of the connection is trivial and inexpensive; it's built into all modern connection managers that I'm aware of.

Nothing can reduce the overheads of creating a new connection to a database.


答:
Mainly because the application server has a pool of database connections open and ready for use.

If you program had to connect and login to the database every time it would slow it down considerably.

There are other advantages such as handling all the variations in connecting to different DBMSes from different vendors, and, handling the connection configuration in a consistent and manageable way. Just imagine if you had 100 services which made thier own connection to a MySql db and your manager told you to connect to Postgress instead. With a J2EE application server this would entail changing a few entries in a single configuration file, without connection pooling you would need to make changes in 100 application programs.

Title: How does database connection pooling improve application performance?

Body:
I can't understand why connection pooling improves application performance.

I suppose connection establishment would cause latency. But reusing an established connection requires more complex error handling. Application server need track state of every connection to set connection to initial state before reusing (such as discarding all transactions, switching to the default isolation level), which also costs time.


问:
Examples of Java APIs that demand an action sequence
As part of a research I'm working on, I'm looking for public APIs that only work correctly when you apply a certain sequence of actions on them.

For example, the java.nio.channels.SocketChannel class, from the Java standard library, only works correctly with sequences such as open() -> connect() -> read() -> read() -> close(). A more complete demonstration if how it may be used may be represented in the following graph:

Additional examples of Java standard library APIs that require certain sequences are java.io.PrintStream (very similar to the one above) and java.util.Iterator (which requires a next() call between every two remove() calls, thus enforcing a certain sequence).

So, does you favorite API for doing X also behave that way? I would very much like to know about additional APIs that require a certain method sequence for correct usage; especially classes that are not part of the Java standard library. The more complex the sequence(s) required, the better.

Some APIs require a sequence that spans across multiple classes, for example:

```<code>X x = new X();
x.setup();
Y y = x.createNewY();
Z z = new Z(y);
z.doSomething();
</code>```

These examples are also interesting, but I'm mostly looking for sequences that all appear in the same class.

EDIT added bounty for greater visibility. I'm sure many of you have encountered many APIs that will match this description - I would really appreciate some good examples.

答:
Like parsing an XML document?</p>

```<code>DocumentBuilderFactory dbf = DocumentBuilderFactory.getInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("file.xml"));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Like parsing an XML document?

DocumentBuilderFactory dbf = DocumentBuilderFactory.getInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("file.xml"));


问:
New Team Lead - How to deal with a resentful former peer
I've been told that I am to be a team lead of an upcoming project. I've not ever been team lead before but the responsibilities are what you would typically expect, with revolving door of 3 to 4 other developers through the 8 or 9 months it takes to complete the project.

My problem is this: one of the developers who will no doubt be working on this project will be a problem. He has more experience than me, has called me an idiot several times in the past, and has told me that he has taken this job because he is a natural leader. He has expected to be promoted to a leadership position with every new project (which has not happened to date), and even once told me that I was to report to him, even though the actual team lead was under no such illusion. Moreover, I've both observed and heard from others that he is extremely unprofessional (watches non-work videos at client sites - with no head phones, dresses unprofessionally, comes to work late, makes inappropriate jokes, etc.) He took or attempted to take credit for my work or insights multiple times while I worked with him as a peer. My current team lead told me that she threw out 1/2 of this guy's code once he left her project because the quality was no good. I could go on.

My fear is that this guy will actively work against me, because he will resent having to report to someone that he considers an inferior, especially since I have been given this opportunity before him. I've successfully dealt with this type of personality as a peer or even reporting to managers like this in the past. I've not dealt with, or ever thought about, having to deal with this type of character who is reporting to me.

My question is: what kind of strategies can I use to effectively and professionally deal with this? Especially now, before it has become a problem, is there any way to cut it off before it gets out of hand etc. If anyone has a similar experience how did they deal with it?

答:
I have also seen this type of job. Some people have extra talent and obviously have risen to a high position, but you have to remember that he is older than you.

So respect him. But never forget you are the team leader and you have to manage your team. You have to maintain a proper understanding between team .//// and go on.


问:
Handling array passed to object at creation
When creating my object I pass it an array of a row from my database.
(everything in the array we will need, disregarding unnecessary elements at sql query level)

When I need to access certain array elements from within my class, I do so like

```<code>$this->row['element']
</code>```

However, As I continue development, I sometimes forget what exactly is in this passed array.(this itself doesn't seem good)

I am wondering if their is a professional approach to dealing with this, Or am I the only one who has these "I wonder whats in the array" thoughts.

One approach to tackling this could be that when we originally pass the array, in the constructor, we assign each element of the array to its own variable, but is this considered professional practice?

Additionally by doing this, we could make those variables constants, in a attempt at immutability.

Overall I am trying to adhere to good software craftsmanship.

Regards.

答:
The best way is to thoroughly describe the structure of your arrays within comments in your code, but I use var_dump() at times that I forget. It will dump a detailed list of each element within an array or object (name, type, key, value, etc) including deeply nested arrays. I've been using PHP for more than 10 years so this sort of thing is second nature to me (PHP didn't really have debuggers or high-end IDE's back than, so you were stuck digging through vars manually)

And yes, it's OK to manually name elements within array properties when constructing a class object. This is actually common practice in configuration files. For example, a config class can have the property $database, and then set $this->database['user'], $this->database['pass'], etc within the constructor.


问:
How do I traverse a tree without using recursion?
I have a very large in memory node tree and need to traverse the tree. Passing the returned values of each child node to their parent node. This has to be done until all the nodes have their data bubble up to the root node.

Traversal works like this.

```<code>private Data Execute(Node pNode)
{
    Data[] values = new Data[pNode.Children.Count];
    for(int i=0; i < pNode.Children.Count; i++)
    {
        values[i] = Execute(pNode.Children[i]);  // recursive
    }
    return pNode.Process(values);
}

public void Start(Node pRoot)
{
    Data result = Execute(pRoot);
}
</code>```

This works fine, but I'm worried that the call stack limits the size of the node tree.

How can the code be rewritten so that no recursive calls to Execute are made?

答:
If you have an estimate for the depth of your tree beforehand, maybe it is sufficient for your case to adapt the stack size? In C# since version 2.0 this is possible whenever you start a new thread, see here:

http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/22/increasing-the-size-of-your-stack-net-memory-management-part-3.aspx

That way you can keep your recursive code, without having to implement something more complex. Of course, creating a non-recursive solution with your own stack may be more time and memory efficient, but I am pretty sure the code will not be as simple as it is for now.


答:
Don't design your database first.  If it seems daunting to try and figure out all of the variables and tables you'll need based on the initial schema, that's a sign that you may be approaching the problem from the wrong directly.

Instead, design your database when you have something to store, especially something that you'll want to summarize or query for latter.  You may find out that just writing some JSON or XML to disk as text files will be all that you need.  Or, you might want store a blob of XML or JSON for each routine, and allow the routines to be queried, joined, and summarized.  Or, you may find that XML and JSON are more trouble that they're worth, and you really do just need a few relational tables.

If you've already got the client application down, and want to work on a database server that will store all of the information for a fitness center's clients, proceed as follows:

Identify what needs to be actually storied and queried.  As I alluded before, if you're not going to query on the raw data, a JSON or XML serialization of your data objects in Java may be the best bet.  (Remember that, if the file is too big to fit into a CHAR, you can always store the text in a "memo" or "blob" field, depending on your database.)

Look for repeated information, where more than a single field can be linked together into some inferred item -- that is, move two or more field to a separate table that would have a many-to-one relationship with where they came from.  What you have listed in the question is a fair start to begin with, although you may find more or discover that you made your schema too complex.

For each table, determine a correct unique key that will be immutable and unique for all records.  Don't be afraid to create virtual keys via identities or similar mechanisms.  And don't obsess over performance just yet; if a natural key seems better than a virtual key, go ahead and use it.

Give every field and table a clear and distinct name.  The names of keys should be unique throughout your database, although secondary fields do not have to be.  (Although, of course, there's no harm in having them so.)

With all of the above in hand, do an initial database design.  You want to get some tables you can send some sample data to, and populate it with some good test data.

Once the database is done, code the data access layer of your application, which will read out data in your app's native form and send said native form to some way that the database can accept.

After you've got some code working and can both write appropriate data and get back the records you were expecting, load up your development database with sample data.  This can be entirely fictitious, or information from your beta testers, or a combination of both.  Feel free to throw a few expected year's worth of data in there.  Or more.

With a database whose tables have some meaty data on them, optimize your database.  You may need to add or adjust keys, refactor some tables into normalized views, or tweak the data types of some fields.  Numbers and testability are your friend, and should be your guide.

Don't be afraid if you find yourself going back a step, or doing them out of order.  Do keep your database as provider-agnostic as you can, so if needs be you can switch from SQLite to MonoDB to MSSQL as the design demands.

Bonus Rant

Whatever you do, and I cannot stress this enough if you're not familiar with relational databases, KEEP YOUR TABLES NARROW.  Don't go adding fields like set1Reps and set2Reps to the same table; that's a headache of a code-smell, and a huge sign that you should either have an internal XML or JSON field to store the asymmetric data or clear and distinct sub-tables.

If for some reason you find yourself wanting a very wide recordset so you can just loop through its fields and assign them to a single data object, you can always do so via a View and some clever SQL.  But in that case, you'd be far better off with seralizing and unserializing a lot of your data object, anyway.


问:
Using a variable in a Global context in webapps
In a webapp, I have a scenario where I need some kind of global context (Static like) for few variables, for the current thread only.

If there are 3 different concurrent users, then I expect three corresponding global context variable for the 3 separate threads/sessions.

Using a Static variable makes its scope global for all the threads.

Is there a way in which I can achieve this?

答: A ThreadLocal is what you want. However, in your situation, I think that you should go for Session scoped variables.


问:
Detect Order Changes in a List
Let's say you have a list of values that are:

a

b

c

d

e

The order on the list might be changed.

a

c

d

b

e

How would you detect this change? We needed something like this when we were building a revision history page for our online form building tool. We found a quick and dirty solution, but I am looking for a more elegant solution for this. Here is what the revision descriptions look like:

Here is the tough part: Elements can be removed/added from/to anywhere on the list. So, the algorithm should be able to ignore those changes.

答:
There are two approaches:

Try to find a way to apply the diff algorithm to your model. This gets easier when there is a underlying textual representation (e.g. HTML source or another DSL).

Don't have your form builder emit complete states, only have it emit differences which you can easily log. Instead of having the before and after lists, you'd log the “move field from x to y” operation.

ContentLicense: CC BY-SA 4.0

Title: Detect Order Changes in a List


问:
Are there established algorithms for spacing out objects of unequal size?
I'm working on visualizing a hierarchy.  There will be clusters of objects, each cluster containing rectangles of fixed width but variable height.  I'd like to arrange these within a rectangular space so as to have equal visual spacing between them, something like this:

Before I spend a day inventing the wheel, are there standard algorithms for this kind of distribution and space-filling?  If the objects were all the same size, I'd just use a grid.

I'll be using this algorithm at two levels: once to lay out the clusters, and again to lay out the objects within each cluster.  The latter would look best if they were arranged within a roughly circular space, but if that complicates things excessively I'm OK with rectangular.

I won't be showing relationships between these objects, so distance minimization is not necessary.

There's a similar question (https://ux.stackexchange.com/questions/29220/what-would-be-the-best-way-to-fill-space-in-an-user-interface-for-irregular-im) about laying out rectangular images while eliminating or minimizing white space.  In my case, I want to equalize white space, clusters will be circular, and some clusters will be much larger than others.

答: This is called in mathematics the bin packing problem. There is some example code of the application of the first fit algorithm. Tackling the distribution of white space as required in the second half of your post might be implemented by introducing the concept of elastic "glue" as it is used in the famous typesetting program TeX written by Donald E. Knuth.</p>


问:
How do you unit test private methods?
I am working on a java project. I am new to  unit testing. What is the best way to unit test private methods in java classes?</p>

答:
If you cannot use external APIs or dont want to, you can still use pure standard JDK API to access private methods using reflection. Here is an example

```<code>MyObject obj = new MyObject();
Method privateMethod = MyObject.class.getDeclaredMethod("getFoo", null);
privateMethod.setAccessible(true);
String returnValue = (String) privateMethod.invoke(obj, null);
System.out.println("returnValue = " + returnValue);
</code>```

Check Java Tutorial http://docs.oracle.com/javase/tutorial/reflect/ or Java API http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html for more information.

As @kij cited on his answer there are times when a simple solution using reflection is really good to test a private method.

Title: How do you unit test private methods?

Body:
If you cannot use external APIs or dont want to, you can still use pure standard JDK API to access private methods using reflection. Here is an example

MyObject obj = new MyObject();
Method privateMethod = MyObject.class.getDeclaredMethod("getFoo", null);
privateMethod.setAccessible(true);
String returnValue = (String) privateMethod.invoke(obj, null);
System.out.println("returnValue = " + returnValue);

Check Java Tutorial http://docs.oracle.com/javase/tutorial/reflect/ or Java API http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html for more information.

As @kij cited on his answer there are times when a simple solution using reflection is really good to test a private method.


问:
Suggestion on how to fill a web form (several times)
I need to fill a form using data from a CSV file. I was planning to use CURL+PHP to do it, but then I realized the form has several steps (one on each page), plus it uses javascript to fill hidden inputs. It is an ASP.NET form, so it has a lot of variables a postback, etc.

I am thinking now, to make a browser extension that would load the CSV file and without any more user input would fill the form, and advance from page to page filling up the form and then somehow wait for the form to finish processing, retrieve the output and restart the form.

I would like to repeat this for 500-600 times. The website in question does not provide an API so filling up forms is the only way.

Does this idea sound feasible, any other ideas?

答: Convert your CSV file into a Selenium script which is basically HTML and run inside your browser. (http://docs.seleniumhq.org/projects/ide/)</p>


问:
Should I have unit tests for known defects?
If my code contains a known defect which should be fixed, but isn't yet, and won't be fixed for the current release, and might not be fixed in the forseeable future, should there be a failing unit test for that bug in the test suite? If I add the unit test, it will (obviously) fail, and getting used to having failing tests seems like a bad idea. On the other hand, if it is a known defect, and there is a known failing case, it seems odd to keep it out of the test suite, as it should at some point be fixed, and the test is already available. </p>

答: If the bug is fresh in your mind and you have the time to write the unit test now, then I would write it now and flag it as a known failure so it doesn't fail the build itself. Your bug tracker should be updated to reflect that there is a unit test that is currently failing for this bug so that the person assigned to eventually fix it doesn't write it all over again. This supposes that the buggy code doesn't need a lot of refactoring and that the API changes significantly -- if that's the case then you might be better off not writing the unit test until you have a better idea of how the test should be written.</p>


答:
The answer is yes, you should write them and you should run them.

Your testing framework needs a category of "known failing tests" and you should mark these tests as falling into that category. How you do that depends on the framework.

Curiously, a failing test that suddenly passes can be just as interesting as a passing test that unexpectedly fails.

Title: Should I have unit tests for known defects?

Body: If my code contains a known defect which should be fixed, but isn't yet, and won't be fixed for the current release, and might not be fixed in the forseeable future, should there be a failing unit test for that bug in the test suite? If I add the unit test, it will (obviously) fail, and getting used to having failing tests seems like a bad idea. On the other hand, if it is a known defect, and there is a known failing case, it seems odd to keep it out of the test suite, as it should at some point be fixed, and the test is already available. </p>


答:
I think you should have an unit test with the current behaviour and in the comments, add the right test and right behaviour. Example:

```<code>@Test
public void test() {
  // this is wrong, it should be fixed some time
  Assert.assertEquals(2, new Calculator().plus(2,2));
  // this is the expected behaviour, replace the above test when the fix is available
  // Assert.assertEquals(4, new Calculator().plus(2, 2));
}
</code>```

This way, when the fix is available, the build will fail, noticing you the failed test. When you'll look at the test, you will know that you changed the behaviour and the test must be updated.

EDIT:
As Captain Man said, in large projects, this will not get fixed anytime soon but for the documentation sake, the original answer is better than nothing.

A better way to do it is duplicating the current test, making the clone assert the right thing and @Ignore it with a message, e.g.

```<code>@Test
public void test() {
  Assert.assertEquals(2, new Calculator().plus(2,2));
}

@Ignore("fix me, Calculator is giving the wrong result, see ticket BUG-12345 and delete #test() when fixed")
@Test
public void fixMe() {
  Assert.assertEquals(4, new Calculator().plus(2, 2));
}
</code>```

This comes with the convention in your team to reduce the number of @Ignored tests. The same way you'd be doing with introducing or changing the test to reflect the bug, except you don't fail the build if this is critical for your team, like OP said that the bugfix won't be included in the current release.

Body:
I think you should have an unit test with the current behaviour and in the comments, add the right test and right behaviour. Example:

@Test
public void test() {
  // this is wrong, it should be fixed some time
  Assert.assertEquals(2, new Calculator().plus(2,2));
  // this is the expected behaviour, replace the above test when the fix is available
  // Assert.assertEquals(4, new Calculator().plus(2, 2));
}

This way, when the fix is available, the build will fail, noticing you the failed test. When you'll look at the test, you will know that you changed the behaviour and the test must be updated.

EDIT:
As Captain Man said, in large projects, this will not get fixed anytime soon but for the documentation sake, the original answer is better than nothing.

A better way to do it is duplicating the current test, making the clone assert the right thing and @Ignore it with a message, e.g.

@Test
public void test() {
  Assert.assertEquals(2, new Calculator().plus(2,2));
}

@Ignore("fix me, Calculator is giving the wrong result, see ticket BUG-12345 and delete #test() when fixed")
@Test
public void fixMe() {
  Assert.assertEquals(4, new Calculator().plus(2, 2));
}

This comes with the convention in your team to reduce the number of @Ignored tests. The same way you'd be doing with introducing or changing the test to reflect the bug, except you don't fail the build if this is critical for your team, like OP said that the bugfix won't be included in the current release.


问:
Potentially Shippable Product Increment - what if users don't like the latest increment?
In our company we do usability test at the end of each Sprint. Many times we discover that the users don't like the implemented feature, so we either completely change it or scrap it in the next Sprint.

However if we start doing potentially shippable product, thus fixing all bugs, running a lot of tests, preparing documentation for FDA and for users, fixing little UI issues - all this work will go to waste if users will not like the feature. Isn't it better NOT to do all this extra potentially shippable stuff until we are sure users actually like the feature?

答:
Your sprints are too large or too complex. Your sprints are failing a key test, putting a lot of work in jeopardy. I believe that a risk (user's not liking an implementation) is not being managed fully or properly, causing extensive rework. Your team's project management style is at fault and you need to plan your sprints accordingly.

Paper or screen mockups, accompanied by lots of handwaving, are much less expensive than code to produce (I'm assuming: you might instead have a killer UI mocking framework). A walkthrough or role playing with appropriate test subjects takes dramatically less effort than building and making a system ready for deployment. Since you already know that user acceptance is high-risk, and that you likely won't get it right the first time, you can plan for multiple iterations within the current sprint in order to get the feature set right.

Since a sprint should not have deliverable elements that depend on elements from earlier in the sprint, you should not plan to deliver the UI/feature elements that you decide on during the current sprint. Instead, the results of the testing inform the planning and development of the following sprint.

In my experience, it is not unreasonable for a sprint to include, let's say, a) code and finishing for hard-and-fast features, b) tech spikes for sprints indefinitely in the future, and c) UI & feature tests for sprints in the near future. This allows you to manage the high risk stuff while continuing to deliver solid, acceptable code with all the proper documentation, etc, that accompanies a product release.

In my last project, we had a sprint constructed with a mix of a) a one-paragraph description of a feature or UI element for review by the user group, b) a screen-shot walkthrough and hand-waving session, c) a prototype ready for play-testing of a feature from a previous sprint, and d) a ready-for-final-acceptance testing feature that was first presented two sprints ago.


答:
Opening a new connection takes a long time - client libraries have to work out which server to talk to, then open a negotiation with that server to get an initial connection, then start bouncing credentials back and forth to authenticate the client, then start up a database session, and [finally] configure that session the way the application wants it.

Slow!

Pooling connections allows most (but not all) of that overhead to be eliminated with no extra work on the part of the application.  The bulk of your error handling is around not being able to get into the database in the first place.

Great for web-applications, where the web server has to get in, do something and get out again, over and over again for a multitude of difference clients.

Not so good for, say, a Windows Service that's running "in background" 24x7 but where the underlying database "disappears" for "some time" every night for housekeeping and other, maintenance activities.

Sure, you could shut the service down while that's going on, but (in the absence of any managed way of doing so at the time) our solution was to build the application to treat its database as a transient entity.  It established a database connection when it could and then held it open and, whenever it wanted to use the database, half-expected it to have "disappeared".  And yes, the error handling needed was far more complicated, but that service has now been running quite happily for a decade and half!  (OK, not continuously; the host gets rebooted every month for patching).


问:
Maintaining independence between modules
I am reading Algorithms 4th Edition by Robert Sedgewick and in chapter 1.2 it discusses API design.  It says:

"The key to success in modular programming is to maintain independence between modules.  We do so by insisting on the API being the only point of dependence among modules."

Now the book is based on Java.  I am considering this in terms of C++ development (but I imagine concepts are similar).

Is this suggesting that if I have a library eg to do networking, that if a client #includes my net.hpp header (fictional name) and maybe sets to link with net.lib then no other includes or libraries should be required?  Is that the jist of this?  Or is there something else?

答:
No, the point is that to use one specific library, all you need to know about it should be in its public interface (in C++, typically the header file). You should not have to know anything other than that, particularly not anything about what algorithms, data types, variables etc. exist within the library. If you did know, you might start relying on this information, and you would be burnt when the library implementation is changed one day.

It is quite common that using one library requires you to include more headers from other libraries - for instance, using a HTTP library might require you to import the definitions of request or packet definitions that the HTTP library itself uses in its API. But it shouldn't require you to import a LinearTrie data structure merely because the HTTP library uses one in its private code.


问:
Models Views and Controllers jobs
First, I know there are lot of answers about MVC but I need some more-specific ansewer based on my probably wrong understanding of MVC.

I've already read this very good answer (Explain Model View Controller) but I still need some clarification.

I need to understand if I've understood how MVC works because I'm using it in a kind of MVC framework I'm developing.

I have the views that are at the moment just "stupid" templates

The models that are "things" that fetch data from database (or other sources) and transform them in arrays passed to the views.

The controllers that are mostly ajax javascript scripts and observers for buttons and other user events and PHP scripts that are called by the Ajax scripts when I need to perform server-side operations like SQL updates, inserts etc.

So my "MVC understanding" makes my app works in this way:

I open my index that loads the viewsloader(model), this one loads the contents calling the contentsloader(model) that calls some other script depending by the view the user is requesting.

Then when all the data is loaded in a single array, the viewsloader(model) uses it to render the requested view and passes it to the user.

Now the user can click some button (for example a "view contacts" button) and under the hood my contactslistener(controller) calls the contactsloader(model) to load the contacts list, the array provided by the contactsloader(model) passed trhough the contactslistener(controller) which injects it in the view.

I think I have serious problems with the MVC model, looks like the controllers are doing too different things. Probably I should put the observers/listeners in the views part and use controllers just to load contents provided by the models.

Are the models dedicated just to data fetching and organization (for example, fetch from database and put it in array organizing it with the right structure)?

Are the controllers thought for handle user events or should I use views for this purpose? Should I use them to query the models and inject the answers into the views?

Are the views just stupid templates or should I put there some business logic like event listeners? Following what I've read I should put the entire interface-side scripts here and put only (client/server)-side scripts in controllers. But in this case I've not idea about what a controller should do...

答:
Thanks to Euphoric for the very useful answer, I've got what he means but I've even found a very good article about MVC used besides Ajax.

It's not "the bible of MVC" but I've used it to understand the functions that each part of MVC should do.

This is the chart I've found useful, edited a bit by meself:

I've added the HTTP response and requests from and to static-HTML because using a template engine like Mustache there aren't the problems described in the article I link below:

https://blog.glyphobet.net/essay/153

Title: Models Views and Controllers jobs


问:
Use of LGPL libraries on android devices (in a single closed source .apk)
Well this question is actually asked multiple times here already.

but the answers are contradictory

So that's why I ask it again (maybe time changed things). Can LGPL licensed libraries be used in closed source applications on androids? Specifically, when they are linked together dynamically through .so. but inside a single apk package.

this topic explains how this is possible and what steps should be taken. However it takes for granted that users are able to repackage the apk file (and thus open up the apk file).

Then this topic simply questions the given above. And the answer is "you don't".

So what is it, can users of your program (when you give them an APK) get their own version of the library, compile it and replace that?

(PS: not sure if I should place it here or on stackoverflow, please move to best location)

答:
The answer is yes. There are some specific requirements and you need to read and understand to be sure you comply. Read S4 in particular.

The requirements are not especially onerous for dynamic linking. Under 4 (d) 1, you only have to "use a suitable mechanism" and provide some additional information. There is language in the licence suggesting a kind of suitable mechanism, but it reads as enabling rather than mandatory, so an equivalent mechanism should suffice. There is a clear obligation that the mechanism be feasible. For example, a method that depended on repackaging the APK might be suitable and this might preclude signing or other protective measures.

There is no obligation that it be technically easy, and your obligations do not extend to educating the user (who is assumed to have the necessary technical skills), to providing active assistance or to changing your application to make it easier.

In practical terms, this obligation will not arise unless or until a specific user wants to replace the library you provide with a different one, perhaps with a bug fix. In that case you cannot withhold information needed to let them do so, or take any action to hinder them, but whether you provide assistance or offer a service is a commercial decision.

Disclaimer: I'm not a lawyer, but I do make these decisions on behalf of my company.


答:
No, thats not it.

It means that the networking library consists of two parts. An API, that defines how your code should communicate with this library and an implementation part, that does the doing of the library. And that your code should only depend on the API part and should not depend, both directly and transitively on the implementation part. The advantage of this kind of design is that you can easily change the inner workings of the library, without having to worry about breaking the code that uses this library.

It is actually somehow difficult to do this in C++, because if you try to use header files as your API, then they have to contain the implementation details of the library in form of private members. And if you try to have two "sublibraries", then the compilation pipeline of the code that uses this this separated library becomes much more complicated. And lets not talk about how would memory management happen in this case.

Title: Maintaining independence between modules

Body:
I am reading Algorithms 4th Edition by Robert Sedgewick and in chapter 1.2 it discusses API design.  It says:

"The key to success in modular programming is to maintain independence between modules.  We do so by insisting on the API being the only point of dependence among modules."

Now the book is based on Java.  I am considering this in terms of C++ development (but I imagine concepts are similar).

Is this suggesting that if I have a library eg to do networking, that if a client #includes my net.hpp header (fictional name) and maybe sets to link with net.lib then no other includes or libraries should be required?  Is that the jist of this?  Or is there something else?


问:
Which database schema should I pick?
I am planning a database scheme and I hesitate between two designs,
which one should I choose?

For the purpose of the question, assume we want to prepare a database
scheme for an application managing student information in a
university.  There is several modules in the application:

Registry, dealing with general informations, like date of birth,
 health insurance number, and the like.

Library, dealing with the properties useful to the library
 management, like the number of books withdrawn, quitus or
 penalties.

Exams, dealing with the exams taken and the grades.

The modules Library and Exams see the modules Registry, but apart from
that, are independant.

In the application scenario, there is a very large number of students,
data is written once, seldom updated and often read.  Furthermore, the
university expands its system each year, so that modules are added:
Sport, Campus, whatever.  Modules remain quite independant.

I hesitate between two database layouts.

First layout

In the first layout, a table MODULE is associated to each Module and
a UID is used as primary key.  Since each module needs the
properties under control of Registry, we also prepare views of the
join of REGISTRY and MODULE on UID, so that the database knows
we will use this join extensively.

When the system expands, we add a new table and a new view to reflect
this expansion.

Second layout

In the second layout, we create a table with a large number of columns
holding the properties of the various modules.

When the system expands, we add columns to the tables.

Comparison

How does these two approaches compare?

If, say, some software upgrade comes with a major bug, requiring to
downgrade the software and perform later a second upgrade, the first layout seems to
be more robust. Regarding perfomance, the second layout saves a lot of
join operations, but in the first layout, we defined views for the
join operations, thus advertising which complex operations are likely
to happen so that the database system can plan this.  I am far from a
database expert, but am I right if I think that if I put all relevant
information into the hands of the database system, it will be able to
properly carry operation?

If I did not see it used in industrial applications, I would never had
given 2 pences on the second layout.  But since I did, I would like to
get other advises.

答:
(At the risk of shouting) First Layout - DEFINITELY.

the second is an Entity-Attribute-Value model which, in all but a handful of cases, causes far more problems than they solve.  Also, you state that "Modules are independent"; mash them altogether into an E.A.V. model and they're forever intertwined.

I would suggest:

Table REGISTRY

Primary Key on USER_ID

Secondary indexes on names and other, commonly-searched fields (watch out for the case of these values; many DBMSs regard "A" != "a").

Table MODULE

Primary Key on MODULE_ID.

A module must be able to exist without any students, so USER_ID cannot appear in this table (except, possibly, as a foreign key to the Module's "owner").

For Students registered on a module, you'll need a "linking" table:

Table MODULE_STUDENT

Primary Key on USER_ID and MODULE_ID.

Secondary index on MODULE_ID (and USER_ID).

If you're using referential integrity (and you should), then add foreign keys to validate the values held in this table:

MODULE_ID -> MODULE.MODULE_ID

USER_ID -> REGISTRY.USER_ID

Where necessary, join across REGISTRY, MODULE_STUDENT and/or MODULE to get all the related information.

Views will not help the performance of your system.

Correct indexing, of the tables underlying those views, will.

(And Views will [probably] make your application coding easier).

Title: Which database schema should I pick?


答:
I suppose the answer really is, it depends. Be pragmatic about it. What does writing it now gain you? Maybe it is fresh in your mind?

When fixing the bug, it makes perfect sense to prove it exists by writing a unit test that exposes the bug. You then fix the bug, and the unit test should pass.

Do you have time to write the failing unit test just now? Are there more pressing features or bug that need to be written/fixed.

Assuming you have competent bug tracking software with the bug logged in it, there is really no need to write the failing unit test right now.

Arguably you might introduce some confusion if you introduce a failing unit test before a release that is happening without the bug fix.


答: I usually feel uneasy about having known failures in test suites, because it's too easy for the list to grow over time, or for unrelated failures in the same tests to be dismissed as "expected". The same things goes for intermittent failures - there could be something evil lurking the code. I'd vote for writing the test for the code as it is now, and as it should be once it's fixed but commented out or disabled somehow.</p>


问:
Relationships in a Chen ERD
I am working on a Chen ERD to model our organizations merchandise.  Our central entity is a Style.  We have supplemental entities of Color and Season.

I am defining our assortment as the relationship between these three entities, and this relationship itself will have attributes and is defined by the three entities which participate in the mandatory relationship.  The rules are;

Many Styles can be offered in a Season, and a Style can be offered in many Seasons.

Within a Season, a Style can be offered in Many Colors.

I then have 2 other entities, one of which I believe is a weak entity, Climate, and the other may be weak, but I am not sure, this being Transaction Channel.

I am thinking of these as relationships off of a relationship?  Meaning, for a given Style/Color combination offered in a Season, it can be available through 1 or more Transaction Channels.  Additionally, within a season, a given Style/Color combination can be intended for 1 or more Climates.

Is it valid to have relationships off of relationships?  Or does this requirement dictate that I should think of this Style/Color/Season relationship as an entity itself, and define the relationships to Climate and Transaction Channel off of this entity?

答:
A relationship is a way to link rows in tables. The start and end points are tables (or views). It doesn't make sense to talk about relationships off a relationship per se, however, you can have a link table (for instance used to express a many-to-many relationship like you have with style and season) which you can create relationships to/from.

In your case the data model could look like this:

style: a style that can be offered in various colors in various seasons.

color: a color that the style is offered in.

season: a period of time in which the style/color is offered.

channel: a party making the style/color available for a given season.

climate: a climate for which the style/color/season is intended.

Since a style can be offered in many seasons and a season can have many styles, you have a many-to-many relationship that you need to break up with a link table. Now, you also say that within a season a style is offered in many colors. This leads us to the following combination: season-style-color. In plain English, a season has many styles of which can have many colors. I'm assuming that the colors may vary for each season. I believe this triplet represents a concrete product (e.g. "a red sweater for winter"). This leads us to:

```<code>            color
              ^
              |
  style <- product -> season
</code>```

In other words, a product is what's being made available to the channels you mentioned. Furthermore, a product is suitable for a particular climate.

In terms of tables:

style: style_id (pk), ...

color: color_id (pk), ...

season: season_id (pk), ...

climate: climate_id (pk), ...

product: (style_id(fk),color_id(fk),season_id{fk)) (pk), ... (see note below).

channel: channel_id (pk), ...

availability: (product_id(fk),product_id(fk)) (pk), ...

The notation "(col_1 (fk), col_2, ..., col_n) (pk)" is my attempt to express a composite primary key. A composite primary key is made up of more than one column and the columns can be foreign keys or regular business values. This allows you to express a product as a combination of style, color and season. Furthermore, you can express when a product is available for a particular channel (the "when" part is part of the season which is part of the product).

Does that make sense?

Title: Relationships in a Chen ERD

Body:
A relationship is a way to link rows in tables. The start and end points are tables (or views). It doesn't make sense to talk about relationships off a relationship per se, however, you can have a link table (for instance used to express a many-to-many relationship like you have with style and season) which you can create relationships to/from.

In your case the data model could look like this:

style: a style that can be offered in various colors in various seasons.

color: a color that the style is offered in.

season: a period of time in which the style/color is offered.

channel: a party making the style/color available for a given season.

climate: a climate for which the style/color/season is intended.

Since a style can be offered in many seasons and a season can have many styles, you have a many-to-many relationship that you need to break up with a link table. Now, you also say that within a season a style is offered in many colors. This leads us to the following combination: season-style-color. In plain English, a season has many styles of which can have many colors. I'm assuming that the colors may vary for each season. I believe this triplet represents a concrete product (e.g. "a red sweater for winter"). This leads us to:

            color
              ^
              |
  style <- product -> season

In other words, a product is what's being made available to the channels you mentioned. Furthermore, a product is suitable for a particular climate.

In terms of tables:

style: style_id (pk), ...

color: color_id (pk), ...

season: season_id (pk), ...

climate: climate_id (pk), ...

product: (style_id(fk),color_id(fk),season_id{fk)) (pk), ... (see note below).

channel: channel_id (pk), ...

availability: (product_id(fk),product_id(fk)) (pk), ...

The notation "(col_1 (fk), col_2, ..., col_n) (pk)" is my attempt to express a composite primary key. A composite primary key is made up of more than one column and the columns can be foreign keys or regular business values. This allows you to express a product as a combination of style, color and season. Furthermore, you can express when a product is available for a particular channel (the "when" part is part of the season which is part of the product).

Does that make sense?


答:
I will treat this as an algorithm question. It may not be what was intended.

Go through the first list, creating an lookup from key->index. In your example, a->1, b->2, c->3, d->4 and so on.

Go through the second list, looking up each element and comparing its index to its neighbour's index. In your case b->2 appears after d->4, which is out of order.

Each of the out of order elements by this criterion is one that has moved. Inserted elements have no index, and deleted elements will not be examined.

Title: Detect Order Changes in a List

Body:
Let's say you have a list of values that are:

a

b

c

d

e

The order on the list might be changed.

a

c

d

b

e

How would you detect this change? We needed something like this when we were building a revision history page for our online form building tool. We found a quick and dirty solution, but I am looking for a more elegant solution for this. Here is what the revision descriptions look like:

Here is the tough part: Elements can be removed/added from/to anywhere on the list. So, the algorithm should be able to ignore those changes.


问:
Citing Borrowed Code
If you borrow code from some source, it is probably best to cite it (like "adapted from [source]"). However, if you take let's say you borrowed this function (example in C++):

```<code>void doWork()
{
     cout << "Doing work!\n" << endl;
}
</code>```

and now you editted it to be like this:

```<code>void doWork()
{
     string name = "";

     cout << "Starting work...\n" << endl;
     cout << "Hello user. What is your name?" << endl;

     cin >> name;
     ...
}
</code>```

Would you still have to say "adapted from [source]" or something like that? Or are you in the safe zone?

Note: I am specifically wondering how this applies to copyrighted (and open source) code

答:
If you are taking code from copyrighted or open source code, then you must conform by the licensing terms under which you obtained the code. If you do not have such a licensing agreement, then you are in violation of copyright law regardless of whether you cite the code or not.

In the case of GPL, in order to use the snippet of code, you must also release ALL of your code under the GPL and include the GPL license as part of your distributed product. You do not need to cite which part you borrowed.

Commercial code typically does not require any form of acknowledgement, licensing or citation.

Other open source licenses may vary in requirements, but as far as I know none require you to cite the individual parts of the code.

Title: Citing Borrowed Code


问:
Is it correct to require end-users to clear their cookies?
Is it any indications of poor programming if the support staff for a given product requires you to clear the cookies in order to troubleshoot issues with their web-site?

As a point of example, if you're trying to activate a new SIM on a tablet, and the carrier's activation web-site is giving you an error message that their web-site is down, even though there is no problem with actually accessing their web-server, which responds with the our-website-is-down page just fine.

Subsequently, the support staff instructs the user to try clearing the cookies (even though this activation web-site is not know to have been accessed prior to the error message taking place).

答:
If the user's expectations is correct and the actual result is different then there's a bug by definition.

You're conflating programming with technical support. They're not the same. Troubleshooting means identifying the problem and hopefully fixing it. If you're calling tech support to register a SIM do you really care what the bug is or do you want to register your SIM? Tech support is trained to solve the problem and get you on your way, not debug the code.

Furthermore, you're equating the web site with the web application. A web site can be up (and serving you the error page) while the application that lets you register your SIM is down. Providing you an error message that says the application is down is a lot more useful than keeping you in the dark -- you can for instance call and have them register the SIM manually.

The support staff in this case seems to be unaware that the web application is down and thus they are making you jump through hoops unnecessarily. A good principle in tech support is never to trust the user, but it's also a good thing to think for yourself and not always blindly follow the script.


问:
Can a scrum master reprimand his team?
Scrum master is a facilitator for the delivery team and acts as a bridge between Project Management and the team. In course of time if he realizes that his team is not delivering the deliverables perfectly possible w.r.t competency of his team, can he question his team members why it is not happening?

It is more like a show-cause notice to them. He knows why it is not happening eg:- spending time on social sites or wasting time on less important issues.

Is it okay for him to say "reprimand" the delivery team on their style of working? Or should it be escalated and left for the functional managers to deal with it?

Important thing to note is that usually in an Org, the scrum master is a good friend with his team and so it makes all the more awkward to react to such a situation.

答:
A Scrum master doesn't reprimand. He or she sees problems and facilitates the team to tackle them.

If the team struggles, it's his or her job to articulate the problems and try to get the team to do a root cause analysis on those problems.

To elaborate on your example: spending time on social network sites is not a root cause. If the team is spending too much time on those sites (and that's still an "if"), there's probably a reason for that. Maybe they need a relief, maybe their work is too boring because they can't take charge of architecting the solution, maybe...

The first step is talking to the team. Let them figure out what's going wrong.

Title: Can a scrum master reprimand his team?


问:
How to validate (and group) User Listings in Marketplace
I am building a hobby marketplace (comic books). Users are able to list comic books they own for trading with other members. The problem I'm running into is that I would like to standardize the listings so I can display multiple options per title. Like this:

User 1 lists: "Amazing Spider-man #4" on site.com/amazing-spider-man-4

User 2 goes to list "amazing spiderman 4" -> direct him to place the listing on site.com/amazing-spider-man-4 instead.

Then this starts to get a bit complex... so in a theoretical example, there could be numerous volumes of each series. i.e. Amazing spider-man #4 (released in 1965) and then again, due to a reboot another Amazing spider-man #4 (released in 1981) or whatever.

Is the answer to this to create a database and populate it with all series titles, issue counts and volumes, and then require the user to select one of those before making a submission? Such a data-source does not exist with reliable "volume" information, so I'm not sure how I'd do it.

答:
The problem is that you're allowing free text input and the user is allowed to inut whatever he/she wants to. The examples list the title ("Amazing Spiderman"), the issue ("#4" and "4"), and even the year published ("released in 1965").

The first question you should ask is: what information am I really asking the user for? Do I really want title, issue and year? Should I ask for these things separately instead of in a single field?

If you take the three values you mention ("Amazing Spider-man #4", "amazing spiderman 4" and "Amazing spider-man #4 (released in 1965)" and strip the special characters, formatting, etc you get:

```<code>amazingspiderman4
amazingspiderman4
amazingspiderman4releasedin1965
</code>```

As you see the first 17 characters are the same. That means that if I start typing you can automatically match my input to what's already know and provide suggestions to me.

So I suggest two solutions:

a) break out and classify your data set better; group it into title, issue and year, and make unusual fields optional.

b) implement fuzzy string matching and present the user with the matches so he/she can pick whatever is right or type his/her own.

Option a) is probably the least effort as you're formalizing the input and not allowing as much room for error.

Body:
The problem is that you're allowing free text input and the user is allowed to inut whatever he/she wants to. The examples list the title ("Amazing Spiderman"), the issue ("#4" and "4"), and even the year published ("released in 1965").

The first question you should ask is: what information am I really asking the user for? Do I really want title, issue and year? Should I ask for these things separately instead of in a single field?

If you take the three values you mention ("Amazing Spider-man #4", "amazing spiderman 4" and "Amazing spider-man #4 (released in 1965)" and strip the special characters, formatting, etc you get:

amazingspiderman4
amazingspiderman4
amazingspiderman4releasedin1965

As you see the first 17 characters are the same. That means that if I start typing you can automatically match my input to what's already know and provide suggestions to me.

So I suggest two solutions:

a) break out and classify your data set better; group it into title, issue and year, and make unusual fields optional.

b) implement fuzzy string matching and present the user with the matches so he/she can pick whatever is right or type his/her own.

Option a) is probably the least effort as you're formalizing the input and not allowing as much room for error.


答:
There is absolutely no contradiction.

The first question you link to explains that you are allowed to use LGPL-licensed libraries in proprietary Android applications under the condition that they are compiled as separate shared libraries and that the application will continue working if the user repackages it to satisfy the LGPL requirement that the user must have a way to use their modified version of the LGPL code.

The second question concerns technical way of packaging executables, not libraries into Android packages and says nothing about licensing except for motivation. The answer there is also not that it's not possible, but only that it does not work the way the asker expected.

Title: Use of LGPL libraries on android devices (in a single closed source .apk)

Body:
Well this question is actually asked multiple times here already.

but the answers are contradictory

So that's why I ask it again (maybe time changed things). Can LGPL licensed libraries be used in closed source applications on androids? Specifically, when they are linked together dynamically through .so. but inside a single apk package.

this topic explains how this is possible and what steps should be taken. However it takes for granted that users are able to repackage the apk file (and thus open up the apk file).

Then this topic simply questions the given above. And the answer is "you don't".

So what is it, can users of your program (when you give them an APK) get their own version of the library, compile it and replace that?

(PS: not sure if I should place it here or on stackoverflow, please move to best location)


答:
The answer is NO IMHO.
You should not add a unit test for the bug until you start working on the fix for the bug and than you will write the test(s) that proves the bug and when that test(s) is failing in accordance to the bug report(s) you will go and correct the actual code to make the test(s) pass and the bug will be solved and it will be covered after that.

In my world we would have a manual test case that the QEs have failing until the bug gets fixed. And us as developers would be aware of it via the manual failing TC and via the bug tracker.

The reason for not adding failing UTs is simple. UTs are for direct feedback and validation of what I as a developer are currently working. And UTs are used in the CI system to make sure I didn't break something unintentionally in some other area of code for that module. Having UTs failing intentionally for a know bug IMHO would be counter productive and just plain wrong.


问:
What is the name of the functional argument in fold
In the higher order function fold/reduce what is the name, if any, of the functional argument?

I am working on a monadic tabular processing library where rows are folded to produce simple analyses (like finding the minimum, maximum, average of a column).  I am therefore looking for a sound name for the argument of the fold function and any name which is well-established in the ML community (or Haskell or Common Lisp as second and third candidates) would be interesting.

A name like f is common in the description of fold functions, it is however undescriptive and a noun would be better suited.

答:
I don't know if there's a single answer to this, as @jozefg mentioned.  And so purely out of speculation, here's one possible explanation:

I suspect the reason is because the type -- (a -> b -> b) in Haskell's foldr, for example -- is more meaningful than any name one could come up with.  Since the a and b type parameters could be anything, the function could do pretty much anything as well.  So you're left with names like function, combiner, morphism, and argument, which aren't especially meaningful either.  Might as well use a short, non-distracting name.

Another example is the id :: a -> a function: what should you call its argument?  Again, I think id's type is more descriptive than its argument name.

However, I agree with you -- it seems like there should be a common name, perhaps in mathematics.  I hope somebody can correct me on this.

Some examples of its name in real code:

In Haskell's libraries, it's mostly called f (and sometimes operator in the comments):

```<code>class Foldable t where
    -- | Map each element of the structure to a monoid,
    -- and combine the results.
    foldMap :: Monoid m => (a -> m) -> t a -> m
    foldMap f = foldr (mappend . f) mempty

    -- | Right-associative fold of a structure.
    --
    -- @'foldr' f z = 'Prelude.foldr' f z . 'toList'@
    foldr :: (a -> b -> b) -> b -> t a -> b
    foldr f z t = appEndo (foldMap (Endo . f) t) z

    -- | Right-associative fold of a structure,
    -- but with strict application of the operator.
    foldr' :: (a -> b -> b) -> b -> t a -> b
    foldr' f z0 xs = foldl f' id xs z0
      where f' k x z = k $! f x z

    -- | Left-associative fold of a structure.
    --
    -- @'foldl' f z = 'Prelude.foldl' f z . 'toList'@
    foldl :: (a -> b -> a) -> a -> t b -> a
    foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z

    -- | Left-associative fold of a structure.
    -- but with strict application of the operator.
    --
    -- @'foldl' f z = 'List.foldl'' f z . 'toList'@
    foldl' :: (a -> b -> a) -> a -> t b -> a
    foldl' f z0 xs = foldr f' id xs z0
      where f' x k z = k $! f z x

    -- | A variant of 'foldr' that has no base case,
    -- and thus may only be applied to non-empty structures.
    --
    -- @'foldr1' f = 'Prelude.foldr1' f . 'toList'@
    foldr1 :: (a -> a -> a) -> t a -> a
    foldr1 f xs = fromMaybe (error "foldr1: empty structure")
                    (foldr mf Nothing xs)
      where
        mf x Nothing = Just x
        mf x (Just y) = Just (f x y)

    -- | A variant of 'foldl' that has no base case,
    -- and thus may only be applied to non-empty structures.
    --
    -- @'foldl1' f = 'Prelude.foldl1' f . 'toList'@
    foldl1 :: (a -> a -> a) -> t a -> a
    foldl1 f xs = fromMaybe (error "foldl1: empty structure")
                    (foldl mf Nothing xs)
      where
        mf Nothing y = Just y
        mf (Just x) y = Just (f x y)

-- instances for Prelude types

instance Foldable Maybe where
    foldr _ z Nothing = z
    foldr f z (Just x) = f x z

    foldl _ z Nothing = z
    foldl f z (Just x) = f z x

instance Ix i => Foldable (Array i) where
    foldr f z = Prelude.foldr f z . elems
    foldl f z = Prelude.foldl f z . elems
    foldr1 f = Prelude.foldr1 f . elems
    foldl1 f = Prelude.foldl1 f . elems

-- | Monadic fold over the elements of a structure,
-- associating to the right, i.e. from right to left.
foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
foldrM f z0 xs = foldl f' return xs z0
  where f' k x z = f x z >>= k

-- | Monadic fold over the elements of a structure,
-- associating to the left, i.e. from left to right.
foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a
foldlM f z0 xs = foldr f' return xs z0
  where f' x k z = f z x >>= k

-- | Map each element of a structure to an action, evaluate
-- these actions from left to right, and ignore the results.
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
traverse_ f = foldr ((*>) . f) (pure ())

-- | Map each element of a structure to a monadic action, evaluate
-- these actions from left to right, and ignore the results.
mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
mapM_ f = foldr ((>>) . f) (return ())
</code>```

It's also called f in Clojure:

```<code>(def
    ^{:arglists '([f coll] [f val coll])
      :doc "f should be a function of 2 arguments. If val is not supplied,
  returns the result of applying f to the first 2 items in coll, then
  applying f to that result and the 3rd item, etc. If coll contains no
  items, f must accept no arguments as well, and reduce returns the
  result of calling f with no arguments.  If coll has only 1 item, it
  is returned and f is not called.  If val is supplied, returns the
  result of applying f to val and the first item in coll, then
  applying f to that result and the 2nd item, etc. If coll contains no
  items, returns val and f is not called."
      :added "1.0"}
    reduce
     (fn r
       ([f coll]
             (let [s (seq coll)]
               (if s
                 (r f (first s) (next s))
                 (f))))
       ([f val coll]
          (let [s (seq coll)]
            (if s
              (if (chunked-seq? s)
                (recur f
                       (.reduce (chunk-first s) f val)
                       (chunk-next s))
                (recur f (f val (first s)) (next s)))
              val)))))
</code>```

Body:
I don't know if there's a single answer to this, as @jozefg mentioned.  And so purely out of speculation, here's one possible explanation:

I suspect the reason is because the type -- (a -> b -> b) in Haskell's foldr, for example -- is more meaningful than any name one could come up with.  Since the a and b type parameters could be anything, the function could do pretty much anything as well.  So you're left with names like function, combiner, morphism, and argument, which aren't especially meaningful either.  Might as well use a short, non-distracting name.

Another example is the id :: a -> a function: what should you call its argument?  Again, I think id's type is more descriptive than its argument name.

However, I agree with you -- it seems like there should be a common name, perhaps in mathematics.  I hope somebody can correct me on this.

Some examples of its name in real code:

In Haskell's libraries, it's mostly called f (and sometimes operator in the comments):

class Foldable t where
    -- | Map each element of the structure to a monoid,
    -- and combine the results.
    foldMap :: Monoid m => (a -> m) -> t a -> m
    foldMap f = foldr (mappend . f) mempty

    -- | Right-associative fold of a structure.
    --
    -- @'foldr' f z = 'Prelude.foldr' f z . 'toList'@
    foldr :: (a -> b -> b) -> b -> t a -> b
    foldr f z t = appEndo (foldMap (Endo . f) t) z

    -- | Right-associative fold of a structure,
    -- but with strict application of the operator.
    foldr' :: (a -> b -> b) -> b -> t a -> b
    foldr' f z0 xs = foldl f' id xs z0
      where f' k x z = k $! f x z

    -- | Left-associative fold of a structure.
    --
    -- @'foldl' f z = 'Prelude.foldl' f z . 'toList'@
    foldl :: (a -> b -> a) -> a -> t b -> a
    foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z

    -- | Left-associative fold of a structure.
    -- but with strict application of the operator.
    --
    -- @'foldl' f z = 'List.foldl'' f z . 'toList'@
    foldl' :: (a -> b -> a) -> a -> t b -> a
    foldl' f z0 xs = foldr f' id xs z0
      where f' x k z = k $! f z x

    -- | A variant of 'foldr' that has no base case,
    -- and thus may only be applied to non-empty structures.
    --
    -- @'foldr1' f = 'Prelude.foldr1' f . 'toList'@
    foldr1 :: (a -> a -> a) -> t a -> a
    foldr1 f xs = fromMaybe (error "foldr1: empty structure")
                    (foldr mf Nothing xs)
      where
        mf x Nothing = Just x
        mf x (Just y) = Just (f x y)

    -- | A variant of 'foldl' that has no base case,
    -- and thus may only be applied to non-empty structures.
    --
    -- @'foldl1' f = 'Prelude.foldl1' f . 'toList'@
    foldl1 :: (a -> a -> a) -> t a -> a
    foldl1 f xs = fromMaybe (error "foldl1: empty structure")
                    (foldl mf Nothing xs)
      where
        mf Nothing y = Just y
        mf (Just x) y = Just (f x y)

-- instances for Prelude types

instance Foldable Maybe where
    foldr _ z Nothing = z
    foldr f z (Just x) = f x z

    foldl _ z Nothing = z
    foldl f z (Just x) = f z x

instance Ix i => Foldable (Array i) where
    foldr f z = Prelude.foldr f z . elems
    foldl f z = Prelude.foldl f z . elems
    foldr1 f = Prelude.foldr1 f . elems
    foldl1 f = Prelude.foldl1 f . elems

-- | Monadic fold over the elements of a structure,
-- associating to the right, i.e. from right to left.
foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
foldrM f z0 xs = foldl f' return xs z0
  where f' k x z = f x z >>= k

-- | Monadic fold over the elements of a structure,
-- associating to the left, i.e. from left to right.
foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a
foldlM f z0 xs = foldr f' return xs z0
  where f' x k z = f z x >>= k

-- | Map each element of a structure to an action, evaluate
-- these actions from left to right, and ignore the results.
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
traverse_ f = foldr ((*>) . f) (pure ())

-- | Map each element of a structure to a monadic action, evaluate
-- these actions from left to right, and ignore the results.
mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
mapM_ f = foldr ((>>) . f) (return ())

It's also called f in Clojure:

(def
    ^{:arglists '([f coll] [f val coll])
      :doc "f should be a function of 2 arguments. If val is not supplied,
  returns the result of applying f to the first 2 items in coll, then
  applying f to that result and the 3rd item, etc. If coll contains no
  items, f must accept no arguments as well, and reduce returns the
  result of calling f with no arguments.  If coll has only 1 item, it
  is returned and f is not called.  If val is supplied, returns the
  result of applying f to val and the first item in coll, then
  applying f to that result and the 2nd item, etc. If coll contains no
  items, returns val and f is not called."
      :added "1.0"}
    reduce
     (fn r
       ([f coll]
             (let [s (seq coll)]
               (if s
                 (r f (first s) (next s))
                 (f))))
       ([f val coll]
          (let [s (seq coll)]
            (if s
              (if (chunked-seq? s)
                (recur f
                       (.reduce (chunk-first s) f val)
                       (chunk-next s))
                (recur f (f val (first s)) (next s)))
              val)))))


问:
Best way to display domain object summary information efficiently and in an OO way from a large inheritance tree?
I've provided only simplified code as it's more of an abstract design question.

So I have many, many nested business/domain event objects, e.g.

```<code> public class Event
 {
  //bunch of properties and standard accessors
 }

 public class ExplosionEvent extends Event
 {
  //properties and standard accessors
 }
</code>```

And many more of these at different levels.  If I need information about any given object chosen, I display it in HTML like so

```<code> private String generateHTML(Event event)
 {
   StringBuilder sb = new StringBuilder();

   sb.append("<HTML><table>");//simplified

   sb.append("<TH>Time</TH>");
   sb.append("<TD>" + event.getEventTime() + "</TD>");

   if (event instanceof ExplosionEvent)
   {
     //append HTML and ExplosionEvent specific data
   }

   // ...many, many more calls like the one above

   sb.append("</table></HTML>");
 }
</code>```

As I have many event types, this means loads of duplicated HTML table tags and uses of instanceof so generateHTML is hundreds of lines long, split into methods of course but still, it's a lot of code that makes this hard to understand, navigate and therefore maintain.

This is ugly and I need a better design for this.  I had the idea of creating a method on Event which is overridable by all sub methods

```<code>//Using LinkedHashMap to preserve order as Properties wont do that
public LinkedHashMap<String, String> getAttributes()
{
 LinkedHashMap<String, String> list = new LinkedHashMap<String, String>();

 list.put("Time", eventTime);
}
</code>```

sub-classes then override this, call their parent and add date specific to them to the list meaning that no matter how many Event classes there is, the existing generateHTML method (external to Event objects) will then simply be one small loop

```<code>private String generateHTML(Event event)
{
  StringBuilder sb = new StringBuilder();

  b.append("<HTML><table>");

  for (Entry<String,String> entry : event.getAttributes().entrySet())
  {
    sb.append("<TH>" + entry.getKey() + "</TH>");
    sb.append("<TD>" + entry.getValue() + "</TD>");
  }

  sb.append("</table></HTML>");
}
</code>```

Is this putting too much logic in business/domain objects?

Is there a better way?

答:
This looks suspicious to me ...

```<code>if (event instanceof ExplosionEvent)
{
  //append HTML and ExplosionEvent specific data
}
</code>```

... usually when I see that I think that Event ought to be abstract with an overridable method. That method be LinkedHashMap<String, String> getAttributes() as you suggested.

Another possibility is to store the LinkedHashMap as a member of Event (pseudo-code ahead):

```<code>class Event
{
    LinkedHashMap<String, String> map;
    protected void SetAttribute(String name, String value)
    {
        // stores in map
    }
    protected String getAttribute(String name)
    {
        // gets from map
    }
    LinkedHashMap<String, String> getAttributes()
    {
        // returns entire map
    }
}

class ExplosionEvent inherits Event
{
    String getLocation() { return getAttribute("location"); }
    void setLocation(String location) { setAttribute("location", location); }

}
</code>```

You could consider using the java.utils.Properties for your implementation.

Another solution might be to use reflection.

OwnerDisplayName: Ross Drew

Body:
This looks suspicious to me ...

if (event instanceof ExplosionEvent)
{
  //append HTML and ExplosionEvent specific data
}

... usually when I see that I think that Event ought to be abstract with an overridable method. That method be LinkedHashMap<String, String> getAttributes() as you suggested.

Another possibility is to store the LinkedHashMap as a member of Event (pseudo-code ahead):

class Event
{
    LinkedHashMap<String, String> map;
    protected void SetAttribute(String name, String value)
    {
        // stores in map
    }
    protected String getAttribute(String name)
    {
        // gets from map
    }
    LinkedHashMap<String, String> getAttributes()
    {
        // returns entire map
    }
}

class ExplosionEvent inherits Event
{
    String getLocation() { return getAttribute("location"); }
    void setLocation(String location) { setAttribute("location", location); }

}

You could consider using the java.utils.Properties for your implementation.

Another solution might be to use reflection.

OwnerDisplayName: ChrisW


答:
They certainly can. Not everything that a team does is perfect or acceptable in any sense of the word.

Scrum masters should enable a culture of open communication, and scrum masters... are part of the team! So, why would they not point out problems with the team?

Some teams are excellent, self-organizing, industrious and effective. Some other teams are mediocre, incapable of organization, lazy or ineffective. Why wouldn't it be so?

That said, there's a big difference between having a blame culture and pointing out clear problems with the team so that they can be addressed.

Also, a scrum master is a facilitator, or helper, role, not a leader in any sense. So they have no particular right to literally reprimand people. They can certainly influence the team and point out problems or even calling out people if needs be.

In summary, this is what we want:

Open communication

One team which includes the scrum-master

When problems arise, they are clearly communicated and addressed

When people clearly misbehave, the bad attitude (never the person!) is addressed openly and fairly

People accepting responsibility

This is what we don't want:

People keeping secrets or cultivating resentment, while pretending to be happy in the team

Scrum master vs. team attitude

Finger pointing

Fear/blame culture

People ducking responsibility

As long as the SM is aiming for the former and avoids the latter, there is no problem is communicating negatively with the rest of the team.

Title: Can a scrum master reprimand his team?

Body:
Scrum master is a facilitator for the delivery team and acts as a bridge between Project Management and the team. In course of time if he realizes that his team is not delivering the deliverables perfectly possible w.r.t competency of his team, can he question his team members why it is not happening?

It is more like a show-cause notice to them. He knows why it is not happening eg:- spending time on social sites or wasting time on less important issues.

Is it okay for him to say "reprimand" the delivery team on their style of working? Or should it be escalated and left for the functional managers to deal with it?

Important thing to note is that usually in an Org, the scrum master is a good friend with his team and so it makes all the more awkward to react to such a situation.


问:
How do Text User Interfaces (TUI) work?
I have recently been assigned to port an old COBOL program. I am used to GUIs, and I can't understand how a TUI works. I searched a lot through Google but couldn't find something.

I knew that console applications could output line by line, but how are colors etc. drawn to the terminal screen? How all this stuff is being drawn?
Do terminals support it somehow? Is there a standard? I am really confused.

答:
Pretty sure your answer is going to vary based on platform here.  There are many different types of terminal/console and for many more than one standard for writing to it.  Most of them I have seen use some sort of escape sequence (ex: ANSI char escapes for dos, YMMV) where you send a special escape char to interrupt the writing to the screen then you can move the cursor, change colors, etc.

If you are writing something literally for dumb terminals then probably going to be using something like https://secure.wikimedia.org/wikipedia/en/wiki/Ncurses

Title: How do Text User Interfaces (TUI) work?


问:
shall a vector2 extends a vector3 or is it the opposite?
Perhaps the question might be tied to a theoritical or mathematical forum, but since it is for programming purpose, i ask here first:

In a computer vision context, i write a couple of interfaces intended to be the "read-only" part of vectors. So i define "IVector2R" and "IVector3R" that only contain getters. The question is:
does IVector2R extends IVector3R (and the "y getter" always returns 0), or is it the opposite: IVector3R extends IVector2R?

I would like a conception as close as possible to the mathematic/sets theory...

Thank you for your attention

答:
So finally, I simplify by only declaring a IMatrixR interface. I let the implementation doing more "optimized" stuff with specific classes such as Vector3 or Vector4, both implementing the IMatrixR interface.

But at a generic level, the UML diagram becomes a little bit more tricky to draw since there is more constraints to indicate and a set of exceptions (or error code to return) to specify on each methods; those implying conditions that i would rather automatically avoid by the type checking process during compilation.

As an example, the mul(IMatrixR,IMatrixR) method has to raise an exception when the dimensions are not compatible. But the overloading method mul(Matrix4,Vector4) will never throw it! Whereas the standard implementation of mul(IMatrixR,IMatrixR) does. The overloading method will be more efficient and does not require to be surrounded by try/catch...


问:
Detect Order Changes in a List
Let's say you have a list of values that are:

a

b

c

d

e

The order on the list might be changed.

a

c

d

b

e

How would you detect this change? We needed something like this when we were building a revision history page for our online form building tool. We found a quick and dirty solution, but I am looking for a more elegant solution for this. Here is what the revision descriptions look like:

Here is the tough part: Elements can be removed/added from/to anywhere on the list. So, the algorithm should be able to ignore those changes.

答:
Create a double linked list for records. In your example:

for the first list:

```<code>a: {prev: -1, next: b}
b: {prev: a, next: c}
c: {prev: b, next: d}
d: {prev: c, next: e}
e: {prev: d, next: -1}
</code>```

and for the second list

```<code>a: {prev: -1, next: c}
c: {prev: a, next: d}
d: {prev: c, next: b}
b: {prev: d, next: e}
e: {prev: b, next: -1}
</code>```

Now when you compare the both list only order change matters should be "b", because it's both previous and next value changed. Only previous or only next value modified records should not be taken into account since they slide because of order change of "b"

Title: Detect Order Changes in a List

Body:
Create a double linked list for records. In your example:

for the first list:

a: {prev: -1, next: b}
b: {prev: a, next: c}
c: {prev: b, next: d}
d: {prev: c, next: e}
e: {prev: d, next: -1}

and for the second list

a: {prev: -1, next: c}
c: {prev: a, next: d}
d: {prev: c, next: b}
b: {prev: d, next: e}
e: {prev: b, next: -1}

Now when you compare the both list only order change matters should be "b", because it's both previous and next value changed. Only previous or only next value modified records should not be taken into account since they slide because of order change of "b"