问:
Selecting the (right?) technology and environment
We are two developers on the edge of starting new web product development.

We are both fans of lean start-up approach and would like to practice continuous deployment.

Here comes the dilemma - we are both coming from a C# / Windows background and we need to decide between:

Stick to .NET and Windows, we will not waste time on learning new technologies and put all our effort in the development.

Switch to Ruby on Rails and Linux which has a good reputation of fast ramp up and vast open source support. The negative side is that we will need to put a lot of effort in learning Ruby, Rails and Linux...

What would you do? What other considerations should we take?

答:
If I were in your situation I would use technology that I'm best in. We had a similar situation in my company where the client requested java and we were all .net developers.

At the beginning everything was just fine, but later on some small things gave us such problems and at one point time frames were SciFi.

In my experience it is easy to learn new programming language and new technology, but to really know you need long time.


问:
How and when had the CC BY license become GNU GPL-compatible?
I believed that Creative Commons Attribution License, even being non-copyleft one, was always and still is incompatible with GNU GPL because of multiple minor issues; which, however, were gradually resolved from version to version: early versions of CC BY were hardly free at all; now, as far as I understand, the only unusual for a free software license clause of CC BY 4.0 is its key point: attribution requirements.

I know, that Creative Commons is now working together with the FSF on making current version of its copyleft license, CC BY-SA 4.0, compatible with GNU GPL. That is a formal process, somewhat similar to publishing a new license version; if it would succeed, there should be an announcement from CC, as it was when CC BY-SA 4.0 was declared mutually compatible with the Free Art License v1.3.

As far as I know, there was no such process for CC BY. However, firstly, a week ago, along with updating links from v2.0 of CC BY to v4.0, a statement about incompatibility of CC BY with GNU GPL and GNU FDL was removed by FSF Licensing & Compliance Manager Joshua Gay from a ‘Various Licenses’ list on www.gnu.org, which is used as authoritative source on GPL-compatibility; and secondly, two days ago an explicit note that “CC BY 4.0 is compatible with GPLv3” was added without any noticeable announcement or explanation, as if it is something obvious.

Is it indeed so obvious? Fourth generation of CC license zoo is about one year old, why only now? And how shall I consider attribution obligations when incorporating a work under CC BY into a work under GPLv3? I guess, as additional requirements under section 7b of the GNU GPLv3:

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

  <...>

  b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it...

These were rhetorical questions though. Now the actual question.

I do not understand very well how transitive CC licenses (since second generation) are: are previous versions of CC BY: 2.0, 2.5 and 3.0; indirectly compatible with GNU GPLv3 now?

答:
Joshua Gay's edit looks sloppy at best: I found at least 2 clauses and a section in http://creativecommons.org/licenses/by/4.0/legalcode that look incompatible with any GPL.
I've written a letter to the FSF asking them to clarify this matter and the properties of the edit.

This is what I just got in reply, from none other than Joshua himself (nested blocks are his quotes from my letter):

Hello,

  Thank you for writing.

It doesn't mark the license as "compatible with the GNU GPL or FDL"
    with the left-side line.

The color doesn't specify a version number of the GPL. I have been
  waiting for confirmation from our general counsel that CC BY is
  incompatible with GPLv2 and the FDL before updating the color on the
  left hand side. Hopefully that will be soon.

It doesn't comment on this decision as if it's something obvious.
    Which it is not:

The http://creativecommons.org/licenses/by/4.0/legalcode#s3a3
    restriction looks drastically incompatible

First note that both licenses make use of words like reasonable and
  within reason. Interpretation should be done with that in mind. Here is
  our position on this as I understand it. You are right that we should
  have a more formal statement and I will try to get one prepared that
  we publish on the site.

GPLv3 7(b) states that you can add terms "Requiring preservation of
  specified reasonable legal notices or author attributions in that
  material or in the Appropriate Legal Notices displayed by works
  containing it;"

The FSF interprets this as to include a licensor doing something such
  as removing certain parts of the reasonable legal notices or marking
  them in ways as different from the original.

http://creativecommons.org/licenses/by/4.0/legalcode#s4 grants a
    set of rights whose relation to those granted by the GPLv3 is very unclear

How are they unclear? I do not see what is unclear.

http://creativecommons.org/licenses/by/4.0/legalcode#s2a5B
    appears to forbid relicensing which is a requirement for GPLv3 compatibility as per
    http://www.gnu.org/licenses/gpl-faq.html#WhatDoesCompatMean

A person does not need to relicense a work to create a combined work
  with the GPL. A CC BY licensed work that is incorporated into a GPL
  licensed work would retain a copy of the CC BY license and all CC BY
  notices. One would simply add to the work as a whole and in relevant
  plces notices about the GPL and a copy of the GPL.

CC BY does not restrict adding additional terms so long as those
  additional terms do not restrict "exercise of the Licensed Rights by
  any recipient of the Licensed Material."

I will see about adding these clarifications somewhere.

  Thanks again for emailing us.

Joshua Gay

  Licensing & Compliance Manager

  Free Software Foundation

This is the reply I got on further clarification of CC#s3a3. He believes it's compatible by doing a narrow interpretation:

The incompatibility as it appears to me is that GPL gives no right to
    change any terms
    for a licensee who has already received a license (or receives it from
    an older copy) -
    since a license is irrevocable and is granted on the terms that
    accompany a specific copy.

So, your interpretation of this CC clause is that it only applies
    to the moment one receives a copy from the copyright holder, not to
    any later moment
    or receiving it from any other party?

That is my current understanding. Do I have a reason to think it would
  mean at a later date? I assumed such a request would need to be made
  alongside the license itself. I will ask Creative Commons what their
  interpretation is.

I am not a lawyer and I have no ideas how courts would interpret this.
  But, I'm not sure how one could reasonable expect a work to be put
  into the wild, modified and remixed for a period of 75 or 80 years and
  then it be reasonable that a licensor could come along and ask for all
  of those notices to be removed.

And here's the final update, right from the horse's mouth. The "reference removal"
CC clause is an obstacle. But as of now, Joshua doesn't consider it a strong enough one
to condemn CC-BY as incompatible. (diff to the current licenses.html as of this writing)

I suspect the clause does have such a use in mind. Its intended use
    appears to be the case where a copyright holder sees their work used
    in
    a context that they deem inappropriate - so they wish any reference to
    them
    removed so that their perceived reputation doesn't suffer.

Creative Commons sent me a clarification and it is the case that the
  intent of the license is so that a user could ask after the fact.
  However, they explained that "to the extent reasonably practicable" gives a person a lot of flexibility in being able to simply deny the
  request of the original licensor. I am interested in finding out some
  other legal opinions on how strong the language "to the extent
  reasonably practicable". Like how easy it is to make that argument as
  a licensee. I believe this is will be the next question in the public
  discussion mailing list. I will also open up an internal discussion at
  the FSF and with our lawyers to make sure they think the language
  "reasonably practicable" is sufficiently strong.

Why did he make the edit when he did? Perhaps because that's when he checked the compatibility. He actively participates in the CC-BY-SA - GPLv3 compatibility effort - that could very well be the reason that drew his attention to that matter.

The "transitive" compatibility of the earlier versions of the CC-BY has already been well explained by apsillers:

Earlier licenses are incompatible on their own but are compatible if the work's license allows relicensing to a compatible version. As you can see, this is a general principle not specific to a license.

ContentLicense: CC BY-SA 3.0


问:
What's the proper name for the type of security where we secure resources by ownerrship?
I work on a REST API that mixes two types of security:

First you have standard role-based security - so we have multiple roles such as administrator, read-only user, super user user, etc.

Then we also have most of those users belonging to certain customers, so we need to secure specific resources (and child resources) based on user customer / owner.

Is there a well-accepted name for this second type of security? The reason I am asking is that I want to find what patterns exist out there to working with the mix of the two - and it is hard to search for it if you do not know proper term for it.

答:
If an owner can grant access to other users, then it is called Discretionary Access Control (DAC):

discretionary access control (DAC) is a type of access control defined <...> "as a means of restricting access to objects based on the identity of subjects and/or groups to which they belong. <...> The term DAC is commonly used in contexts that assume that every object has an owner that controls the permissions to access the object

This is a model used in unix-like OSs, where each file/directory has rights for owner, group and other users - see chmod.

Otherwise, if an owner just has a fixed set of permissions assigned by someone else (administrator), then I think it's just an ACL-based model, where subject is not a concrete user, but just an abstract "owner". You can think of it as an access rule where subject (user) is checked by a condition which is not like user.name == 'Alice', but like user == object.owner. That way, it's just an ACL with custom "matching" rules.

I might be wrong here, so please check the list of access control models.


问:
Why are there no java compiler alternatives to allow new functionality?
For example, a new java compiler could allow for some breaking backwards compatibility to allow for things like overloading on generic types like:

```<code>void foo(List<String> arr);
void foo(List<Integer> arr);
</code>```

Or to allow things like generics over primitive types

```<code>void foo(List<int> arr);
</code>```

Now I am not suggesting these are trivial changes, or that everyone would even use such a compiler, but I was curious why I could not find ANY alternatives to javac. Even if you never modified the bytecode spec, some of these changes (and others) could be implemented purely at compile time. If nothing else, it could allow a nice testbed to merge changes back to mainline in some fashion (I get that changing the semantics of the language means it is no longer "Java", but let's call it J++ or something).

I like Java's backwards compatibility first mentality, but I was surprised this is not an approach people have taken over completely new languages like Kotlin/Ceylon/etc.

Is there more going on here that prevents this from happening?

答:
I would add to P.T. answer above. Scala as a functional programming language which compiles to Java bytcode (so uses JVM) allows some fancy FP footwork but either way the answer resolves to a hack. here is a link to a previous asked similar question for Scala:

https://stackoverflow.com/questions/4982552/scala-method-overloading-over-generic-types

I would be hesitant to suggest Java 8 may be able to provide a similar hack given functions are now treated as first class citizens and can be passed around as arguments much like Scala.


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答: Implicit type conversions when the types being converted between have no obvious relationship. For example, converting a random, non-numerical string into an int, like in PHP.

ContentLicense: CC BY-SA 2.5


问:
Concurrent collections, should read methods allow multiple threads at one time?
I have custom collection and I want to add wrapper to allow concurrent access.

```<code>public class MyConcurrentCollection<T>
{
    private MyCollection _collection; // passed in constructor

    public void Add(T item)
    {
        //modifies and may temporarily "break" the collection while executing this method
    }

    public bool Contains(T item)
    {
        //only reads
    }

    // other read and write methods
}
</code>```

At this moment, I have object private member that acts as lock in every method, allowing only one thread at a time to access the collection, so every method looks like this:

```<code>public bool Contains(T item)
{
    lock(_lock)
    {
        return _collection.Contains(item);
    }
}
</code>```

However this seems really inefficient. Since Contains() only reads from the collection, should I allow multiple threads into it?

Of course, I need to lock access to Add() and other methods while there are threads in Contains() and I need to block access to Contains() if there is a thread wishing to modify the collection.

Is there any disadvantage of allowing multiple threads into read only methods, or should I stick with my basic solution?

答:
It is inefficient but it is necessary - what happens if you read from the collection while someone else is adding a new entry but, in the way of threading, hasn't quite finished writing the new entry's data?

There are ways to make it more efficient, particularly using a read-write lock, which locks the entire collection to both readers and writers if someone is writing, but allows multiple readers access (ie a read lock prevents a writer - the writer has to wait until you're done reading, but does not block other readers).

Incidentally, using an object as a lock is not considered best practice. Use a dedicated lock construct. I remember reading somewhere the CLR team wish they'd never allowed such use.


问:
Where is asp mvc model data stored?
I am using ViewModel classes in order to structure data being populated inside of a controller.

My questions is now where exactly is data of a @model stored after being populated via asp mvc controller.

答:
In MVC, the model (that is an instance of a model class) is nothing more than an ordinary object. It is initialized by the controller which passes it to MVC's engine which, in turn, uses it when generating the final result from a view.

If you're asking whether it is stored on the stack or on the heap, the response is: on the heap.

Instance variables for a reference type are always on the heap.

(Source; see also: What and where are the stack and heap?)

If you're asking whether it is stored in memory or on a hard disk, the response is: it depends. In general, it will be in memory, unless the operating system runs out of memory and decides to move it to the pagefile (chances for this to happen are slim).

If you're asking how should you access the model once initialized (i.e. where to find the instance of the model class), just keep a reference to it within the controller itself.

Title: Where is asp mvc model data stored?


问:
DDD - Aggregate root with large number of children
I'll preface this question by saying I am relatively new to DDD so I may be making some fundamental mistakes here!

I working on a project which involves the concepts of Accounts and Transactions (in the financial sense). An Account can have many Transactions entered against it.

It seems to me that Account and Transaction are both Entities, and that Account is an Aggregate root containing Transactions since a Transaction cannot exist without the Account.

However when I come to apply this in code I immediately hit a problem. In many situations it's not especially useful for me to have a list of every Transaction in an Account at all times. I am interested in being able to do things like calculating Account balance and enforcing invariants such as a credit limit, but I also want to be able to easily work with a subset of Transactions (eg displaying those which fall within a date range).

In the latter case, if I was using a TransactionRepository I could efficiently access just those objects I need without loading the whole (potentially very large) list. However this would allow things other than the Account to work with Transactions which means I have broken the concept of Account as aggregate root.

How do people handle this kind of situation? Do you just accept the memory and performance implications of loading a potentially huge number of children for an aggregate root?

答:
I'd recommend being careful with the "can't exist without" rule. This talks to the concept of composition in UML/OO design and may have been one of the prescribed approaches to designing Aggregates in the original DDD blue book (not sure about that) but has largely been revised since. It might be a better idea to see your aggregates from a transactional consistency boundary perspective.

The idea is to neither make your aggregates too large, where you would have performance problems such as the one you point out, nor too small, because some invariants would inevitably span multiple aggregates - causing aggregate locking and concurrency problems.

The right aggregate size would ideally match the contours of what you modify in a given business transaction, no more and no less. In your example, if there are not many domain invariants that span over multiple financial transactions, making Transaction an Aggregate Root in its own right might well be the best solution.


问:
Comparing path strings against list of rules
I am trying to find a way to enhance a filtering algorithm. I am developing a backup software that enables users to specify custom filters to exclude unwanted files/directories.
Currently when trying to check if a file should be taken into backup, the path of the file is compared against a list of rules.

Each rule is specific to a single path (file or directory) and the path of the file is compared in a way similar to this:

Lets assume this is our rule structure

```<code>[Rule]
Path = "C:\Windows\"
Exclude = TRUE
</code>```

And I compare the file path I got with the rule path by the length of the rule path.

Now, this works fine and I haven't had an issue with it but my issue is that I do not have a limit on the number of rules a user can add to the system. He can add as many rules as he likes and here is my problem.

The more rules a user adds means more iterations for each file against the rules set.

What is a good practice to do such thing?

答:
One way to improve this is to build a tree structure out of the path components.

So if he adds c:\Windows\system32 and c:\Windows\temp and your input path is c:\users\serpent then you can happily skip both rules with a single check.

As your rule set gets bigger, this approach can reduce the amount of checking considerably. Some collections can do this for you automatically (a c++ stl map for example), you add all your paths and the collection stores them in a tree structure based on the strings.

Edit:

imagine you're looking for a taxi in the phone directory. Do you: start at the beginning and work your way through, comparing you input requirement of a taxi against the aardvark trainers, then the abacus sellers, etc; or do you skip to the T section, then skip to the Taxi subsection and then look through the list of taxi companies?

This is the same principle - if you split your rule paths into their components, then an input directory that is (in our examples) not inside the Windows root directory can be skipped completely - there's no need to check against c:\Windows\temp because you've ruled out all c:\Windows\everything rules.


答:
You can do it without locks, but the cost is that your add method will be more expensive. If you have a lot more reads than writes then your add method can just create a new and updated MyCollection object:

```<code>public void Add(T item)
{
    MyCollection newCollection = new MyCollection();
    newCollection.Append(_collection); // fill with old values
    newCollection.Add(item); // add the new item
    _collection = newCollection; // switch the internal pointer to the new object
}
</code>```

This works because threads accessing the read method only ever see the old or the new object, so your collection is never in an in-between state for other threads. If you have more than one writer thread you must of course add a lock to the add method (but not to the read methods).

Despite all this, you should use collections from system.collections.concurrent if possible, because they are a lot less error-prone.

Title: Concurrent collections, should read methods allow multiple threads at one time?

Body:
I have custom collection and I want to add wrapper to allow concurrent access.

```<code>public class MyConcurrentCollection<T>
{
    private MyCollection _collection; // passed in constructor

    public void Add(T item)
    {
        //modifies and may temporarily "break" the collection while executing this method
    }

    public bool Contains(T item)
    {
        //only reads
    }

    // other read and write methods
}
</code>```

At this moment, I have object private member that acts as lock in every method, allowing only one thread at a time to access the collection, so every method looks like this:

```<code>public bool Contains(T item)
{
    lock(_lock)
    {
        return _collection.Contains(item);
    }
}
</code>```

However this seems really inefficient. Since Contains() only reads from the collection, should I allow multiple threads into it?

Of course, I need to lock access to Add() and other methods while there are threads in Contains() and I need to block access to Contains() if there is a thread wishing to modify the collection.

Is there any disadvantage of allowing multiple threads into read only methods, or should I stick with my basic solution?

Body:
You can do it without locks, but the cost is that your add method will be more expensive. If you have a lot more reads than writes then your add method can just create a new and updated MyCollection object:

public void Add(T item)
{
    MyCollection newCollection = new MyCollection();
    newCollection.Append(_collection); // fill with old values
    newCollection.Add(item); // add the new item
    _collection = newCollection; // switch the internal pointer to the new object
}

This works because threads accessing the read method only ever see the old or the new object, so your collection is never in an in-between state for other threads. If you have more than one writer thread you must of course add a lock to the add method (but not to the read methods).

Despite all this, you should use collections from system.collections.concurrent if possible, because they are a lot less error-prone.


问:
Confused about ASP.NET Ajax, jQuery and JavaScript
Yesterday, I read couple of chapters on ASP.NET Ajax and jQuery from my ASP.NET 4 book and I found those frameworks pretty interesting and decide to learn more about them.

Today, I borrowed some books from library on Ajax and JavaScript. It seems ASP.NET Ajax is different from Ajax and jQuery seems like the "new" JavaScript.

Does it mean that I can skip JavaScript and learn jQuery directly?

On the other hand, the non-ASP.NET Ajax book I borrowed seems to apply to the client side web programming only and looks quite different from what I learned from ASP.NET Ajax. If I'm an ASP.NET developer, I guess I should stick with ASP.NET Ajax instead of client side Ajax right? What about PHP? Is there a "PHP Ajax" similar to ASP.NET Ajax?

It's not that I'm lazy to learn other tools, but I just want to focus on the right ones.

答:
No, there is no PHP AJAX.

If you have to do client development learn first pure javascript. Then learn jQuery. If you start with just jQuery you will miss important javascript concepts and you will be basically doing cut&paste programming.

JavaScript and jQuery are the universal and standardized tools that can be used almost in any HTML development. PHP programmers use js+jq when doing client things, Ruby programmers use js+jq etc.

Now, as far as I know, ASP.NET AJAX is even a higher level JavScript framework that is suited to work with ASP.NET, because ASP.NET, as you probably know, is itself a pretty hight abstraction from HTML. That's why they have a specific JS things. Basically it's ment to  play well with the server-side ASP.NET components and enhance them. Also, ASP.NET AJAX started in times where it wasn't that clear that jQuery will be defacto-standard. Or, it was clear, but not to Microsoft ;-) - they actually planned to create their own middle-level JS library (like jQuery is).

Honestly, I'm not a Microsoft guy and I would definitely stick to pure JavaScript + jQuery for as long as I could - if your employer/project does not exactly require ASP.NET AJAX. It will give you the most universally recognized knowledge of client-side programming.

OwnerDisplayName: Michal Till


问:
Algorithm Space and Time Complexity with Consideration for I/O (eg cache)
Is there an expression of performance for an algorithm or data structure that attempts to consider cache and other hardware concerns?

Context: in my class we're looking at binary trees and it seems like it would be extremely difficult to optimize data retrieval with the structure.  I know B-Trees address this problem, but I haven't seen a formal analysis of how much speed is improved considering some amount of cache.

答:
What kind of formal analysis do you mean?
If you look at Big O notation, the complexity does not change when you change a constant factor. What I mean is: a cache may be faster than RAM, but that does not change your complexity from O(n) to O(log n).

I think the problem is that things like cache optimization are so much dependent on the specific hardware that a formal analysis is not really useful.


问:
Tracing an object
Suppose I want an object with a list of strings and every method that this object gets passed to adds its name to the list of strings. Basically it's a stack trace, except unlike a stack trace it keeps a record of everywhere it's previously been.

In order to do this, I would have to put code in every method it goes through to add itself but if it went through methods that didn't know to add themselves then of course it wouldn't have a record of having been through those methods.

It would be cool if it were possible to make an object self aware, so to speak, of the methods it goes through but I don't think it is. But I'm wondering if there is any other way to get a record of all methods the object goes through, including those methods that don't know to update the object?

EDIT: Currently, I'm thinking the closest you could come to solving this would be to make any property/method that's accessed on the object update itself at that point in time. of course this wouldn't catch places that it simply passes through without being accessed.

答:
I would investigate non-coding solutions first:

ReSharper - Find Usages

Visual Studio Ultimate - Map Dependencies

Title: Tracing an object


问:
How to structure GUI program with a database
I am fairly experienced with web design and programming, C, C++ and a little java (used it to build some small GUI).

I am trying to work with Python, and I am faced with some technical structuring issues.

Here is a description of what I want to do

1. I want to build a standalone application that will be deployed in a company with several computers connected over a local network.

2. The application is to communicate with a database. (One database shared by applications in all computers)

3. Only one of the computers will have the database installed (more like client server relationship in web)

So here is my question

1. Can the application be written in such a way that when it is installed on a new computer, it installs the database(mysql or sqlite etc) without the need to first install database?

2. And is it possible that the content of the database can only be seen by the application?

3. I am a little bit not sure if the structure as described above is the best way to go. Please advice me on this.

I would be glad if pointed to a literature online on structuring standalone applications.

Thank you for the help

答:
```<code>... when it is installed on a new computer, it installs the database
(mysql or sqlite etc) without the need to first install database?
</code>```

Yes, but I would suggest, don't.

Install the database separately (and only once) on a known machine.
Then provide the name/ I.P.Address of that machine when installing all of the client applications.

If you don't do this, then you run the risk of having the database created on the boss' laptop and he's out of the office most of the time!

```<code>... is it possible that the content of the database can only be seen by the application?
</code>```

Yes, up to a point.

You can set up the database security so that the application uses a pre-defined account and credentials that the Users are never told about.  If you want users to have "accounts" within the database, then set these up using your own tables, not as actual database accounts.  It just makes everything easier - database permissions are only given to the "application" account, not to individual users, which means there's zero overhead of managing all those user accounts and, if you want these users to have passwords, then you always have a working password-reset mechanism (how's that going to work if a user can't connect to the database to reset their password because they've forgotten their password?).

But, as always, security is only "so good"; anything that can be built can be broken.

All that said, many client applications with a single, central database is definitely the way to go.

Body:
... when it is installed on a new computer, it installs the database
(mysql or sqlite etc) without the need to first install database?

Yes, but I would suggest, don't.

Install the database separately (and only once) on a known machine.
Then provide the name/ I.P.Address of that machine when installing all of the client applications.

If you don't do this, then you run the risk of having the database created on the boss' laptop and he's out of the office most of the time!

... is it possible that the content of the database can only be seen by the application?

Yes, up to a point.

You can set up the database security so that the application uses a pre-defined account and credentials that the Users are never told about.  If you want users to have "accounts" within the database, then set these up using your own tables, not as actual database accounts.  It just makes everything easier - database permissions are only given to the "application" account, not to individual users, which means there's zero overhead of managing all those user accounts and, if you want these users to have passwords, then you always have a working password-reset mechanism (how's that going to work if a user can't connect to the database to reset their password because they've forgotten their password?).

But, as always, security is only "so good"; anything that can be built can be broken.

All that said, many client applications with a single, central database is definitely the way to go.


问:
Create the fields in class level then instantiate inside methods or create and instantiated inside methods
I'm a newbie in software development. Just wondering which code is better and why should I continue which pattern I should follow.

First Snippet:

```<code>Class TestClass
{
    private Object1 field = null;
    private Object2 field2 = null;

    public void TestMethod1()
    {
          field = new Object1();
          field2 = new Object2();
    }

    public void TestMethod2()
    {
          field = new Object1();
          field2 = new Object2();
    }
}
</code>```

As you can see, I created fields in Class level and instantiate them inside the method.

Second Snippet:

```<code>Class TestClass
{

    public void TestMethod1()
    {
          Object1 field = new Object1();
          Object2 field2 = new Object2();
    }

    public void TestMethod2()
    {
          Object1 field = new Object1();
          Object2 field2 = new Object2();
    }
}
</code>```

Here I created and instantiated the fields.

These fields are being used over and over in many methods in a class.

答:
If field and field2 need to persist outside of a particular method call, then they need to be defined at class level, outside of the methods.

Where they happen to get instantiated thereafter doesn't really matter (as long as all of your code accepts that they might not be initialised).

If field and field2 are only ever used inside a particular method, then define and initialise them inside that method.

Scope variables as "tightly" as you can to avoid side-effects and the Perils of Thread Un-Safety.


问:
How "Best" to capture State Transitions in a formal software requirements specification
Suppose you have a state transition diagram. What is the best way to "Formally" write requirement(s) that capture the state transitions depicted in the diagram.  Over the years I have used two approaches and both work, but each time I work with new people there seems to be disagreements on how best to "Formally" capture the state transitions. "Formally" capture is required because traceability matrices are used that map to "Test Cases" and "Software Units (ie. Classes and/or Modules)".

Method 1

The system shall transition between states as depicted in Figure 1 XYZ Transition Diagram.

OR

Method 2

Look at the diagram and write a requirement for each transition.

Upon power up the system shall start in the Comms-Init State.

Upon establishing communications the system shall transition to the Initialization State.

(ie. A requirement for each state transition)

The benefit to method 1 is that it is one requirement and very easy to write.

The con to method 1 is that pictures don't work well with traceability matrices and it is more difficult to verify that you've covered all the transitions.

The benefit to method 2 is that each transition can be mapped to the explicit test cases and modules in their respective traceability matrices.

The con is that it is more work writing all the extra requirements and sometimes putting into clear and accurate words what the picture clearly shows is not as easy as it sounds. Also, the additional requirements seem to add more clutter as opposed to value, which makes reading the requirements less understandable rather than more.

While I suspect the answer in the simple case like I described is that it depends on the project or it doesn't really matter. The issue on my new project is that things are slightly more complicated (there are modes in addition to states that interplay). Thus, method 2 will potentially explode into a lot of requirements.

So I am asking the question because this is one of those "practices" that I have been doing without really knowing "Why".  I don't generally like to work that way, so I am hoping that someone can point out valid reasons why one approach is "more proper" than the other and in the process I will learn the "Why", which will let me understand how best to tailor for the slightly more complicated scenarios.

答:
I think the best approach to this would be to first provide a unique identifier to your state transition diagram. This will allow it to be referenced in downstream work. It would also allow your specific requirements to be explicitly linked to the figure, providing traceability between a visual model and a textual requirement, even if they live in the same document.

When you're creating textual requirements from the diagram, don't just translate the diagram to lines of text. In Visual Models for Software Requirements, the authors suggest asking four questions to derive requirements from a State Table or State Diagram:

What conditions are required for the transition to occur?

What action initiated the transition?

What is the output of the transition?

What actions or data transformations occur as a result of the transition?

The above diagram comes from the Seilevel website. The leadership of this company, Joy Beatty and Anthony Chen, wrote the book I linked to above. This example also appears in Chapter 23 of the book.

From a diagram like this, you can derive some functional requirements. For example, you know that your system shall accept a property address. There could be a data dictionary that describes that address's format that you can reference. I suspect that there would be some defined interface for the electronic transmission of an application. You could also reference an Interface Requirements Document or Interface Control Document that specifies the formats for inputs and outputs, if one exists. You can derive some roles and responsibilities from this diagram as well, that could go into a Roles and Responsibilities Matrix that can be created to say who can deny a submitted application. There could be business rules related to the application processing that can be functional requirements. If there is automated processing, you can derive non-functional requirements for the processing state, such as time.

Your "shall" statements would not just be an enumeration of this diagram. They wouldn't be things like "the system shall start in a prequalified state" and "the system shall transition to a submitted state when the property address is entered". Instead, you would use this as a tool to clearly see business rules and functional/non-functional requirements. It would especially highlight the requirements that are missing - what if you don't have a definition of who can perform the state transition from submitted to denied?


问:
Implement multiple separate interfaces or interface hierarchy
I've been refactoring one of my projects recently and ran into a decision I have to make.

I have several interfaces:

Entity: Something in the game world

Actor: An Entity that can perform actions

Character: An Actor that has a name (as well as some other features I haven't determined yet

Player: A Character that is played by a human being.

The type hierarchy is currently

```<code>public interface Entity { }
public interface Actor extends Entity { }
public interface Character extends Actor { }
public interface Player extends Character { }
</code>```

The reason I have it designed this way is because a big portion of functionality will come from community-driven mods that add functionality to the game, and I want it to be as modular as possible.

Now, the decision I ran into is: Should I keep this type hierarchy, or, to allow for more robust design (possibly, I can't think of an example), implement each individually?

The current implementation details are

```<code>public class BaseEntity implements Entity { }
public class BaseActor extends BaseEntity implements Actor { }
public class BaseCharacter extends BaseActor implements Character { }
public class BasePlayer extends BaseCharacter implements Player { }
</code>```

My question is, would there be any benefit (from a design perspective) of doing something like this instead

```<code>public interface Entity { }
public interface Actor { }
public interface Character { }
public interface Player { }

public class BaseEntity implements Entity { }
public class BaseActor implements Entity, Actor { }
public class BaseCharacter implements Entity, Actor, Character { }
public class BasePlayer implements Entity, Actor, Character, Player { }
</code>```

I can't think of a good reason to do this, but someone who would use my API to make their own mod may have their own

```<code>public class FooPlayer implements Player, Foo { }
</code>```

And not want/care about the methods defined in Entity, Actor, or Character.

答:
I would go for another approach:

Interfaces are meant to share behaviour accross otherwise independent or different objects. E.g. if you have an Interface called swim it could be implemented by humans or by ducks. Ducks and humans have not that much in common, but: the could swim; and if you look at how humans and ducks do it - they use a different approach, or implementation. So if you are dealing with humans and ducks it makes totally sense to use an interface. This is called the strategy pattern.

If you want to express, that the subjects of some behaviour have something in common, you could use class(ical) inheritance or as the books say an: »is a«-relationship.

So far the theory.

Looking at what you posted, you have several interfaces:

```<code>public interface Entity { }
public interface Actor extends Entity { }
public interface Character extends Actor { }
public interface Player extends Character { }
</code>```

Entity: Something in the game world

Actor: An Entity that can perform actions

Character: An Actor that has a name (as well as some other features I haven't determined yet

Player: A Character that is played by a human being.

Your classes are BaseEntity, BaseActor, BaseCharacter,BasePlayer.

You are mirroring your class definitions in the interface definitions.
Here, you are saying something like the following:
»An Entity is, what has entity-behaviour«
Only to some extend, that does make sense. That is, what I expect from an entity.

Based, from what I said, that different objects share behaviour via interfaces, your decision seems at best undecided:

1) If you choose to use a hierarchical approach via inheritance (is-a), there is no need to back up every class with an interface. You have similar objects (an actor is an entity with some extras, a character is in principle an actor with some extras). If you need specification, you typically subclass.

2) Or you choose the "behaviour via interface"-approach, where you define behaviour (and perhaps groups of behaviour) but need no classhierarchy.

But not both.

Your second approach goes in that direction of (2).

public interface Entity { }

public interface Actor { }

public interface Character { }

public interface Player { }

public class BaseEntity implements Entity { }

public class BaseActor implements Entity, Actor { }

public class BaseCharacter implements Entity, Actor, Character { }

public class BasePlayer implements Entity, Actor, Character, Player { }

Better:

```<code>public interface Entity { }
public interface Actor extends Entity{ }
public interface Character extends Actor{ }
public interface Player extends Character{ }

public class EntityImpl implements Entity { }
public class ActorImpl implements Actor { }
public class CharacterImpl implements Character { }
public class PlayerImpl implements Player { }
</code>```

With this, you make the following points clear:

1) For each class, you strictly define the API ("interfaces as contracts"):
A »character« is some object, which behaves at least like a "Character"

2) Since Character extends Actor, you are saying, that characters in some respect behave like actors

3) If I want to design an entity with extras, I could do so in using the existing interface  and create a new class implementing it and adding new behaviour (perhaps via another interface). So the interfaces are reusable.

Of course, there is some drawback: Interfaces have to be implemented with each class (exception: default methods). But on the other hand, you see every method(_implementation) without walking up the inheritance-tree.

You could go either ways, class hierarchy or interface hierarchy. In terms of maintainability and flexibility, I would go for the second solution.

Body:
I would go for another approach:

Interfaces are meant to share behaviour accross otherwise independent or different objects. E.g. if you have an Interface called swim it could be implemented by humans or by ducks. Ducks and humans have not that much in common, but: the could swim; and if you look at how humans and ducks do it - they use a different approach, or implementation. So if you are dealing with humans and ducks it makes totally sense to use an interface. This is called the strategy pattern.

If you want to express, that the subjects of some behaviour have something in common, you could use class(ical) inheritance or as the books say an: »is a«-relationship.

So far the theory.

Looking at what you posted, you have several interfaces:

public interface Entity { }
public interface Actor extends Entity { }
public interface Character extends Actor { }
public interface Player extends Character { }

Entity: Something in the game world

Actor: An Entity that can perform actions

Character: An Actor that has a name (as well as some other features I haven't determined yet

Player: A Character that is played by a human being.

Your classes are BaseEntity, BaseActor, BaseCharacter,BasePlayer.

You are mirroring your class definitions in the interface definitions.
Here, you are saying something like the following:
»An Entity is, what has entity-behaviour«
Only to some extend, that does make sense. That is, what I expect from an entity.

Based, from what I said, that different objects share behaviour via interfaces, your decision seems at best undecided:

1) If you choose to use a hierarchical approach via inheritance (is-a), there is no need to back up every class with an interface. You have similar objects (an actor is an entity with some extras, a character is in principle an actor with some extras). If you need specification, you typically subclass.

2) Or you choose the "behaviour via interface"-approach, where you define behaviour (and perhaps groups of behaviour) but need no classhierarchy.

But not both.

Your second approach goes in that direction of (2).

public interface Entity { }

public interface Actor { }

public interface Character { }

public interface Player { }

public class BaseEntity implements Entity { }

public class BaseActor implements Entity, Actor { }

public class BaseCharacter implements Entity, Actor, Character { }

public class BasePlayer implements Entity, Actor, Character, Player { }

Better:

public interface Entity { }
public interface Actor extends Entity{ }
public interface Character extends Actor{ }
public interface Player extends Character{ }

public class EntityImpl implements Entity { }
public class ActorImpl implements Actor { }
public class CharacterImpl implements Character { }
public class PlayerImpl implements Player { }

With this, you make the following points clear:

1) For each class, you strictly define the API ("interfaces as contracts"):
A »character« is some object, which behaves at least like a "Character"

2) Since Character extends Actor, you are saying, that characters in some respect behave like actors

3) If I want to design an entity with extras, I could do so in using the existing interface  and create a new class implementing it and adding new behaviour (perhaps via another interface). So the interfaces are reusable.

Of course, there is some drawback: Interfaces have to be implemented with each class (exception: default methods). But on the other hand, you see every method(_implementation) without walking up the inheritance-tree.

You could go either ways, class hierarchy or interface hierarchy. In terms of maintainability and flexibility, I would go for the second solution.


问:
Is there a canonical book on Ruby on Rails?
I'm an experienced developer with .NET, and understand core computing concepts well (OOP, design patterns, etc) but would like to also learn rails.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on Ruby on Rails? What about that book makes it special?

答:
Once you've grasped the basics of creating web applications with Rails and are looking for further reading, I highly recommend you check out both the RSpec Book and The Well-Grounded Rubyist.

The former gives a great overview of behaviour-driven development with an eye to Rails, and is worth reading because the Ruby community has a strong emphasis on testing and most people are using the tools described in the RSpec book.

The latter is the best book out there for getting into a Ruby mindset and developing your knowledge of the language from 'the pretty guts behind Rails' to understanding both the guts and the ethos of the language, which approaches many things with a very different perspective from C# and similar languages.


问:
Can table of content be parsed using some formal grammar?
A table of content can look like:

```<code>Preface
Table of Content
Chapter 1 ...
1.1 ...
1.1.1 ...
1.1.2 ....
1.2 ...
Summary
Exercises
Chapter 2 ...
...
Appendix ...
A ...
A.1 ...
A.2 ...
B ...
References
Index
</code>```

Its logical structure is a tree of multiple levels:

```<code>Preface
Table of Content
Chapter 1 ...
    1.1 ...
        1.1.1 ...
        1.1.2 ....
    1.2 ...
    Summary
    Exercises
Chapter 2 ...
...
Appendix ...
    A ...
        A.1 ...
        A.2 ...
    B ...
References
Index
</code>```

I wonder if parsing a table of content into a tree is a parsing
problem according to some grammar (e.g. regular grammar,
context-free grammar, or some other grammars)?

If yes, how can we specify the grammar of a table of content?

Can your parsing method deal with ambiguous case e.g.

```<code>Preface
Table of Content
Chapter 1 ...
1.1 ...
1.1.1 ...
1.1.2 ....
1.2 ...
Summary
Exercises
Chapter 2 ...
2.1.1 ...
2.1.2 ...
Appendix ...
A ...
A.1 ...
A.2 ...
B ...
References
Index
</code>```

where 2.1.1 ... is a one level lower than Chapter 2 ..., while
1.1.1 ... is two levels lower than Chapter 1?

Thanks.

答:
This is neither complete nor tested, but it should give you the general idea.

```<code>start
  = outermost_line+

outermost_line
  = no_dot_word description? '\n' one_dot_line*

one_dot_line
  = one_dot_word description? '\n' two_dot_line* | two_dot_line

two_dot_line
  = two_dot_word description? '\n' three_dot_line* | three_dot_line
</code>```

The outermost_line contains any number of one_dot_lines within it.  The way you handle your skipping straight to two dot lines is the | two_dot_line that can pass through to the next layer.  Verifying that the chapter numbers match up with the section numbers I wouldn't do in the parser, but the next layer up.

Body:
This is neither complete nor tested, but it should give you the general idea.

start
  = outermost_line+

outermost_line
  = no_dot_word description? '\n' one_dot_line*

one_dot_line
  = one_dot_word description? '\n' two_dot_line* | two_dot_line

two_dot_line
  = two_dot_word description? '\n' three_dot_line* | three_dot_line

The outermost_line contains any number of one_dot_lines within it.  The way you handle your skipping straight to two dot lines is the | two_dot_line that can pass through to the next layer.  Verifying that the chapter numbers match up with the section numbers I wouldn't do in the parser, but the next layer up.


答:
It actually depends. I would only create a Class which contains instance attributes if more than one of its methods uses it.
On the other hand, if an attribute (or variable) is only used inside the method, then it should be defined local to the method it uses.

In the example you describe, I think that you are using functions instead of methods, which to me seems like they are independent between each method execution. (This comes from the "test" word).

If both objects instances you plan to use are the same, maybe define in the class level and instantiate both in the setup method.

Title: Create the fields in class level then instantiate inside methods or create and instantiated inside methods

Body:
I'm a newbie in software development. Just wondering which code is better and why should I continue which pattern I should follow.

First Snippet:

```<code>Class TestClass
{
    private Object1 field = null;
    private Object2 field2 = null;

    public void TestMethod1()
    {
          field = new Object1();
          field2 = new Object2();
    }

    public void TestMethod2()
    {
          field = new Object1();
          field2 = new Object2();
    }
}
</code>```

As you can see, I created fields in Class level and instantiate them inside the method.

Second Snippet:

```<code>Class TestClass
{

    public void TestMethod1()
    {
          Object1 field = new Object1();
          Object2 field2 = new Object2();
    }

    public void TestMethod2()
    {
          Object1 field = new Object1();
          Object2 field2 = new Object2();
    }
}
</code>```

Here I created and instantiated the fields.

These fields are being used over and over in many methods in a class.


答:
The decision to make an interface extend another should be based on the Liskov Substitution Principle. So Actor should only extend Entity if every program that's correct when given an Entity will also be correct when given an Actor. If it's not always the case that an Actor can implement everything an Entity should implement, then keep them separate. See also the Interface Segregation Principle.

If you decide to keep the interfaces separate, you'll need to use generics whenever your methods need an argument that implements multiple interfaces. E.g.

```<code>public <T extends Entity & Actor> void foo(T entityActor) {
    entityActor.someEntityMethod(); // OK
    entityActor.someActorMethod(); // Also OK
}
</code>```

The only cost here is the verbosity of the signature, but otherwise it's not any more difficult to implement or use:

```<code>BaseActor actor = getActorFromSomewhere();
foo(actor); // Just works
</code>```

In the case of seperate interfaces I would also recommend choosing composition and delegation over inheritance as illustrated in Thomas Junk's answer. Inheritance hierarchies are brittle and rigid; using composition and delegation it's easy to mix and match implementations of the different interfaces.

Title: Implement multiple separate interfaces or interface hierarchy

Body:
I've been refactoring one of my projects recently and ran into a decision I have to make.

I have several interfaces:

Entity: Something in the game world

Actor: An Entity that can perform actions

Character: An Actor that has a name (as well as some other features I haven't determined yet

Player: A Character that is played by a human being.

The type hierarchy is currently

```<code>public interface Entity { }
public interface Actor extends Entity { }
public interface Character extends Actor { }
public interface Player extends Character { }
</code>```

The reason I have it designed this way is because a big portion of functionality will come from community-driven mods that add functionality to the game, and I want it to be as modular as possible.

Now, the decision I ran into is: Should I keep this type hierarchy, or, to allow for more robust design (possibly, I can't think of an example), implement each individually?

The current implementation details are

```<code>public class BaseEntity implements Entity { }
public class BaseActor extends BaseEntity implements Actor { }
public class BaseCharacter extends BaseActor implements Character { }
public class BasePlayer extends BaseCharacter implements Player { }
</code>```

My question is, would there be any benefit (from a design perspective) of doing something like this instead

```<code>public interface Entity { }
public interface Actor { }
public interface Character { }
public interface Player { }

public class BaseEntity implements Entity { }
public class BaseActor implements Entity, Actor { }
public class BaseCharacter implements Entity, Actor, Character { }
public class BasePlayer implements Entity, Actor, Character, Player { }
</code>```

I can't think of a good reason to do this, but someone who would use my API to make their own mod may have their own

```<code>public class FooPlayer implements Player, Foo { }
</code>```

And not want/care about the methods defined in Entity, Actor, or Character.

Body:
The decision to make an interface extend another should be based on the Liskov Substitution Principle. So Actor should only extend Entity if every program that's correct when given an Entity will also be correct when given an Actor. If it's not always the case that an Actor can implement everything an Entity should implement, then keep them separate. See also the Interface Segregation Principle.

If you decide to keep the interfaces separate, you'll need to use generics whenever your methods need an argument that implements multiple interfaces. E.g.

public <T extends Entity & Actor> void foo(T entityActor) {
    entityActor.someEntityMethod(); // OK
    entityActor.someActorMethod(); // Also OK
}

The only cost here is the verbosity of the signature, but otherwise it's not any more difficult to implement or use:

BaseActor actor = getActorFromSomewhere();
foo(actor); // Just works

In the case of seperate interfaces I would also recommend choosing composition and delegation over inheritance as illustrated in Thomas Junk's answer. Inheritance hierarchies are brittle and rigid; using composition and delegation it's easy to mix and match implementations of the different interfaces.


问:
Generate random numbers with certain spikes?
I am trying to generate random numbers to simulate steering wheel angles and velocities of a car. So for steering wheels the random numbers could go like 1,2,4,6,4,3,40,0.
I can generate random numbers but the problem is it wouldnt make sense to have truly random numbers for steering angle data. So usually a driver only turns a few degrees unless there is a turn and somtimes he will not steer and the steering angle would be just zero. Can someone give me some advice regarding this?</p>

答:
As you've noted, random steering wheel angles don't make sense.

Instead, try random or semi-random inputs to the steering wheel instead.

For example:

Assume the wheel is straight.  You can randomly apply deltas (perhaps in the range of +/- 2 degrees) to the wheel position to simulate guiding the vehicle down a straight road.

You can introduce a bias to those deltas (say, +/- 2 degrees, plus another 0 - 5 degrees) to introduce a bend in the road.

You'll want to keep track of the absolute position of the steering wheel, especially if you're adding sharp corners (it's not possible to turn the wheel +90 degrees 20 times in a row).


问:
proper way to design REST interface with nginx lua.
I'm a noob at nginx and lua. But I'm trying to design a REST interface.

The plan is to create a location entry that will match URIs like this:

```<code>curl -i -X GET 'http://localhost/widgets/widget?name=testname&loc=20000' -H "Accept:application/json"
</code>```

OR

```<code>curl -i -X POST 'http://localhost/widgets/widget?name=testname&loc=20000&price=10.12' -H "Accept:application/json"
</code>```

I want to return data like this:

```<code>HTTP/1.1 201 Created
Server: nginx/1.6.2
Date: Wed, 25 Feb 2015 13:32:24 GMT
Content-Type: application/json; charset=utf-8

{"name":"testname","loc":"20000","price":"10.12","GET":"http:\/\/localhost\/widgets\/\/widget?name=testname&loc=20000"}
</code>```

What I've come up with so far:

Within the location block / context, I'm going to test what the request method is (GET vs. POST vs. DELETE) and then execute logic inside separate lua files to do all the CRUD operations.  So for example, notice the following quasi pseudo code:

```<code>  #curl -i -X GET 'http://localhost/widgets/widget?name=testname&loc=20000' -H "Accept:application/json"
    location /widgets/widget {
            default_type "text/pain";
            #ifisEvil... unless done inside lua
            content_by_lua '

                    if ngx.var.request_method == 'GET' then
                            add logic to call "read_widget.lua"
                            somehow save results from read_widget.lua in string
                            response.body = results_string
                            convert results_string to json format.
                            return results_string_as_json
                    elseif ngx.var.request_method = 'POST' then
                            add logic to call "create_widget.lua"
                            same logic as GET...
                    elseif ngx.var.request_method = 'DELETE' then
                            add logic to call "delete_widget.lua"
                            same logic as GET...
                    end
            ';
    }
</code>```

Questions

Is this the right approach to take? Specifically, is it possible to call methods in external files and return large amounts of data from them back in the nginx.conf file?

Even if it's possible, is it a good idea?  These external files will contain logic to connect to the datasource, massage the data and then prepare the correct HTTP response... like 201 for new resources, 404's etc etc.

Thanks everyone.

答:
Yes, it is a fair architecture - the concept of a web server taking requests and the passing the call on to another server to process is almost certainly best practice in all cases. At least theoretically you could then hosts your logic files on one or more application servers if load gets too great. Even if this doesn't apply to you right now, its still good to have the flexibility, especially if you end up reusing some of this code in the future.

However, write your 'business logic' files so they do not have any understanding of the http request, so they return normal error codes that are translated into something more http-y by the webserver side of things.

You might also like to see some helper code like lua-resty-rack


答:
You could create a list of discrete steering behaviors where each one has a set of wheel angles that are executed in succession:

Right Turn

Sharp left turn

straight with minor adjustments

avoid pot hole or other obstacle

veer off road (someone was texting and driving)

change lane

Then you can randomly select through this list. Each item could be weighted to occur more often depending on the type of driving you'd like to simulate: off-road, highway, inner city, country road, etc.

Title: Generate random numbers with certain spikes?

Body:
I am trying to generate random numbers to simulate steering wheel angles and velocities of a car. So for steering wheels the random numbers could go like 1,2,4,6,4,3,40,0.
I can generate random numbers but the problem is it wouldnt make sense to have truly random numbers for steering angle data. So usually a driver only turns a few degrees unless there is a turn and somtimes he will not steer and the steering angle would be just zero. Can someone give me some advice regarding this?</p>


问:
how often do we need to do appraisal for a developer?
I have this question since my friend told me that if we have frequent appraisal such as 4 months or 6 months once, people will be turned to a money minded.

But I am thinking this in another aspect like, people will be getting feedback and boost quickly than one year appraisal. We do not need to increase the salary much. But the token advancement would help them to get some refreshment.

答:
Formal Performance Evaluation should be separate from bi-weekly informal one-on-one and ad-hoc feedback.

Formal appraisal/performance review should be at most quarterly and this is usually where you are measured by some documented method against your Key Performance Indicators (KPI's) or objectives. The week before this happens, everyone is keen to be hero, either working late, fixing the nastiest/ugliest/hardest bugs, cleaning up mess that nobody wants to touch, etc and generally trying to look good in front of their line manager. When there's potential raises at stake, this will always happen. There are many studies of the best ways to motivate but the role of the individual will always need to be considered. Often the objectives are just used to steer away from bad/unhelpful behaviour and try to aim towards a new skill or responsibility that will be win-win for the company and the employee.

There should also be a regular one-on-one/one-to-one meeting which is an informal chat about what's been happening lately, how you feel about project, interaction with other team members, etc. This is the time to raise things like "I'm finding it hard to get through to Dave" where your line manager or team leader can give some insight into alternative approaches. This is best done for 10 to 15 minutes weekly (new hires) or bi-weekly (everyone else), but not less frequently as issues that come up will not be dealt with and either fester until Perf Eval time (bad) or not get addressed (also bad).

Isolated incidents where you upset/are-upset-by a colleague or do or say something that your team leader considers troublesome should be handled within 24 hours on an ad-hoc basis.

This may sound like a whole load of meetings, but they should be kept short and to-the-point, keeping their value in focus.


答:
You can map the values to a function that rises sharply at one end and then select from this.

I think this function might work well:

```<code>y = 1/(1.1 - x)
</code>```

If x is your randomly produced number and y is the value you use for steering.

Most of the time your values will be fairly small, but occasionally the output of the function will rise to very high value giving you the peaks you want.

Tweaking values of this function will allow you to get different results such as higher peaks or less likely peaks.

Body:
You can map the values to a function that rises sharply at one end and then select from this.

I think this function might work well:

y = 1/(1.1 - x)

If x is your randomly produced number and y is the value you use for steering.

Most of the time your values will be fairly small, but occasionally the output of the function will rise to very high value giving you the peaks you want.

Tweaking values of this function will allow you to get different results such as higher peaks or less likely peaks.


问:
Is there a name for a dictionary that returns the key as the value by default?
A dictionary that returns the key as the value by default can be used in cases where exceptions or translation is needed.

E.g. One could do

```<code>i18n = SpecialDict()

if spanish:
    i18n["Hello"] = "Hola"

print(i18n["Test"]) # prints Test
print(i18n["Hello"]) # prints Hola if spanish
</code>```

I18n is just an example, there are other (probably better) uses.

Is there a name for this dictionary / pattern?

Edit

Wow, I did not expect such a backsplash. Just to make it clear, this type of dictionary is not "defective" or "broken". It is a simple and elegant solution for a specific type of problem, and I have used this pattern with great success in my career. If you fail to see a usage for this then please move along to another question.

As for gnat's comment, I was not aware that questions like this are not welcome here. I'm sorry for that. I would delete my question but there is already an answer (which actually does not answer my question at all) so I'll just flag it for closure.

Edit 2

Since I have not found a name or usage of this, and this (sadly short-lived) question did not bring up anything either I hereby name this pattern

Data Aspect

and the dictionary-like object a

Data Aspect Map

I would love to post an answer to this question with a more detailed definition, description and maybe some examples and welcome feedback to this pattern, but I can't, since this question is on hold.

答: This doesn't sound like any Dictionary class I've heard of, but it could be trivially implemented by wrapping a dictionary in another class (or inheriting from it) and modifying the Get behavior.</p>


问:
What is the proper way for these methods to function?
How can I properly design what a method or function should do?

To clarify the question I am going to use an example from a simple (non GUI) hangman game I created. The design is simple, it has a HangmanGame class which has the word the user needs to guess and other such things as well as the methods that control the game. It also has a HangmanDriver class that controls the flow of the game and methods calls and such.

1 of the methods is to get the users guess and process it and it does this by calling 2 other private (helper) methods inside the class. The following is the code (after which is my actual quetion).

```<code>/**
 * This method gets and processes a users guess.
 */
public void getAndProcessGuess()
{
    this.processGuess(this.getGuess());
}

/**
 * Asks the user for their guess and validates that their
 * guess is legal and has not already been made.
 *
 * @return char The letter the user guessed
 */
private char getGuess()
{
    java.util.Scanner input = new java.util.Scanner(System.in);
    String guess = "";
    char letter = '\0';

    //get and validate the user input
    while (true)
    {
        System.out.print("Please enter your guess: ");
        try
        {
            guess = input.nextLine().toUpperCase();
        }
        catch (InputMismatchException e)
        {}

        System.out.println();

        if (guess.length() >= 1)
            letter = guess.charAt(0);

        if (!(guess.matches("[A-Z]{1}")))
            System.out.println("Please enter a single letter between A and Z\n");
        else if(isLetterGuessed((letter)))
            System.out.println("\nThat letter has already been guessed\n");
        else
            return letter;

        printSeparator(); //if the guess isn't valid print out a line separator
    }
}

/**
 * Processes the guess from user
 *
 * @param letter the letter the user guessed
 */
private void processGuess(char letter)
{

    if (secretWord.indexOf(letter) >= 0)
    {
        int count = secretWord.length() - secretWord.replaceAll(Character.toString(letter), "").length();
        System.out.println("The letter " + letter + " appears " + count + (count == 1 ? " time." : " times.") + "\n");
        setLetterAsGuessed(letter);
        printSecretWordWithGuessedLettersShown();
    }
    else
    {
        System.out.println("The letter " + letter + " does not appear in the hidden word\n");
        decrementNumOfGuessesLeft();
        System.out.println("You have " + numOfGuessesLeft + " incorrect guesses left\n");
    }

    printSeparator();

}
</code>```

What should be done inside each of these methods and whether they are doing too much?

The issue I have with the way it is now is that the methods print things out. It works in the current way the program works but it feels like these methods are doing more than they should and that perhaps the printing should be done by the Driver class not the instance of the class. Also if this were to ever be changed into a GUI the method wouldn't really make sense.. The issue with not having the method print out a line is that the validation would then also need to be done in the driver class.

The way I see it is there are three possible paths:

Inheritance

The Hangman game can be made into a superclass and it would then have 2 children one a HangmanConsoleGame and another HangmanGUIGame. This would solve the issue with how the methods function in each class (but the question still remains whether the methods should be printing things out).

Keep As Is

It works for how the game runs now. If any changes needed to be made or if the game will be changed to a GUI version the code can be refactored later so it works for the changes. This assumes that the methods doing the validation and printing things out is ok.

Refactor Now

Change the code now so that the validation is done within the Driver class and the methods simply return values with indications if the value is not valid. With the Driver class doing all the printing and the methods for getting the users guess only returning values it can then easily be changed into a GUI later on and minimizes what the methods are doing.

Which of these makes the most sense if any? Is there a better way to be doing this?

答:
It works in the current way the program works but it feels like these methods are doing more than they should

I agree, your methods do too much right now.

I would refactor now. If you extract code to classes, it will make your code more extensible, and also make it easier to find functionality. I would create a structure such as this:

```<code>interface Input {
    char getGuess(List<Character> guessedLetters) throws IllegalInputException;
}

interface Output {
    void reportIncorrectInput(String message);
    void reportWrongGuess(String message, char guess);
    void reportRightGuess(String message, char guess);
}

class IllegalInputException extends Exception {
    public IllegalInputException(String s) {
        super(s);
    }
}

class ConsoleInput implements Input {
    @Override
    public char getGuess(List<Character> guessedLetters) throws IllegalInputException {
        // get input. if input is illegal, throw:
        throw new IllegalInputException("message depending on error");
    }
}

class ConsoleOutput implements Output {
    // report (in this case, all methods just print to console)
}
</code>```

And then use the interfaces in your game controller. That way, you can easily exchange the concrete implementation against a different one (such as a gui).

OwnerDisplayName: yitzih

Body:
It works in the current way the program works but it feels like these methods are doing more than they should

I agree, your methods do too much right now.

I would refactor now. If you extract code to classes, it will make your code more extensible, and also make it easier to find functionality. I would create a structure such as this:

interface Input {
    char getGuess(List<Character> guessedLetters) throws IllegalInputException;
}

interface Output {
    void reportIncorrectInput(String message);
    void reportWrongGuess(String message, char guess);
    void reportRightGuess(String message, char guess);
}

class IllegalInputException extends Exception {
    public IllegalInputException(String s) {
        super(s);
    }
}

class ConsoleInput implements Input {
    @Override
    public char getGuess(List<Character> guessedLetters) throws IllegalInputException {
        // get input. if input is illegal, throw:
        throw new IllegalInputException("message depending on error");
    }
}

class ConsoleOutput implements Output {
    // report (in this case, all methods just print to console)
}

And then use the interfaces in your game controller. That way, you can easily exchange the concrete implementation against a different one (such as a gui).


答:
I think it depends on how modular you want your code to be. I learned to make your 'Driver/main' class as minimalistic as possible, put the hard work down as far as you can to make your code as reusable as possible. But it's really a matter of opinion. If you feel that rewriting chunks of your code will be beneficial, do it, but don't waste your time on something that will only give you a meager return.

There is probably always a better way, and absolutely always a different way to do something in code, it's just a matter of whether you think what you did serves its purpose.

If there is a good possibility of moving to a GUI based application, I would recommend doing the super/sub class idea you had mentioned. That would make it easer with plenty of overlap between code, so you don't have to write as much.

There's quite a few options that you could go with, it's just up to your personal preference.

Title: What is the proper way for these methods to function?

Body:
How can I properly design what a method or function should do?

To clarify the question I am going to use an example from a simple (non GUI) hangman game I created. The design is simple, it has a HangmanGame class which has the word the user needs to guess and other such things as well as the methods that control the game. It also has a HangmanDriver class that controls the flow of the game and methods calls and such.

1 of the methods is to get the users guess and process it and it does this by calling 2 other private (helper) methods inside the class. The following is the code (after which is my actual quetion).

```<code>/**
 * This method gets and processes a users guess.
 */
public void getAndProcessGuess()
{
    this.processGuess(this.getGuess());
}

/**
 * Asks the user for their guess and validates that their
 * guess is legal and has not already been made.
 *
 * @return char The letter the user guessed
 */
private char getGuess()
{
    java.util.Scanner input = new java.util.Scanner(System.in);
    String guess = "";
    char letter = '\0';

    //get and validate the user input
    while (true)
    {
        System.out.print("Please enter your guess: ");
        try
        {
            guess = input.nextLine().toUpperCase();
        }
        catch (InputMismatchException e)
        {}

        System.out.println();

        if (guess.length() >= 1)
            letter = guess.charAt(0);

        if (!(guess.matches("[A-Z]{1}")))
            System.out.println("Please enter a single letter between A and Z\n");
        else if(isLetterGuessed((letter)))
            System.out.println("\nThat letter has already been guessed\n");
        else
            return letter;

        printSeparator(); //if the guess isn't valid print out a line separator
    }
}

/**
 * Processes the guess from user
 *
 * @param letter the letter the user guessed
 */
private void processGuess(char letter)
{

    if (secretWord.indexOf(letter) >= 0)
    {
        int count = secretWord.length() - secretWord.replaceAll(Character.toString(letter), "").length();
        System.out.println("The letter " + letter + " appears " + count + (count == 1 ? " time." : " times.") + "\n");
        setLetterAsGuessed(letter);
        printSecretWordWithGuessedLettersShown();
    }
    else
    {
        System.out.println("The letter " + letter + " does not appear in the hidden word\n");
        decrementNumOfGuessesLeft();
        System.out.println("You have " + numOfGuessesLeft + " incorrect guesses left\n");
    }

    printSeparator();

}
</code>```

What should be done inside each of these methods and whether they are doing too much?

The issue I have with the way it is now is that the methods print things out. It works in the current way the program works but it feels like these methods are doing more than they should and that perhaps the printing should be done by the Driver class not the instance of the class. Also if this were to ever be changed into a GUI the method wouldn't really make sense.. The issue with not having the method print out a line is that the validation would then also need to be done in the driver class.

The way I see it is there are three possible paths:

Inheritance

The Hangman game can be made into a superclass and it would then have 2 children one a HangmanConsoleGame and another HangmanGUIGame. This would solve the issue with how the methods function in each class (but the question still remains whether the methods should be printing things out).

Keep As Is

It works for how the game runs now. If any changes needed to be made or if the game will be changed to a GUI version the code can be refactored later so it works for the changes. This assumes that the methods doing the validation and printing things out is ok.

Refactor Now

Change the code now so that the validation is done within the Driver class and the methods simply return values with indications if the value is not valid. With the Driver class doing all the printing and the methods for getting the users guess only returning values it can then easily be changed into a GUI later on and minimizes what the methods are doing.

Which of these makes the most sense if any? Is there a better way to be doing this?


答:
The main issue I have is that you are printing to console from all your methods. If possible, see if you could refactor your code to return significant results, and then print (or read) to/from console from 1 place, such as the driver.

This would come in handy should you want to make a GUI program, and now your logic will need to be rewired to handle actual windows and panels, and that might not be a fun ride. If you shield your logic from what means you are using to communicate with the user, rewiring it should be easier.

Secondly (my major concern) is that you are creating a new Scanner: java.util.Scanner input = new java.util.Scanner(System.in);, but you never actually release it, so your application has a leak.

Lastly, this: (!(guess.matches("[A-Z]{1}"))) will check if the string has at least one character (upper case). However, you are taking the first character of input, thus, something like so: 123t should pass the check but break your logic. Using something like: Char.isLetter(guess.charAt(0)) should work better, or else change your pattern to (!(guess.matches("^[A-Za-z]"))).


问:
Integrating QA within agile sprints
I've been working in "Agile" for a while and am working to move more towards agile at a new company. One of the problems I have always sort of encountered is effective integration of QA within the sprint.

We've done better at getting stories to QA earlier and shortening that feedback loop, but in the example of a 2-week sprint it was always inevitable that the last stories would get to QA late in the sprint, so QA would finish testing within the sprint but what does the developer do? They're done and have delivered all their stories, short of anything coming back from QA/UAT. How do we ensure they aren't just twiddling their thumbs for the last day-2 days of a sprint?

答:
Developers and QA should both work up until the end of the sprint.

Developers can spend the last day/few hours working on QA feedback, performing their own unit tests, reviewing or refactoring code, etc. assuming there is not enough time to pull in any stories from the backlog.

QA will of course spend the last time in the sprint testing, with any feedback at the end carrying over to the next sprint.

If there truly is nothing to do at the end of the sprint, people can take a well-deserved long lunch, maybe start gathering thoughts for the sprint retrospective, or high-level planning for the next sprint. Reviewing code (developers) and retesting (QA) never hurts either.

Title: Integrating QA within agile sprints


问:
How do you differentiate software between TEST and PROD environments?
We have a TEST and PROD environment. TEST and PROD are nearly identical, and obviously software first ends up in TEST before getting approved to go to PROD. Our software is primarily Windows Applications.

I'm wondering what the best way is to differentiate an application that is running in TEST vs one that is running in PROD. This would be a visual differentiation to the end user. My first thought would be version number, but then it seems like you'd be maintaining two sets of numbers.

答:
Anything that is a clear indication at all times (not just a splash screen, for instance) when running the application.  For WinForm applications, that could be appending "Test" onto the title bar where you have the application name.

Another common and more obvious indicator could be the use of colors.  A certain window color for production (that you want end-user UX friendly), but an obviously different window color for Test or other pre-prod environments.

The color trick is a common SQL DBA/developer practice.  Connecting to production SQL instances and your query window bar is red.  Non-prod and it is green.  It requires an extra layer of ignore to make a mistake.


答:
I recommend the online Rails Tutorial book.

I also have a copy of Ruby on Rails for Microsoft Developers and it's been pretty helpful in providing an overview of Rails, drawing parallels with ASP.NET, and giving a good introduction to web development in general.

Title: Is there a canonical book on Ruby on Rails?

Body:
I'm an experienced developer with .NET, and understand core computing concepts well (OOP, design patterns, etc) but would like to also learn rails.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on Ruby on Rails? What about that book makes it special?


答:
In layman's words

You have to separate business logic from presentation logic.

The game class (business logic) should not read input from console not from an HTML form.

The game class (business logic) should only communicate with the world via method calls.

A console app (presentation logic) should ask for input and make method calls to the game class, and output info to console

A web app (also presentation logic) should ask for input and make method calls to the game class, and output to HMTL

A graphic desktop app (yet another presentation logic) should ask for input (maybe a dialog box or mouse events) and make method calls to the game class, and output graphically in windows, dialog boxes, etc.

The game class is agnostic. It doesn't worship the console God, the web God or the desktop God.


问:
Distributing Libraries
How are libraries typically distributed?  Because they have to be compiled with the same compiler under the same settings as the project using it, distributing the .dll, .lib, etc. seems  impractical.  Is the source code just made available for download?

答:
As you noticed, distributing libraries is impractical...  You have to care about the version of the compiler (including Service Packs), the settings used to compile, etc.  We used to have 6 different ports for each version of Visual Studio: the most important difference was the Runtime Library used (/ST, /MT or /MD).

But unless you can distribute the source code, you'll have to live with this...

Title: Distributing Libraries


问:
When NOT to apply the Dependency Inversion Principle?
I am currently trying to figure out SOLID. So the Dependency Inversion Principle means that any two classes should communicate via interfaces, not directly. Example: If class A has a method, that expects a pointer to an object of type class B, then this method should actually expect an object of type abstract base class of B. This is helps for Open/Close as well.

Provided that I understood that correctly, my question would be is it a good practice to apply this to all class interactions or should I try to think in terms of layers?

The reason I am skeptical is because we are paying some price for following this principle. Say, I need to implement feature Z. After analysis, I conclude that feature Z consists of functionality A, B and C. I create a facade class Z, that, through interfaces, uses classes A, B and C. I begin coding the implementation and at some point I realize that task Z actually consists of functionality A, B and D. Now I need to scrap the C interface, the C class prototype and write separate D interface and class. Without interfaces, only the class would've needed to be replaced.

In other words, to change something, I need to change 1. the caller 2. the interface 3. the declaration 4. the implementation. In a python directly coupled implementation, I would need to change only the implementation.

答:
In layman's words:

Applying the DIP is both easy and fun. Not getting the design right at the first attempt is not enough reason giving up on the DIP altogether.

Usually IDEs help you do that kind of refactoring, some even allow you to extract the interface out of an already implemented class

It's almost impossible to get the design right the first time

The normal workflow involves changing and rethinking the interfaces in the first stages of developement

As development evolves it matures and you will have less reasons to modify the interfaces

In an advanced stage the interfaces (the design) will be mature and will hardly change

From that moment on, you begin to reap the benefits, since your app is open to scale up.

In the other hand, programming with interfaces and OOD can bring the joy back to the sometimes stale craft of programming.

Some people say it adds complexity but I think the opossite is true. Even for small projects. It makes testing/mocking easier. It makes your code to have fewer if any case statements or nested ifs. It reduces cyclomatic complexity and makes you think in fresh ways. It makes programming more alike to real-world design and manufacturing.


答:
If you're doing it right, the development load towards the end of the sprint should be lighter. If it's not working, development are flat out fixing bugs and trying to get stories closed.

Some options are:

Preparation for the next sprint. I like the team to have a good idea about what is likely to be in the next sprint and be thinking about the stories and likely tasks. That way sprint planning is not one big surprise to them.

Innovation days - pick a relevant topic, research and present on it. This can work if it's guided and can be a good chance to push the product forward and also give developers a chance to shine.

Developers execute test cases - teams are supposed to be cross-functional, right? If there's a QA bottleneck, why not have the whole team work to shift it?

Title: Integrating QA within agile sprints

Body:
I've been working in "Agile" for a while and am working to move more towards agile at a new company. One of the problems I have always sort of encountered is effective integration of QA within the sprint.

We've done better at getting stories to QA earlier and shortening that feedback loop, but in the example of a 2-week sprint it was always inevitable that the last stories would get to QA late in the sprint, so QA would finish testing within the sprint but what does the developer do? They're done and have delivered all their stories, short of anything coming back from QA/UAT. How do we ensure they aren't just twiddling their thumbs for the last day-2 days of a sprint?


答:
For the use case you've described, I think it's a valid pattern. However, there is no name for this, AFAIK.

In Java 8, there is a Map.getOrDefault method, which almost does that:

```<code>String greetingKey = "Hello";

Map<String, String> i18n = new HashMap<>();
i18n.put(greetingKey, "Hola");

String greeting = i18n.getOrDefault(greetingKey, greetingKey);
</code>```

Just using a key as default value - a bit more verbose than your version, if it was implemented as a class with overridden get method.

There is more general pattern to that: "if there is no value for a requested key, return result of some function applied to a key (and other data in a map/dictionary)" - in your case it's just an identity function applied to a key. Same pattern can be used for interpolation, for example.

It may be called "interpolated map", where in your case interpolation is degenerated to just use a key (argument) and no "neighbor points" (compare: linear interpolation uses two neighbors). Yet, I've never heard of such a thing being an object-oriented pattern. It is more of a functional design pattern, which just uses higher-order functions, hence no specific name needed.

EDIT: Your approach can be considered as flawed because there is an implicit contract on map/dictionary, which states: "if containsKey returns false, then get must return null" (opposite may not hold if null is a valid value).

There probably is some code which relies on this contract, and your implementation breaks it, hence it may cause runtime errors.

Title: Is there a name for a dictionary that returns the key as the value by default?

Body:
A dictionary that returns the key as the value by default can be used in cases where exceptions or translation is needed.

E.g. One could do

```<code>i18n = SpecialDict()

if spanish:
    i18n["Hello"] = "Hola"

print(i18n["Test"]) # prints Test
print(i18n["Hello"]) # prints Hola if spanish
</code>```

I18n is just an example, there are other (probably better) uses.

Is there a name for this dictionary / pattern?

Edit

Wow, I did not expect such a backsplash. Just to make it clear, this type of dictionary is not "defective" or "broken". It is a simple and elegant solution for a specific type of problem, and I have used this pattern with great success in my career. If you fail to see a usage for this then please move along to another question.

As for gnat's comment, I was not aware that questions like this are not welcome here. I'm sorry for that. I would delete my question but there is already an answer (which actually does not answer my question at all) so I'll just flag it for closure.

Edit 2

Since I have not found a name or usage of this, and this (sadly short-lived) question did not bring up anything either I hereby name this pattern

Data Aspect

and the dictionary-like object a

Data Aspect Map

I would love to post an answer to this question with a more detailed definition, description and maybe some examples and welcome feedback to this pattern, but I can't, since this question is on hold.

Body:
For the use case you've described, I think it's a valid pattern. However, there is no name for this, AFAIK.

In Java 8, there is a Map.getOrDefault method, which almost does that:

String greetingKey = "Hello";

Map<String, String> i18n = new HashMap<>();
i18n.put(greetingKey, "Hola");

String greeting = i18n.getOrDefault(greetingKey, greetingKey);

Just using a key as default value - a bit more verbose than your version, if it was implemented as a class with overridden get method.

There is more general pattern to that: "if there is no value for a requested key, return result of some function applied to a key (and other data in a map/dictionary)" - in your case it's just an identity function applied to a key. Same pattern can be used for interpolation, for example.

It may be called "interpolated map", where in your case interpolation is degenerated to just use a key (argument) and no "neighbor points" (compare: linear interpolation uses two neighbors). Yet, I've never heard of such a thing being an object-oriented pattern. It is more of a functional design pattern, which just uses higher-order functions, hence no specific name needed.

EDIT: Your approach can be considered as flawed because there is an implicit contract on map/dictionary, which states: "if containsKey returns false, then get must return null" (opposite may not hold if null is a valid value).

There probably is some code which relies on this contract, and your implementation breaks it, hence it may cause runtime errors.


问:
What is Quality Assurance's role in a company that practices Continuous Delivery?
I was listening to this podcast on Continuous Delivery and Jez Humble briefly talked about QA's role, but I didn't really get a "big picture" idea of they're doing on a day to day basis.  How is their job description changed when a company practices Continuous Delivery?</p>

答:
There are some things which a CI environment can't effectively check. Or things which are cost prohibitive to implement in a CI build process.

For example, I work with embedded systems which run on all manner of physical machines. It is incredibly difficult and frankly impossible to perfectly model the entire physical machine for all possibilities virtually.

The specific hardware combinations alone cause issues. The physical connections between different components may cause issues. Disk write speed on "virtual" systems vs the deployment system may change, resulting in different failures.

CI can do a great job on testing individual pieces of a large system to verify they work correctly. But writing a comprehensive "perfectly replicate your product in a CI test environment" simulator/emulator simply is not possible in some cases.

So a QA department can add a lot of value in situations like this.

If it's possible to develop a CI system to completely and comprehensively test all your processes, you may benefit from moving all your testing to CI and have a lower need of QA. But in many applications this is quite non-trivial.