问:
Can I use "user stories" for process improvement tasks?
We currently use JIRA to track our development work. My management wants to format and categorize everything as "User Stories," including non-software development related tasks. For example:

"As a test manager, can I perform testing of the application using only automated tests and no manual testing so that I can test the application as efficiently as possible?

Acceptance Criteria:
1. Convert 50 existing manual tests to fully automated tests
2. Tests must execute in less than 1 hour"

I want to get a sense from the community if it makes sense to use "user stories" for work that supports the software development process, is not done by the programmers, and does not directly results in deliverable code. Or should this be handled/classified differently (for example, in JIRA)?

Updated 6/7/2011 - Rephrased question to focus on "user story" term.

答:
The "chickens and pigs" comment misses the point. Internal stakeholders are chickens when it comes to the product being developed (unless it is being developed for them), but they are pigs when it comes to the development process.

The question you are asking is whether the sentence formula "As a , I would like to be able to _, so that I can __" would be useful for defining and improving business processes where the improvements do not require writing new software code. I came upon this thread because I am thinking about doing the same thing and am looking for best practice, but my strong intuition is that the answer to your question is "yes." The purpose of the sentence structure is really to force the writer to abstract away solutions that s/he might already have in mind and focus on what the user--in this case, the process user--wants to be able to do. I see no reason why the user story wouldn't be useful when applied to process.

The point about acceptance criteria is a good one, but need not be dogmatic about it (which is Agile anyway). It is a good exercise when designing any business process to ask, "How will I know if the change in process accomplished my goal?" It is true that you can't always run an automated test to answer that question, but that's not a reason to disqualify the user story as a tool.


问:
Dropping database in Grails is too easy. How to prevent accidental drops?
I just dropped production database. It happened because I used dbCreate = "create" instead of "update" in DataSource.groovy.

I was changing some domain models and wanted to update the database. dbCreate value was empty string (""), and I accidentally changed it to "create" instead of "update".

How could I prevent this from happening in the future (grails wise or in general)?

答:
Don't give DROP DATABASE or DROP TABLE privileges to the DB user you use for Grails.

It might also be a good idea to withhold most other privileges (other then INSERT, SELECT, DELETE) in production, as you don't want Grails to automagically do an ALTER TABLE operation that locks an important table for 30 minutes...

ContentLicense: CC BY-SA 3.0


问:
How to invoke a method in a class always when the class is accessed - like a reaction?
I am working on a C# net micro framework project, in particular an I2C bus class.

I have several different I2C devices each defined in separate classes which contain all of the devices' unique methods. In my case, I can only have ONE I2CDevice object defined and to switch to another I2C device, I have to change the I2CDevice.Config = DeviceConfig.

For example (pseudo-code):

```<code>Class Device1
-DeviceConfig1
-Method 1
-Method 2
-Method 3

Class Device2
-DeviceConfig2
-Method 1
-Method 2
-Method 3

Main Program
{
I2cBus = new I2CDevice(configuration)
Device1.Method1
Device2.Method3
}
</code>```

When switching between devices, I need to change the I2CDevice.Config property. I'm looking for an elegant way such that whenever I call a Method for a device, that the I2CBus.Config is automatically changed. Is there a way that I don't need to re-type this config code in each method? Have a separate internal method that's called each time I access any of those methods?

I hope my description is clear.

Update, As an alternative, is there a way I can have my make my I2C Bus class and then ADD the devices to the this class? Then To access The Devices, I would Do something like

```<code>I2CBus.AddDevice(Device1ObjectClass)
I2CBus.AddDevice(Device2ObjectClass)
I2CBus.Device1.Method1
I2CBus.Device2.Method2
</code>```

I still have the same problem that I need to "automatically" switch the I2C configuration between Different Device calls.

答:
Maybe:</p>

```<code>class DeviceWrapper
{
   private Device1 _device1;
   public Device1 device1
   {
      get
      {
           happensEveryTimeDeviceIsAccessed();
           return _device1;

       }
   }
}
</code>```

OwnerDisplayName: GisMofx

Body:
Maybe:

class DeviceWrapper
{
   private Device1 _device1;
   public Device1 device1
   {
      get
      {
           happensEveryTimeDeviceIsAccessed();
           return _device1;

       }
   }
}

OwnerDisplayName: RadioSpace


答:
This is the best I could come up with, and I'm not afraid to admit that it's garbage because you're still not able to have your I2CBus intrinsically know what to do. It kind of works but, as I mentioned, it's all I have.

```<code>public interface IDevice
{
    string Name { get; set; }
    DeviceConfiguration GetConfiguration();
}

public abstract class DeviceParent : IDevice
{
    public DeviceParent(DeviceConfiguration aConfig)
    {
        myConfig = aConfig;
    }

    #region IDevice Members

    public string Name { get; set; }

    public virtual DeviceConfiguration GetConfiguration() //This could also simply be a property, not sure what you want to do with it.
    {
        return myConfig;
    }

    #endregion

    protected DeviceConfiguration myConfig;

}

public class DeviceConfiguration
{
    public DeviceConfiguration()
    {

    }
}

public class Device : DeviceParent
{
    public Device(DeviceConfiguration aConfig) : base(aConfig) { }

    public void SomeMethod()
    {

    }
}

public class Device2 : DeviceParent
{
    public Device2(DeviceConfiguration aConfig) : base(aConfig) { }

    public void SomeMethod2()
    {

    }
}

public class I2CBus : IEnumerable<IDevice>
{

    private List<IDevice> myDevices;
    private DeviceConfiguration currentConfiguration;

    public enum NonExistantDeviceBehaviour
    {
        ReturnNull,
        AddToOurselves
    }

    public NonExistantDeviceBehaviour NoDeviceBehaviour; //Defines what should happen in the event that we're indexed by a device that we don't contain yet.

    public IDevice this[IDevice index]
    {
        get
        {
            if (!myDevices.Exists(d => d.Name == index.Name))
            {
                switch (NoDeviceBehaviour)
                {
                    case NonExistantDeviceBehaviour.ReturnNull:
                        return null;
                    case NonExistantDeviceBehaviour.AddToOurselves:
                        myDevices.Add(index);
                        break;
                }
            }

            currentConfiguration = index.GetConfiguration();

            return myDevices.Find(d => d.Name == index.Name);

        }
    }

    public I2CBus()
    {
        currentConfiguration = null;
        myDevices = new List<IDevice>(); //Ensures our list is never null
    }

    #region IEnumerable<IDevice> Members

    public IEnumerator<IDevice> GetEnumerator()
    {
        return myDevices.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion
}
</code>```

So all I did pretty much was add the index to the I2CBus class, which allows you to use this syntax:

```<code>I2CBusInstance[Device1]
</code>```

However, you still have to cast to the type you're passing to that index to get access to that type's methods anyway, which is why this solution isn't ideal. Here is the usage:

```<code>I2CBus i2cb = new I2CBus();

Device device = new Device(new DeviceConfiguration());
Device2 device2 = new Device2(new DeviceConfiguration());

i2cb.NoDeviceBehaviour = I2CBus.NonExistantDeviceBehaviour.AddToOurselves;

(i2cb[device] as Device).SomeMethod();
</code>```

Hope that helps a little... I'll be watching this question a while because I'm incredibly intrigued now.

Title: How to invoke a method in a class always when the class is accessed - like a reaction?

Body:
I am working on a C# net micro framework project, in particular an I2C bus class.

I have several different I2C devices each defined in separate classes which contain all of the devices' unique methods. In my case, I can only have ONE I2CDevice object defined and to switch to another I2C device, I have to change the I2CDevice.Config = DeviceConfig.

For example (pseudo-code):

```<code>Class Device1
-DeviceConfig1
-Method 1
-Method 2
-Method 3

Class Device2
-DeviceConfig2
-Method 1
-Method 2
-Method 3

Main Program
{
I2cBus = new I2CDevice(configuration)
Device1.Method1
Device2.Method3
}
</code>```

When switching between devices, I need to change the I2CDevice.Config property. I'm looking for an elegant way such that whenever I call a Method for a device, that the I2CBus.Config is automatically changed. Is there a way that I don't need to re-type this config code in each method? Have a separate internal method that's called each time I access any of those methods?

I hope my description is clear.

Update, As an alternative, is there a way I can have my make my I2C Bus class and then ADD the devices to the this class? Then To access The Devices, I would Do something like

```<code>I2CBus.AddDevice(Device1ObjectClass)
I2CBus.AddDevice(Device2ObjectClass)
I2CBus.Device1.Method1
I2CBus.Device2.Method2
</code>```

I still have the same problem that I need to "automatically" switch the I2C configuration between Different Device calls.

Body:
This is the best I could come up with, and I'm not afraid to admit that it's garbage because you're still not able to have your I2CBus intrinsically know what to do. It kind of works but, as I mentioned, it's all I have.

public interface IDevice
{
    string Name { get; set; }
    DeviceConfiguration GetConfiguration();
}

public abstract class DeviceParent : IDevice
{
    public DeviceParent(DeviceConfiguration aConfig)
    {
        myConfig = aConfig;
    }

    #region IDevice Members

    public string Name { get; set; }

    public virtual DeviceConfiguration GetConfiguration() //This could also simply be a property, not sure what you want to do with it.
    {
        return myConfig;
    }

    #endregion

    protected DeviceConfiguration myConfig;

}

public class DeviceConfiguration
{
    public DeviceConfiguration()
    {

    }
}

public class Device : DeviceParent
{
    public Device(DeviceConfiguration aConfig) : base(aConfig) { }

    public void SomeMethod()
    {

    }
}

public class Device2 : DeviceParent
{
    public Device2(DeviceConfiguration aConfig) : base(aConfig) { }

    public void SomeMethod2()
    {

    }
}

public class I2CBus : IEnumerable<IDevice>
{

    private List<IDevice> myDevices;
    private DeviceConfiguration currentConfiguration;

    public enum NonExistantDeviceBehaviour
    {
        ReturnNull,
        AddToOurselves
    }

    public NonExistantDeviceBehaviour NoDeviceBehaviour; //Defines what should happen in the event that we're indexed by a device that we don't contain yet.

    public IDevice this[IDevice index]
    {
        get
        {
            if (!myDevices.Exists(d => d.Name == index.Name))
            {
                switch (NoDeviceBehaviour)
                {
                    case NonExistantDeviceBehaviour.ReturnNull:
                        return null;
                    case NonExistantDeviceBehaviour.AddToOurselves:
                        myDevices.Add(index);
                        break;
                }
            }

            currentConfiguration = index.GetConfiguration();

            return myDevices.Find(d => d.Name == index.Name);

        }
    }

    public I2CBus()
    {
        currentConfiguration = null;
        myDevices = new List<IDevice>(); //Ensures our list is never null
    }

    #region IEnumerable<IDevice> Members

    public IEnumerator<IDevice> GetEnumerator()
    {
        return myDevices.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion
}

So all I did pretty much was add the index to the I2CBus class, which allows you to use this syntax:

I2CBusInstance[Device1]

However, you still have to cast to the type you're passing to that index to get access to that type's methods anyway, which is why this solution isn't ideal. Here is the usage:

I2CBus i2cb = new I2CBus();

Device device = new Device(new DeviceConfiguration());
Device2 device2 = new Device2(new DeviceConfiguration());

i2cb.NoDeviceBehaviour = I2CBus.NonExistantDeviceBehaviour.AddToOurselves;

(i2cb[device] as Device).SomeMethod();

Hope that helps a little... I'll be watching this question a while because I'm incredibly intrigued now.

OwnerDisplayName: Brandon


问:
Am I covered with GPL If I want to create a derived work from a GPLv2 project and change the project name?
Recently I create a fork from an "open source project GPLv2" with different name. I make a major changes in source code and I gave a new name to the modified open source. I kept in the header of each source file the origin author copyright. And then I publish my new open source in github.

is this behavior is legal according to GPLv2 License statements   ?
do I have the right to change the name of the modified open source ?
Could you please provide justification from licenses with the answer.

答:
Open source licenses (including the GPLv2) give you the right to modify a program written by someone else and distribute your modified version. There are few restrictions in the modifications that you can make.

The most common restriction is that you can't remove or alter the copyright license.

I am not aware of any open source licenses that forbid renaming your fork. In many cases, it is rather the other way around and it is frowned upon to release a fork of an existing project under the same name, because it can create a lot of confusion among the users if it depends on where you got your copy from whether version 10.1 of product FOO contains feature X.

In fact, some open source projects use trademark protection on their name (for example firefox) to force forks to use a different name.


答:
is this behaviour is legal according to GPLv2 License statements ?

Yes

do I have the right to change the name of the modified open source ?

Yes

Could you please provide justification from licenses with the answer.

A name change is just a modification to the source code (etc) that embodies the name, and modification of "the work" is one of many things that is permitted by the GPL (subject the rest of the license terms).

Besides, a restriction on renaming would go against the Four Freedoms.

In a comment, you say "the name is different!".

Yes and no.

Yes.  A name can be trademarked.  But trademark law does not prevent you from using a non-trademarked name ... unless it that one is sufficiently similar as to cause confusion.  Trademark is about stopping the use of a word / name, rather than forcing its use.

No.  A name cannot be copyrighted independently.  It is too small to be considered copyrightable.  Besides, if you replace a name with a different name, you are not copying the original one.

No.  To the extent that the name is part of the copyrighted work as a whole, the GPL says you can modify the work; see above.

Standard disclaimers apply.  IANAL.

I recommend that you take the time to read the GNU license itself, and the accompanying FAQs.  The latter have been professionally translated into many languages ... probably including yours.

Title: Am I covered with GPL If I want to create a derived work from a GPLv2 project and change the project name?

Body:
Recently I create a fork from an "open source project GPLv2" with different name. I make a major changes in source code and I gave a new name to the modified open source. I kept in the header of each source file the origin author copyright. And then I publish my new open source in github.

is this behavior is legal according to GPLv2 License statements   ?
do I have the right to change the name of the modified open source ?
Could you please provide justification from licenses with the answer.


问:
Compile-time IOC
Has anyone started a project to do IOC at compile time (possibly using Roslyn or Linq MethodInfo emit)?

My experience with IOC containers has thus far been great, baring a few small issues

Many IOC containers are slow to start up, as much of the resolution logic occurs here

It is often hard to ensure that resolution is possible, as compilation no longer ensures that the constructor can be called

Often IOC containers add a small overhead to the runtime (some aren't even small, often the ones that start up quickly run slowly)

It seems to me that the ideal solution would be to add a compile step to the build chain that adds a Factory class instead of IOC.

Has anyone done this before? If not, why not?

答:
Doing this should not be such a problem. Just run same IoC logic and instead of instantiating the classes, you emit code that does the instantiating.

But by doing this, you are removing one huge advantage of IoC : Ability to change how the coponents are composed without having to recompile the whole application. Just by replacing the config, you can have application use different services or data sources. And while I have yet to see application that would make full use of this capability, it is still major part of IoC's success.

Title: Compile-time IOC


问:
In Git, is the use of a 'PRODUCTION' branch necessary and/or would it be feasible to have more than one of them?
A short summary of how we do branch managing: From the MASTER branch one or many feature branches can be made (for mid to long term development), when deploy-able changes have been merged to MASTER then release branches are made. Release branches are kept for maintaining deployed version until the next release occurs and they are merged to PRODUCTION in order to build TAGS which are deployed to Live Environments.

First verse of the question: Is it actually necessary to have the PRODUCTION branch step? Surely TAGS can reliably be created off a Release Branch at the same point that it would have been merged to the PRODUCTION branch?

If they are worth having then the second verse of the question: Would it be a suitable source control to have more than one PRODUCTION branch while having just one MASTER?

The motivation: We will soon have an internal project starting that will (hopefully) be a "white-label" product we can use to replace three separate internal applications we use currently (as well as for any future applications). It would be one back-end, one library, one API but three teams using it and managing their own User Interfaces and adding reusable functionality to the back-end.

A thought was the project could be one repo with one MASTER, various feature branches for any of the teams as they need to develop things (mid- to long term). But should we then have a PRODUCTION branch for each of the three 'versions' of the product or just TAG off from the respective Release branches? So that they could deploy independently from each others' sprints and requirements (as long as they do not break the shared infrastructure).

PS:
Each of the three applications deploy to independent Live environments and used by different departments in the company.

PPS:
If you know of any other versioning-flows which would be better suited please tell me!

[EDIT - After reading jhr's answer]
Think of this as one BIG project/application. But instead of having one BIG team working on the sections used by 3 departments (each with their own required UI flows and features etc) we may be split into three teams, each working on a department's features, on the same code base (repo).
This is not a technical spec question per-say but rather one for opinion, experience or  preference etc.

答:
First of all, since your specifications are rather unclear, I'm not sure how much of this really applies. But I'll give it a shot...

If your project has one single release cycle, you only need one repository. If your three teams need to release new version independently, it gets a lot messier. But for that I'd need more specific input. At the moment, it sounds to me like you need to stabilize your API, develop the library and manage your back-end development. If that's part of one project, go ahead and use one repository.

As for the branching, I'd recommend to always have one branch that simply represents the latest released and working version. This branch will probably mostly have merge commits. I like the idea of release branches independent of development branches as a release manager could then easily review everything (after feature freeze if you want so), scratch the last few itches, set the version properly, and merge into your production branch. (You could even bind hooks or deployment strategies to that merge in order to automatically push release onto your build system or something).

As I said above, I'd recommend having one release cycle within one repository. If you can have that, only one production branch will be necessary. If the teams really need to release new versions of the same project independently, it feels like there's something wrong with the project management. But that's again without knowing much about the team and project in general.

A style that I like much is the git flow as described by Atlassian. It suggests having one master (production) and one development branch. On development the actual work happens but, that usually splits up into feature branches. What I like is that a development manager (someone with deep technical insight) can manage the development branch. They decide whether to merge new features or not. At some point they will tell a project/release manager that the team's done and that project/release manager can then (together with the development manager) work out the last few glitches on a release branch before it'll be merged into master (and back into development, of course). It's just an interesting separation of concerns that developers are so keen on regarding different aspects of the very same projects. :)

Hope this helps a bit.


问:
For professional designing company, what is the key to design an app elegantly?
I am coding and found it's pretty hard to come up with an elegant design for my app at the  first attempt.

First time I'm only about 40% happy, then I refactor it to code the same app a second time (almost start from scratch).

Second time coding, I'm only happy about 60% happy, so I refactor it once more to code the same app a third time (not start from scratch but I made a lot of changes).

Third time coding, I'm only happy about 80%. Here I am quite happy but I think if I can start over I can do much better and it should be very solid. But I am running out of time now. So I just leave it like it is. 80% Happy.

So my key word is "to keep re-factoring".

But this is my point of view as an indie developer so I don't know how a design company would design an application.

Suppose I give my idea to a professional designing company, will they keep refactoring like that many times to achieve an elegant design?

Or because they are a big design company, are they able to design everything well at the first attempt?

Do you work for a software design company? If you do then how does the professional designing company design applications elegantly?

答:
If you can get to a usable working solution in only 3 iterations, you're doing well.

The number of iterations and the amount of refactoring per iteration is highly dependent on the nature of the problem, how well you understand the specifications, how well the end customer knows what they want, and so on.

Some companies will iterate a lot more than 3 times.  Few if any will do it in less (unless we're talking about trivial programs).

With practice you'll find the process easier.

As for big design companies, it's important to remember that they have more people to work on a program and some of them might have more experience.  However, that doesn't necessarily make them smarter or "better" (however you define that term) than you.


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
The only thing that I disable JavaScript for is testing my own website. However, you might be interested in a study that Yahoo did that found between 1-2% of users have JavaScript disabled. Yahoo's audience is probably a pretty good representation of the average user.

A key quote from the study:

While 2% of U.S. visitors may not
  seem like a lot, keep in mind that
  over 300 million users visit the
  Yahoo! homepage each month. That means
  6 million users visit each month
  without the benefit of JavaScript. So
  even though it’s worth spending your
  time on the JavaScript-enabled version
  of the site, there are still a
  non-trivial amount of users out there
  who won’t be able to use it.

ContentLicense: CC BY-SA 2.5


问:
Picking a card from a shuffled deck
I'm pretty new to Haskell although I did some ML many moons ago.

I'm trying to set up a deck of playing cards, shuffle them and then deal them. I have the deck and shuffle sorted (of a fashion) but I'm not sure what I'm doing after that.

This is what I have so far:

```<code>import System.Random
import Data.Array.IO
import Control.Monad

-- | Randomly shuffle a list
--   /O(N)/
shuffle :: [a] -> IO [a]
shuffle xs = do
        ar <- newArray n xs
        forM [1..n] $ \i -> do
            j <- randomRIO (i,n)
            vi <- readArray ar i
            vj <- readArray ar j
            writeArray ar j vi
            return vj
  where
    n = length xs
    newArray :: Int -> [a] -> IO (IOArray Int a)
    newArray n xs =  newListArray (1,n) xs

ranks=[2..14]

suits=[1,2,3,4]

cards=[(r,s) | r <- ranks, s<- suits]

deck=shuffle cards

myAction :: IO [(Integer, Integer)]
myAction = shuffle cards

main :: IO ()
main = do
    xs <- myAction
    print xs
</code>```

There was no particular reason I chose that list shuffler other than the reason I could interrogate (or at least display) the resulting list.

I'd like to be able to pull items off the returned IO [(Integer, Integer)] but I'm not entirely sure how to proceed. I understand that I can't simply convert it to a vanilla list (this is covered sufficiently elsewhere) so presumably I either need to:

extend the IO (monad?) somehow

write a custom list of tuples shuffler

write my own monad

use some other method I haven't learnt yet

Anecdotally, I believe this can be done "uncleanly" but I don't want to go to programmer hell until I understand how hot the fires are...

Any idea how best to proceed?

答:
In abstract terms, what you should do is push the IO part as "high" up in your code as possible, so that as little code as possible knows about IO.

In more concrete terms, for your problem, shuffle and myAction don't need to know about IO, and also don't need to know how the randomness is generated.  They just need the randomness passed in as a parameter.  So what you can do is, generate the random value in main, and then pass it in as a pure value to myAction and/or shuffle.

You should end up with types like shuffle :: randomness -> [a] -> [a] and myAction :: randomness -> [a], where "randomness" is generated in main.  Now your return values aren't polluted with IO, and it's easy to work with them.*

AFAIK, this pattern -- where you split your code into "pure" and "impure" portions (and hope that most of it is "pure" :) ) -- is pretty common in Haskell.

*: if you're ever stuck in IO, read up on functors (fmap), applicatives (liftA2, <*>, etc.), monads (liftM, >>=, etc.), and lifting.  It's still a pain, but using those you can work on the a part of IO a.

Title: Picking a card from a shuffled deck


问:
Maintaining indices for location in a sorted list in database rows
I have a fairly simple data structure like this:

```<code>create table project (id int auto increment primary key, name text);

create table item (id int auto increment primary key, name text,
    project_id int not null,
    project_sort_index int not null,
    sort_index int not null,
    foreign key fk_project(project_id) references project(id));
</code>```

A project can have many items. Items have two different fields for maintaining sort order, project_sort_index and sort_index.

These sort order fields apply in the following way. When I view all items belonging to a project, I need a sort order specific to each project for the items. When I view all items globally, I need a sort order for them globally.

I have a couple of questions as to how best to maintain and modify sort order for these items. Lets say that I have moved an item at index 4 to index 2. How do I propagate that change to my database efficiently?

For example, how do I now update all index numbers >= 2 to move everything down, yet close the gap left in place 4? Is there a better way of sorting lists in SQL?

答:
If you move an item then only those items which lie between the old and new positions, inclusive, need to receive new sort_index values.  If an item moves from position 4 to position 2, only 2, 3 & 4 are affected; 1 is still 1, 5 is still 5 etc.

```<code>declare @id int;
declare @old int = 4;  -- the value in the original question
declare @new int = 2;
declare @lower int;
declare @upper int;

select @lower = MIN(c1)
from (values (@old),(@new)) as t1(c1);

select @upper = MAX(c1)
from (values (@old),(@new)) as t1(c1);

update #items
set si = si + SIGN(@old - @new)
where si between @lower and @upper;

update #items
set si = @new
where id = @id;
</code>```

I've tested this against SQL Server 2008R2.  Your RDBMS's syntax may vary.  The second UPDATE could be eliminated with more clever setting of @upper or @lower, depending on the direction of the move.  Given that any real system is likely to have a unique constraint on the sort_index, and hence an index, the update is likely to be quite efficient.  The number of rows modified would depend on how far the item's new position is from its previous one.  I would suggest that in any practicable UI this would be quite modest.  You know your data best, however.

As an aside, your table design is not normalised.  If an item were in 50 projects it would have to have 50 rows in your item table, each with different project_sort_index values but all with the same sort_index.  A better design would be

```<code>create table project (
    id int auto increment primary key,
    name text);

create table item (
    id int auto increment primary key,
    name text,
    sort_index int not null);

create table project_item (
    item_id int not null,
    project_id int not null,
    project_sort_index int not null);
</code>```

Body:
If you move an item then only those items which lie between the old and new positions, inclusive, need to receive new sort_index values.  If an item moves from position 4 to position 2, only 2, 3 & 4 are affected; 1 is still 1, 5 is still 5 etc.

declare @id int;
declare @old int = 4;  -- the value in the original question
declare @new int = 2;
declare @lower int;
declare @upper int;

select @lower = MIN(c1)
from (values (@old),(@new)) as t1(c1);

select @upper = MAX(c1)
from (values (@old),(@new)) as t1(c1);

update #items
set si = si + SIGN(@old - @new)
where si between @lower and @upper;

update #items
set si = @new
where id = @id;

I've tested this against SQL Server 2008R2.  Your RDBMS's syntax may vary.  The second UPDATE could be eliminated with more clever setting of @upper or @lower, depending on the direction of the move.  Given that any real system is likely to have a unique constraint on the sort_index, and hence an index, the update is likely to be quite efficient.  The number of rows modified would depend on how far the item's new position is from its previous one.  I would suggest that in any practicable UI this would be quite modest.  You know your data best, however.

As an aside, your table design is not normalised.  If an item were in 50 projects it would have to have 50 rows in your item table, each with different project_sort_index values but all with the same sort_index.  A better design would be

create table project (
    id int auto increment primary key,
    name text);

create table item (
    id int auto increment primary key,
    name text,
    sort_index int not null);

create table project_item (
    item_id int not null,
    project_id int not null,
    project_sort_index int not null);


答:
Another solution would be to hold your items as a doubly-linked list

```<code>create table item (
    id int auto increment primary key,
    name text,
    preceeding_item_id int,    -- have to be NULLable for first & last items.
    succeeding_item_id int);
</code>```

A move would then update at most 5 rows - the neighbours from the old location, those in the new, and the item itself.  The application would retrieve all rows and handle the on-screen sequencing.

Title: Maintaining indices for location in a sorted list in database rows

Body:
I have a fairly simple data structure like this:

```<code>create table project (id int auto increment primary key, name text);

create table item (id int auto increment primary key, name text,
    project_id int not null,
    project_sort_index int not null,
    sort_index int not null,
    foreign key fk_project(project_id) references project(id));
</code>```

A project can have many items. Items have two different fields for maintaining sort order, project_sort_index and sort_index.

These sort order fields apply in the following way. When I view all items belonging to a project, I need a sort order specific to each project for the items. When I view all items globally, I need a sort order for them globally.

I have a couple of questions as to how best to maintain and modify sort order for these items. Lets say that I have moved an item at index 4 to index 2. How do I propagate that change to my database efficiently?

For example, how do I now update all index numbers >= 2 to move everything down, yet close the gap left in place 4? Is there a better way of sorting lists in SQL?

Body:
Another solution would be to hold your items as a doubly-linked list

create table item (
    id int auto increment primary key,
    name text,
    preceeding_item_id int,    -- have to be NULLable for first & last items.
    succeeding_item_id int);

A move would then update at most 5 rows - the neighbours from the old location, those in the new, and the item itself.  The application would retrieve all rows and handle the on-screen sequencing.


问:
Trying to "combine" similar objects without doing a bazillion comparisons
In this database I have "accesses" - each access can have any number (usually less than 4, sometimes as many as 15) attributes. I also have "tickets" where N users are requesting M accesses, so I've got a sub-ticket table with the NxM "user access requests". Then for the sub-ticket, there is another table with the A attributes for that access (where "A" varies depending on the request).

So, for example, if I have two users requesting three accesses, and those accesses have 2, 3 and 4 attributes respectively, I have 1 ticket record, 6 sub-tickets records, and 18 sub ticket attribute records.

The problem is that I want to quickly group the sub-tickets together, so that when I display them I can find all the ones for one type of access, then all the ones of another type of access, and then the third type of access. I know, each type of access should have been given a unique id somehow, but they weren't, and now it's my burden. I only am allowed to "suggest" database changes, not insist on them.

Any suggestions?

答: We have a large (100 million row) tables which hold variable number of attributes per item too.  For ad hoc querying I have created views which pivot the data i.e. turn rows into columns.  The result can then be queried as if it were a "proper" table.  You'll have to know the attribute names for this to work, however, or write a script which dynamically creates the SQL to create the view.</p>


答:
I use NoScript but whitelist any site I actually intend to use.

When you install NoScript, JavaScript, Java, Flash Silverlight and possibly other executable contents are blocked by default. You will be able to allow JavaScript/Java/... execution... selectively, on the sites you trust. You can allow a site to run scripts temporarily, if you're just surfing randomly, or permanently, when you visit it often and you really trust it. This means that NoScript learns from your own browser habits and tends to disappear in the background after a while, but it promptly comes back to save your day if you stumble upon a malicious web page.

When you browse a site containing blocked scripts a notification, similar to those issued by popup blocker, is shown.

  Look at it or at the statusbar icon to know current NoScript permissions...

Title: How important is graceful degradation of JavaScript?

Body:
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?


问:
Testing ASP.NET .aspx and .ascx code behind files
I am wondering how to test .aspx.cs and .ascx.cs code behind. Can I use unit testing and if so how? Are there alternatives that will help test the functions in the code behind files? I don't know how to mock the page or control.

I would like to try to apply tdd methodology but I don't know how to unit test the code behind. Do you setup tests for the code behind or move the code to alternate files that are easier to test.

Is moving the code out of the code behind a better practice?

Also, how would you go about unit testing the code behind files?

答: It is actually pretty easy. All you need to do is to Extract the logic from Code behind/beside into Presenter class. All ASP.NET specific code should stay in code behind abstracted by View interface, that will be manipulated from Presenter. There is many examples on Model-View-Presenter pattern. Eg. http://blog.vuscode.com/malovicn/archive/2007/10/25/model-view-presenter-mvp-design-pattern-close-look-part-1-supervising-controller.aspx</p>


问:
Kibibtye or Kilobyte to represent 1024 bytes
I am working on a project with several older programmer and we were doing up the documentation of the program when I had a heated debate with one of the older programmers regarding the term : Kilobyte.

He wanted to stick to the old way of using Kilobytes to represent 1024 bytes as he said most programmers understood the term : Kilobyte to represent 1024 bytes.

I wanted the new way of using Kibibyte to represent 1024 bytes as we can't forever be stuck in our old ways and this has been updated by the community.

How should I resolve this conflict with him so as to appease both of us  ??

答: Use Kilobyte as it's the generally accepted term of art. Kibibyte is a hypercorrection unless it's somehow critically important to the functioning of the application. Software documentation should focus on clarity. This includes adhering to accepted conventions.</p>


问:
Should refactoring be the exception or the rule?
I had a discussion with a co-worker yesterday about design philosophy.  The other coder is more experienced then me, and I fully admit that he is likely much better at properly automating his testing, which I'm just now trying to break sloppy habits.  However, it seems that some of our dispute is a philosophical issues where I'm unwilling to simply yield to his greater experience.

Generally he is a Directing programmer, who follows all of the formal approaches.  He has interfaces for nearly every class  and has automated tests for everything down to getter and setters on basic POJO objects.  He sees refactoring as a dirty word which is a sign that things weren't written/designed properly from the start, it’s inevitable and done as necessary but everything should be done to avoid having to do it and you should feel bad when you have to.

I feel I'm a more flexible/Enabling programmer.  I feel that interfaces should be used as necessary, but not thrown in until they are needed (KISS), and that it's easy enough to pull an interface out of an existing object by refactoring if you decide an interface/polymorphism makes more sense later.  I also felt that, while I admit I need to be better at testing then I am currently, the level of automated tests he suggested seemed too rigors since it would take so long to implement and, more importantly, make refactoring a nightmare since I wouldn't be free to modify the behavior of any non-private method.  As my requirements grow and change I find myself refactoring heavily and that level of testing feels like it would kill my flexibility.  His view is that I shouldn't be refactoring so it doesn't matter if the tests make it harder to do.

Ultimately all of the other philosophical discussions seemed to boil down to the word 'refactor'.  I love refactoring, I feel it should be used liberally any time you feel that something isn't quite as clean and beautiful as it should be, and that the natural course of growing a program or adding new requirements will necessitate refactoring to better enable code reuse, moving logic to new classes/packages as it grows more complex, and yes fixing inevitable design mistakes which will happen from a flexible agile development approach (and that’s not always bad if your code is written to allow modification!).  He disagrees with all of that.

I'm wondering what other's thoughts are on refactoring.  How common should it be?  Is writing code with a philosophy of "I'm doing it simple now, I can refactor it later if more complicated logic proves necessary" inherently flawed/dangerous?  Does acceptability of refactoring depend on program approach and style?  I generally am on rapid prototyping or “clean up this ugly, but working, prototype some non-engineers wrote”, while it sounds like he actually gets to do formal programming with official requirements that don’t change; I’ve never once had a job like that myself!

答:
It all come down to who writes better code relative to the amount of time. Your company/team should define what "better" means. Customers have something to say about this as well.

Make sure you have a solid definition of Refactoring. It sounds like you do, but you mention it along with code behavioral changes very close together in your question. Be careful. You two can't maintain this debate if you don't agree on the definition.

Out of everything the two of you are claiming, the biggest issue is his claim to be able to write code correctly the "first" time. Does this occur when code is checked in for the very first time or before it goes into production? Obviously the later gives you a little more time to get things right. Maybe he has worked on this particular project for so long that he is able to do it because he understands the code and the people asking for features. A new PM could be added who doesn't create as detailed of specs or may not understand the domain as much as the current one. Your method may make you more adaptable.

Does he take a disproportionate amount of time to achieve the same objective as you do with fewer bugs/need to improve? Code can be improved to a certain extent forever, but truly good code gets shipped. Do you introduce more bugs into the system? Users want new features and corrections sooner, but there is a point they get too frustrated with too many bugs popping up too often. Every time we update...

Your philosophical arguments are only just personal preferences until you can determine who is the most effective developer. Would your Directing programmer be able to do this on a new project? Are you using "I can refactor it later" as a crutch?


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答: Many laywers offer free consultations, where they will explain what you will expect to pay and what you might be able to gain. Google "Intellectual Property Lawyer" and ask until you find one who will give you a free consultation.</p>

Title: How to get money from reluctant client?


答:
I think the answer lies in between the two of you.

Changes are to be expected as software evolves. No matter how competent you are, you can't predict the future with 100% accuracy. And even if you could, it may not match your customer's predictions or taste. Since he's the one who pays he (most unfortunately :) ) has a say in it. So unless it's dead simple, it's almost impossible to design an application with everything in it's right place from day one.

On the other hand, you still do have the responsibility to be, at all times, as close as possible to that. You have to plan and think ahead of requirements so that you will be less likely to paint yourself in a corner and make it nearly impossible for your code to adapt to new demands (and believe it, there will be demands).

Therefore, while I fully agree with you that refactoring is a great thing to do whenever you feel things could be better, calling it a "rule" doesn't sound quite right to me. If refactoring code is something you do on a daily basis then clearly something is wrong with the way you are coding your apps.

On this question:

```<code>Is writing code with a philosophy of "I'm doing it simple now, I can refactor
it later if more complicated logic proves necessary" inherently flawed/dangerous?
</code>```

If you expect - or even just suspect - that more complicated logic will be required eventually, the answer is most definitely yes. If not then it really depends on code's usefulness, how deep it will be in your app, project deadlines and perhaps most importantly, common sense.

If your customer is a bike workshop in Wisconsin it's very unlikely that he'll need an app that supports international phone numbers. Therefore it's reasonable for you to design a PhoneNumber class that's really just holding a three digits area code and a seven digits number. In the unlikely event that it becomes necessary for your customer to store data on bikers from France, refactoring may then become helpful.

This is of course just an example but you get the idea: while at first it may make sense to write pretty straightforward code, as time passes and requirements changes you might find that the way your application now relies on it may be a problem. This is the kind of scenario which you should normally try to avoid but unless you're God you won't be able to avoid all of them. Sometimes it won't even be your fault; software customers tends to be very imaginative when it comes to transform a bike workshop management application into a pizza ordering system.

In any case, you should still always write code in the way you think it should be upon release. Think of refactoring as a way to fix things you made wrong assumptions on.

Title: Should refactoring be the exception or the rule?

Body:
I had a discussion with a co-worker yesterday about design philosophy.  The other coder is more experienced then me, and I fully admit that he is likely much better at properly automating his testing, which I'm just now trying to break sloppy habits.  However, it seems that some of our dispute is a philosophical issues where I'm unwilling to simply yield to his greater experience.

Generally he is a Directing programmer, who follows all of the formal approaches.  He has interfaces for nearly every class  and has automated tests for everything down to getter and setters on basic POJO objects.  He sees refactoring as a dirty word which is a sign that things weren't written/designed properly from the start, it’s inevitable and done as necessary but everything should be done to avoid having to do it and you should feel bad when you have to.

I feel I'm a more flexible/Enabling programmer.  I feel that interfaces should be used as necessary, but not thrown in until they are needed (KISS), and that it's easy enough to pull an interface out of an existing object by refactoring if you decide an interface/polymorphism makes more sense later.  I also felt that, while I admit I need to be better at testing then I am currently, the level of automated tests he suggested seemed too rigors since it would take so long to implement and, more importantly, make refactoring a nightmare since I wouldn't be free to modify the behavior of any non-private method.  As my requirements grow and change I find myself refactoring heavily and that level of testing feels like it would kill my flexibility.  His view is that I shouldn't be refactoring so it doesn't matter if the tests make it harder to do.

Ultimately all of the other philosophical discussions seemed to boil down to the word 'refactor'.  I love refactoring, I feel it should be used liberally any time you feel that something isn't quite as clean and beautiful as it should be, and that the natural course of growing a program or adding new requirements will necessitate refactoring to better enable code reuse, moving logic to new classes/packages as it grows more complex, and yes fixing inevitable design mistakes which will happen from a flexible agile development approach (and that’s not always bad if your code is written to allow modification!).  He disagrees with all of that.

I'm wondering what other's thoughts are on refactoring.  How common should it be?  Is writing code with a philosophy of "I'm doing it simple now, I can refactor it later if more complicated logic proves necessary" inherently flawed/dangerous?  Does acceptability of refactoring depend on program approach and style?  I generally am on rapid prototyping or “clean up this ugly, but working, prototype some non-engineers wrote”, while it sounds like he actually gets to do formal programming with official requirements that don’t change; I’ve never once had a job like that myself!

Body:
I think the answer lies in between the two of you.

Changes are to be expected as software evolves. No matter how competent you are, you can't predict the future with 100% accuracy. And even if you could, it may not match your customer's predictions or taste. Since he's the one who pays he (most unfortunately :) ) has a say in it. So unless it's dead simple, it's almost impossible to design an application with everything in it's right place from day one.

On the other hand, you still do have the responsibility to be, at all times, as close as possible to that. You have to plan and think ahead of requirements so that you will be less likely to paint yourself in a corner and make it nearly impossible for your code to adapt to new demands (and believe it, there will be demands).

Therefore, while I fully agree with you that refactoring is a great thing to do whenever you feel things could be better, calling it a "rule" doesn't sound quite right to me. If refactoring code is something you do on a daily basis then clearly something is wrong with the way you are coding your apps.

On this question:

Is writing code with a philosophy of "I'm doing it simple now, I can refactor
it later if more complicated logic proves necessary" inherently flawed/dangerous?

If you expect - or even just suspect - that more complicated logic will be required eventually, the answer is most definitely yes. If not then it really depends on code's usefulness, how deep it will be in your app, project deadlines and perhaps most importantly, common sense.

If your customer is a bike workshop in Wisconsin it's very unlikely that he'll need an app that supports international phone numbers. Therefore it's reasonable for you to design a PhoneNumber class that's really just holding a three digits area code and a seven digits number. In the unlikely event that it becomes necessary for your customer to store data on bikers from France, refactoring may then become helpful.

This is of course just an example but you get the idea: while at first it may make sense to write pretty straightforward code, as time passes and requirements changes you might find that the way your application now relies on it may be a problem. This is the kind of scenario which you should normally try to avoid but unless you're God you won't be able to avoid all of them. Sometimes it won't even be your fault; software customers tends to be very imaginative when it comes to transform a bike workshop management application into a pizza ordering system.

In any case, you should still always write code in the way you think it should be upon release. Think of refactoring as a way to fix things you made wrong assumptions on.


答:
I'd say the exception.

Every time you refactor, you're basically changing the way the code looks rather than the way it works (eg you might extract a block of code into a method, or change a switch to a polymorphic function call, in all cases the functionality hasn't changed, you've just altered it).

Now while this maybe useful to make the code easier to maintain or understand, it is still making large changes that will really affect the way your code shows up in the source control logs. You cannot now look at the diffs and see a bug because of a code change, as the code is radically different. Its the same problem when you change the look of code because you want to prettify it (eg change brace positions or rename variables).

So refactoring should really be kept for cases where it is really worthwhile, just so you can keep a sense of what the code does. I used to work with a guy who changed the code dramatically - I'd come in after a weekend and find the codebase was practically a different product. It made working with it tremendously difficult as I had to take the time to figure out where the bits I was familiar with had gone.

There is also a sense that refactoring is overused nowadays, a sense that coders should hack something together that works quickly, and then tidy it up to make it look good later (or even, just tidy it up as you go). I think this is a poor practice. You should think what you're trying to achieve before you do it. If this was done first, you shouldn't need to refactor. In the old days where design-first was much more prevalent, refactoring was solely used for legacy code, never for daily work.

I know one though - 'beauty is in the eye of the beholder'. You may refactor to make things look nicer, but then someone else may come along and refactor again to make it look nice to them (in Fowler's Refactoring book there are refactorings that are opposites!). You'll never stop, spending all day refactoring code and none actually writing product features.


答:
Embrace refactoring. Embrace the fact that you can create code that works, and you have tests that make it work, and then you can change the internals having confidence that you are not breaking anything. And as you mention, KISS.

About the view of not having written/designed correctly from the start, for me the answer is that I have not worked in a project in which there were no changes at some point (or rather, very often). Even if someone spent a month "designing" the solution. Changes that introduce duplication, that introduce generalization, that introduce new use cases. For all of them you will refactor.

Even as you are writing a fully "designed" solution, you will find that there is duplicated code, that there are generalizations not taken into account. Coding is designing, and until you are not done coding, you have not finished designing.

One other thing to add: YAGNI.


问:
Wrapper around C++ STL
Where I work we have our own system library, which pretty much is only wrappers around the STL, such as:

```<code>template <typename T>
class HVector {
protected:
    std::vector<T> data;
public:
    int size () const; //Only returns data.size()
    int custom(); //Some generic custom function that uses the data vector
}
</code>```

Most of the class members are just re-declarations of the STL container members, but we also have a few customized functions that do some generic tasks with the container.

Is this a good design? If not, what would be the best way to implement the customized functions around the containers?

答:
I wouldn't, I'd rather see a class that is a vector if its basically just a vector with 1 or 2 custom functions.

For these custom functions, I'd say its better to make functions that operator on the type, for example all the methods in . You might find this approach is a little more generic and so encourages reuse across your wrapper classes.

However, if the class is more than a vector, and just happens to use a vector as internal data storage, then that's fine. A Customers class that deals with a vector of Customer objects is one thing. Re-implementing a vector with your own vector isn't.

Title: Wrapper around C++ STL


答:
I've preferred to derive from the STL to add functionality and also hide the templating.  So rather than use the vector as a member variable, I would derive so that my CustomVector is still a vector, and all the methods that are available on a vector, are also available on my CustomVector.  Also, any method that can work off a Vector will also work on my custom class.

If you wanted to keep the exposure of the templates, as you do in your example, it's easy enough to do with this technique.

Title: Wrapper around C++ STL

Body:
Where I work we have our own system library, which pretty much is only wrappers around the STL, such as:

```<code>template <typename T>
class HVector {
protected:
    std::vector<T> data;
public:
    int size () const; //Only returns data.size()
    int custom(); //Some generic custom function that uses the data vector
}
</code>```

Most of the class members are just re-declarations of the STL container members, but we also have a few customized functions that do some generic tasks with the container.

Is this a good design? If not, what would be the best way to implement the customized functions around the containers?


答:
It depends on the nature of those custom operations, but probably yes, it's bad design. And the main reason for stating this is that you are coupling operation and storage.

If a certain custom operation is semantically independent, it can be better implemented as an standalone (functor) class or function, taking an specific container parameter. Moreover, if it doesn't depend on the concrete container class, it can be added an extra template parameter specifying it, or even better, refactored in order to work over iterator ranges. See, just like the STL algorithm functions.

Also, wrapping the way you do it involves forwarding a significant part of the wrapped container's public interface. This is a clear smell.

Title: Wrapper around C++ STL


问:
Git, rebase and stay synced with remote branch
I have something of an annoyance in my Git workflow. I do the usual thing where I branch off master, into a branch called feature. I work on this feature branch for a while, meanwhile possibly master has commits of its own, which I might merge into feature. As I do this, I have a remote branch for feature (origin/feature) that I use so I can build and run my code on multiple machines.

Now, when I finish with the feature branch, I need to push the code to our code review system. This means rebasing feature off master, and squashing all the commits into one. I do this, resolve conflicts if necessary, great. Here's the problem: feature and origin/feature now have different histories, and I'm not able to push. I tried push with -f to force it even, and this did not work either.

Is there some convenient way to rebase feature off master, and keep feature and origin/feature synced? What I'm considering is doing another branch for the code review. In other words, before the rebase and squash, branch into featurecodereview. Then rebase featurecodereview off master, and if I like I can push this upstream to a new remote branch. I was wondering if there was something cleaner than opening another branch.

答:
What code review tool/system are you using? Because git does have ways to show the diff (or create a patch, I think) across multiple commits. So rebasing and squashing may be completely unnecessary.

I also use a feature branch workflow, and I never bother with either. I just do a pull request (either in Github or Atlassian Stash) and it shows all the differences as if it had been a single commit.


问:
PHP Code base design: Single "queries.php" file, or spread queries across different php files/classes?
When I create PHP projects, is it better to put all database (e.g. MySql) queries in a single file (i.e. "queries.php")? Or is it better to place the respective queries in any "model" classes (i.e. User.php) that I may be creating? Is it bad practice to put database queries anywhere in any PHP file?

In the queries.php I would be placing functions for calling the queries.

答: You can create a base Model which will have the general queries and other models can be inherited from the base model and will contain specific queries to that model.</p>


问:
Is it fine to reuse a class instance?
I ask in terms of high cost classes, with a particle engine as an example.

I read somewhere that an instance of a class with a high cost to initialize, like a particle manager, should have its state variables altered at run time rather than reinitialize the particle manager with new data every time it is used in a different way.

The particle manager would create perhaps thousands of instances of particles on initialization and then manage them from then on.

For example, let's say this particle manager is used to manage shrapnel in an explosion; and you're creating a ground zero simulation for an artillery attack; thus there are many explosions.

Instead of multiple managers for each explosion, which is extremely expensive, you alter the variables for each explosion and have a scattered sequential set of explosions using the same manager and the same particles.

So I ask: is it fine to reuse a class instance at run time?  Or is the above really just a super optimization case?

答:
It is perfectly fine to reuse an object like this as long as it is written correctly for that purpose.

Invoking behavior on the object should not be affected by any previous calls to the object. Consider the following code:

```<code>class Example {
  private int x = 1;

  public int multiply(int y) {
    return x *= y;
  }
}
</code>```

Calling the multiply() function alters the state of the class. Calling it multiple times produces different results, so to produce consistent results you would need multiple objects. Granted this is a contrived example but it shows the issue: this class is not easily reusable by two different processes.

It may also be permissable to have a way to reset an object. Perhaps it has complex storage requirements, and it is faster to zero out its storage than to release and reacquire resources. This is a simple Java example showing what I mean:

```<code>List<Object> data = new ArrayList<Object>(1000000);
someMethod(data);
data.clear();
someMethod2(data);
</code>```

While ArrayList is not a really expensive object, think about a million element array. Perhaps it is faster to zero it out than to ask the memory manager to find another chunk of memory that can accommodate that much storage (and Java will zero out the memory anyway, making clear() work faster in this case).

Unfortunately there is no way to say for sure that it will or will not always work, all we can do is say "if the code does this, it will or will not work."

Title: Is it fine to reuse a class instance?

Body:
It is perfectly fine to reuse an object like this as long as it is written correctly for that purpose.

Invoking behavior on the object should not be affected by any previous calls to the object. Consider the following code:

class Example {
  private int x = 1;

  public int multiply(int y) {
    return x *= y;
  }
}

Calling the multiply() function alters the state of the class. Calling it multiple times produces different results, so to produce consistent results you would need multiple objects. Granted this is a contrived example but it shows the issue: this class is not easily reusable by two different processes.

It may also be permissable to have a way to reset an object. Perhaps it has complex storage requirements, and it is faster to zero out its storage than to release and reacquire resources. This is a simple Java example showing what I mean:

List<Object> data = new ArrayList<Object>(1000000);
someMethod(data);
data.clear();
someMethod2(data);

While ArrayList is not a really expensive object, think about a million element array. Perhaps it is faster to zero it out than to ask the memory manager to find another chunk of memory that can accommodate that much storage (and Java will zero out the memory anyway, making clear() work faster in this case).

Unfortunately there is no way to say for sure that it will or will not always work, all we can do is say "if the code does this, it will or will not work."


答:
Assuming the previous usage is completed and no paralelism takes place:

It depends on cost (both runtime and developement) of getting the instance into "neutral" state. Sometimes its easier to delete (or not reference it anymore and leave releasing for GC) whole object than inspect and delete its parts. And sometimes it's hard to be sure you did it right.
And sometimes original author did not exepect reuse, so some operations are one way only.
And reusing object can (in systems with GC) lead to it being moved to longer lived generation, so even if it is not needed soon after it will be GCed much later (if it is needed then it does not matter).

That does not mean you should never do it, just think about consequences and measure result.

If you are designing such object, try to split it in expensive reusable object (not containing state from usage) and as cheap as possible nonreusable usage specific object. (eg. in hibernate  there is Session factory (expensive) and it creates session (relatively cheap).

Title: Is it fine to reuse a class instance?

Body:
I ask in terms of high cost classes, with a particle engine as an example.

I read somewhere that an instance of a class with a high cost to initialize, like a particle manager, should have its state variables altered at run time rather than reinitialize the particle manager with new data every time it is used in a different way.

The particle manager would create perhaps thousands of instances of particles on initialization and then manage them from then on.

For example, let's say this particle manager is used to manage shrapnel in an explosion; and you're creating a ground zero simulation for an artillery attack; thus there are many explosions.

Instead of multiple managers for each explosion, which is extremely expensive, you alter the variables for each explosion and have a scattered sequential set of explosions using the same manager and the same particles.

So I ask: is it fine to reuse a class instance at run time?  Or is the above really just a super optimization case?


问:
Is there any performance benefit in checking the item count prior to executing a foreach loop?
I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping:

```<code>if (SqlParams.Count > 0)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

I always prefer to do a null check instead and let the foreach loop just hop out if there are 0 items.

```<code>if (SqlParams != null)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

Isn't that the better way?

答:
The benefit comes in the form of flexibility, but it has no performance benefit.

When a foreach runs over an ICollection with count of 0, the enumerator will register as having already traversed the whole set.  Functionally, it's similar to the following for loop:

```<code>for(int i = 0; i > -1; i++)
    foo();
</code>```

Now, if there is some other business rule that needs to fire prior to the foreach, that's a completely different story, and having the if condition accomodates that future capability nicely.  But, it's also not strictly necessary, either.

EDIT: In response to your edit, the null check is a vastly better way to do it, since a collection can be null.

I wound up writing a IsNullOrEmpty extension method for IEnumerables, because I kept on seeing a lot of repeated conditions like:

```<code>if(SomeCollection != null
   && SomeCollection.Count > 0
   && (SomeOtherCondition))
{
    // Stuff that relies on SomeCollection having at least one value.
}
</code>```

Body:
The benefit comes in the form of flexibility, but it has no performance benefit.

When a foreach runs over an ICollection with count of 0, the enumerator will register as having already traversed the whole set.  Functionally, it's similar to the following for loop:

for(int i = 0; i > -1; i++)
    foo();

Now, if there is some other business rule that needs to fire prior to the foreach, that's a completely different story, and having the if condition accomodates that future capability nicely.  But, it's also not strictly necessary, either.

EDIT: In response to your edit, the null check is a vastly better way to do it, since a collection can be null.

I wound up writing a IsNullOrEmpty extension method for IEnumerables, because I kept on seeing a lot of repeated conditions like:

if(SomeCollection != null
   && SomeCollection.Count > 0
   && (SomeOtherCondition))
{
    // Stuff that relies on SomeCollection having at least one value.
}


答:
Not really, because if there are 0 items, the setup of the foreach loop will find that out anyway and simply not execute the body of the loop.

It's theoretically possible, in a very tight loop in which it's common for your collection to be empty, and in which finding the count is a very inexpensive operation, for there to be a noticeable performance benefit here, but if you're doing database queries, that's almost certainly not the case.  So don't worry about it unless profiling shows that this is actually taking a significant amount of execution time.

Title: Is there any performance benefit in checking the item count prior to executing a foreach loop?

Body:
I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping:

```<code>if (SqlParams.Count > 0)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

I always prefer to do a null check instead and let the foreach loop just hop out if there are 0 items.

```<code>if (SqlParams != null)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

Isn't that the better way?


问:
Is there a named antipattern for unclear API not exposing the requirements?
In the source code I'm evaluating (jarjar), there exists java code that can be used like this:

```<code>JarJarTask fixture = new JarJarTask();
fixture.addConfiguredRule(new Rule());
fixture.execute();
</code>```

Which will throw an exception like:

```<code>java.lang.IllegalArgumentException:
The <rule> element requires both "pattern" and "result" attributes.
</code>```

Now, to me it is clear that the API is less than optimal here - if the rule element requires these attributes, it should ask for them in the constructor (or provide a Builder or similar that would require them). But I was unable to find coding conventions or java programming recommendations to agree with me.

Is there some specific name for this that I can use to look this up in research, programming literature, style guides? Which terms could I use to find some discussion on this?

Surely it's been discussed somewhere using some terms, but I seem to be unable to find anything.

I did find discussion around constructor injection as presented by Kent Beck in Smalltalk Best Practice Patterns and supported by Martin Fowler, which, according to this, makes it "immediately clear what a class requires when it is instantiated, and furthermore it is impossible to instantiate the class without passing in the field’s objects". So that's a starting point at least to find some discussion.

答:
The best you're going to do here is to state what the API isn't, or what it fails to provide.  Constructor vs. Setter Injection is a bit of a side journey, but the principle is sound: write your classes so that it is clear from the constructor arguments exactly what is required to create a fully-formed, functional object.

If you follow best practices in your organization, simply state that the class fails to follow the practice of describing its instantiation requirements in the constructor.

Related

Design by Contract


问:
How is the router configuration gui designed and implemented?
It's a rather simple concept, and each vendor seems to have their own "Website" for their config. I am curious to find out a few things. In my linksys router, if I go to 192.168.1.1, it asks for a simple log in, followed by the status page.

Here ports/passwords and all that can be completely changed. What's interesting is how the firmware updater works. You can click upload, drop in their new firmware, and it presumably flashes the device.

What technologies / frameworks would be ideal for creating my own custom router page? I've seen a custom one (Tomato).

答:
Creating a custom router page is no different than creating any other web page.  You use the tools that are most appropriate for that.

The real difference is that a UI for a router or other embedded device is going to be much simpler.  You're not going to be using elaborate frameworks like Ruby on Rails, Angular or even jQuery.  All you really need is probably some static HTML files and a simple HTTP server.

Further Reading

Embedded Web Servers


问:
Why no MVC methodology for desktop applications?
I'm currently learning how to develop web apps with C#, ASP, .NET and MVC. I am enjoying the MVC paradigm a lot, but then thought about using this to develop desktop software with. I googled around, but found nothing using the MVC pattern to create desktop apps that connect to databases. So what software pattern do .net programmers like use if they not using MVC? </p>

<p>Thanks.  </p>

答:
Try looking for MVVM instead of MVC.

Here's an MS article on MVVM which is very much applicable to WPF

And here's another tutorial on MVVM with WPF

Or look at MVP with winforms.

From a broad point of view, MVVM and MVP are just variants of MVC.


问:
Real time unit testing - or "how to mock now"
When you are working on a feature that depends on time... How do you organize unit testing ? When your unit tests scenarios depend on the way your program interprets "now", how do you set them up ?

Second Edit: After a Couple of days reading your experience

I can see that the techniques to deal with this situation usually revolve around one of these three principles:

 Add (hardcode) a dependency: add a small layer over the time function/object, and always call your datetime function through this layer. This way, you can get control of time during the test cases.

 Use mocks: your code stays exactly the same. In your tests, you replace the time object by a fake time object. Sometimes, the solution involves modifying the genuine time object that is provided by your programming language.

 Use dependency injection: Build your code so that any time reference is passed as a parameter. Then, you have control of the parameters during the tests.

Techniques (or libraries) specific to a language are very welcome, and will be enhanced if an illustrative piece of code comes along. Then, most interesting is how similar principles may be applied on any platform.
And yes... If I can apply it straight away in PHP, better than better ;)

Let's start with a simple example: a basic booking application.

Let's say we have JSON API and two messages: a request message, and a confirmation message.
A standard scenario goes like this:

You make a request. You get a response with a token. The resource that is needed to fulfill that request is blocked by the system for 5 minutes.

You confirm a request, identified by the token. If token was issued within 5 minutes, it will be accepted (the resource is still available). If more than 5 minutes have passed, you have to make a new request (the resource was freed. You need to check for its availability again).

Here come the corresponding test scenario:

I make a request. I confirm (immediately) with the token I received. My confirmation is accepted.

I make a request. I wait 3 minutes. I confirm with the token I received. My confirmation is accepted.

I make a request. I wait 6 minutes. I confirm with the token I received. My confirmation is rejected.

How can we get to program these unit tests ? What architecture should we use so that these functionalities remain testable ?

Edit Note: When we shoot a request, the time is stored in a database in a format that looses any information about milliseconds.

EXTRA - but maybe a bit verbose: Here come details about what I found out doing my "homework":

I Built my feature with a dependency on a time function of my own. My function VirtualDateTime has a static method get_time() that I call where I used to call new DateTime(). This time function allows me to simulate and control what time is "now", so that I can build tests like: "Set now to 21st jan 2014 16h15. Make a request. Move ahead 3 minutes. Make confirmation.". This works fine, at the cost of the dependency, and "not so pretty code".

A little more integrated solution would be to build a myDateTime function of my own that extends DateTime with additional "virtual time" functionnalities (most importantly, set now to what I want). This is making the first solution's code slightly more elegant (use of new myDateTime instead of new DateTime), but ends up to be very similar: I have to build my feature using my own class, thus creating a dependency.

I have though about hacking the DateTime function, to make it work with my dependency when I need it. Is there any simple and neat way to replace a class by another, though ? (I think I got an answer to that: See namespace below).

In a PHP environment, I read "Runkit" may allow me to do this (hack the DateTime function) dynamically. What is nice is that I would be able to check I am running in test environment before modifying anything about DateTime, and leave it untouched in production [1]. This sounds much safer and cleaner than any manual DateTime hack.

Dependency injection of a clock function in each class that uses time [2]. Is this not overkill ? I see that in some environments it gets very usefull [5]. In this case, I do not like it so much, though.

Remove dependency of time in all the functions [2]. Is this always feasible ? (See more examples below)

Using namespaces [2][3] ? This looks quite good. I could mock DateTime with my own DateTime function that extends \DateTime... Use DateTime::setNow("2014-01-21 16:15:00"), and DateTime::wait("+3 minutes"). This covers pretty much what I need. What if we use the time() function though ? Or other time functions ? I still have to avoid their use in my original code. Or I would need to make sure any PHP time function I use in my code is overridden in my tests... Is there any library available that would do just this ?

I have been looking for a way to change the system time just for a thread. It seems that there is none  [4]. This is a pity: a "simple" PHP function to "Set time to 21st jan 2014 16h15 for this thread" would be a great feature for this kind of tests.

Change the system date and time for the test, using exec(). This can work out if you are not afraid to mess up with other things on the server. And you need to set back the system time after you ran your test. It can do the trick in some situations, but feels quite "hacky".

This looks like a very standard problem to me. However, I still miss a simple an generic way to deal with it. Maybe I missed something ?
    Please share your experience !

NOTE: Here are some other situations where we may have similar testing needs.

Any feature that works with some kind of timeout (e.g. chess game ?)

processing a queue that triggers events at a given time (in the above scenario we could keep going like this: one day before the reservation starts, I want to send a mail to the user with all the details. Test scenario...)

You want to set up a test environment with data collected in the past - you would like to see it like if it was now. [1]

1 https://stackoverflow.com/questions/3271735/simulate-different-server-datetimes-in-php

2 https://stackoverflow.com/questions/4221480/how-to-change-current-time-for-unit-testing-date-functions-in-php

3 http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/

4 https://stackoverflow.com/questions/3923848/change-todays-date-and-time-in-php

5 Unit testing time-bound code

答:
I explored the namespaces option in PHP. Namespaces give us the opportunity to add some testing behavior to the DateTime function. Thus, our original objects stay untouched.

First, we set up a fake DateTime object in our namespace so that we may, in our tests, manage what time is considered to be "now".

Then, in our tests, we can manage this time via the static functions DateTime::set_now($my_time) and DateTime::modify_now("add some time").

First comes a fake Booking Object. This object is what we want to test - observe the use of new DateTime() without parameters in two places. A short overview:

```<code><?php

namespace BookingNamespace;
/**
* Simulate expiration process with two public methods:
*      - book will return a token
*      - confirm will take a token, and return
*                       -> true if called within 5 minutes of corresponding book call
*                       -> false if more than 5 minutes have passed
*/
class MyBookingObject
{
    ...

    private function init_token($token){ $this->tokens[$token] = new DateTime(); }

    ...

    private function has_timed_out(DateTime $booking_time)
    {
            $now = new DateTime();
            ....
    }
}
</code>```

Our DateTime object overriding the core DateTime object looks like this. All function calls remain unchanged. We only "hook" the constructor to simulate our "now is whenever I choose" behavior. Most importantly,

```<code>namespace BookingNamespace;

/**
 * extend DateTime functionalities with static functions so that we are able
 * to define what should be considered to be "now"
 *   - set_now allows to define "now"
 *   - modify_now applies the modify function on what is defined as "now"
 *   - reset is for going back to original DateTime behaviour
 *
 * @author mika
 */
 class DateTime extends \DateTime
 {
     private static $fake_time=null;

     ...

     public function __construct($time = "now", DateTimeZone $timezone = null)
     {
          if($this->is_virtual()&&$this->is_relative_date($time))
          {
           ....
          }
          else
            parent::__construct($time, $timezone);
     }
 }
</code>```

Our tests are then very straightforward. It goes like this with php unit (full version here):

```<code>....
require_once "DateTime.class.php"; // Override DateTime in current namespace
....

class MyBookingObjectTest extends \PHPUnit_Framework_TestCase
{
    ....

    /**
     * Create test subject before test
     */
    protected function setUp()
    {
        ....
        DateTime::set_now("2014-04-02 16:15");
        ....
    }

   ...

    public function testBookAndConfirmThreeMinutesLater()
    {
        $token = $this->booking_object->book();
        DateTime::modify_now("+3 minutes");
        $this->assertTrue($this->booking_object->confirm($token));
    }

    ...
}
</code>```

This structure can be easily reproduced wherever I need to manage "now" manually: I only need to include the new DateTime object, and use its static methods in my tests.

Body:
I explored the namespaces option in PHP. Namespaces give us the opportunity to add some testing behavior to the DateTime function. Thus, our original objects stay untouched.

First, we set up a fake DateTime object in our namespace so that we may, in our tests, manage what time is considered to be "now".

Then, in our tests, we can manage this time via the static functions DateTime::set_now($my_time) and DateTime::modify_now("add some time").

First comes a fake Booking Object. This object is what we want to test - observe the use of new DateTime() without parameters in two places. A short overview:

<?php

namespace BookingNamespace;
/**
* Simulate expiration process with two public methods:
*      - book will return a token
*      - confirm will take a token, and return
*                       -> true if called within 5 minutes of corresponding book call
*                       -> false if more than 5 minutes have passed
*/
class MyBookingObject
{
    ...

    private function init_token($token){ $this->tokens[$token] = new DateTime(); }

    ...

    private function has_timed_out(DateTime $booking_time)
    {
            $now = new DateTime();
            ....
    }
}

Our DateTime object overriding the core DateTime object looks like this. All function calls remain unchanged. We only "hook" the constructor to simulate our "now is whenever I choose" behavior. Most importantly,

namespace BookingNamespace;

/**
 * extend DateTime functionalities with static functions so that we are able
 * to define what should be considered to be "now"
 *   - set_now allows to define "now"
 *   - modify_now applies the modify function on what is defined as "now"
 *   - reset is for going back to original DateTime behaviour
 *
 * @author mika
 */
 class DateTime extends \DateTime
 {
     private static $fake_time=null;

     ...

     public function __construct($time = "now", DateTimeZone $timezone = null)
     {
          if($this->is_virtual()&&$this->is_relative_date($time))
          {
           ....
          }
          else
            parent::__construct($time, $timezone);
     }
 }

Our tests are then very straightforward. It goes like this with php unit (full version here):

....
require_once "DateTime.class.php"; // Override DateTime in current namespace
....

class MyBookingObjectTest extends \PHPUnit_Framework_TestCase
{
    ....

    /**
     * Create test subject before test
     */
    protected function setUp()
    {
        ....
        DateTime::set_now("2014-04-02 16:15");
        ....
    }

   ...

    public function testBookAndConfirmThreeMinutesLater()
    {
        $token = $this->booking_object->book();
        DateTime::modify_now("+3 minutes");
        $this->assertTrue($this->booking_object->confirm($token));
    }

    ...
}

This structure can be easily reproduced wherever I need to manage "now" manually: I only need to include the new DateTime object, and use its static methods in my tests.


问:
Does subtype polymorphism distinguish between inheriting behavior, or inheriting an interface?
To provide some context, I've seen some comments lately that equate inheriting behavior from a supertype, with inheriting a pure interface with no behavior. But there are pretty significant, and different, consequences to each.

e.g. Here's a sample base class, and a "pure" interface (pseudocode):

```<code>class FlyingBird {
    void fly() {
        change state due to flight
    }
}

interface Flyable {
    void fly();
}
</code>```

Now Let's say I have Swan and Dove. I'll subclass Swan from FlyingBird, and have Dove implement Flyable.

```<code>Swan extends FlyingBird {
    (no defnition for fly, because we inherit it from FlyingBird)
}

Dove implements Flyable {
    void fly() {
        ... must provide implementation for fly, because the interface only provides the signature
    }
</code>```

Now, I can call both swan.fly() and dove.fly(), but swan gets its implementation from FlyingBird. The idiom "Favor composition over inheritance" tells me to favor the Dove implementation over Swan, with some sort of injected implementation, but "subtype polymorphism" doesn't seem to make that distinction.

The distinction is important, because, for example:

There's a growing movement in OO to make classes "final" or "non-extendable" by default, because of the complexities of inheriting behavior without breaking the super-classes' semtantics. In other words, some people are suggesting that one form of subtype prototyping should be disabled by default. (I haven't heard anyone suggest getting rid of interfaces in Java.)

"Favor composition over inheritance" differentiates sharing behavior through class inheritance vs. providing a common interface backed by a shared implementation.

In other words, there are practical and important differences between inheriting behavior and just inheriting an interface.

Does subtype polymorphism distinguish between inheriting behavior, or inheriting an interface?

答:
In your example, Flyable and FlyingBird are not related. Therefore there's no real distinction to be made for the compiler, it just sees two completely different objects that happens to each have a fly() method.

If you declare a Flyable variable and call its fly method, no matter what the instance is, it shall be the instance method matching the interface's method that will be called.

If, however, you declare a FlyingBird variable and affect a Swan instance to it, since FlyingBird knows nothing of Flyable then it's the base FlyingBird.fly() method that will be executed.

What might be confusing is if your FlyingBird was implementing Flyable but would still have its own fly method. Logically you would have your Flyable.fly() implementation on the FlyingBird.fly() method so again there wouldn't have a distinction to be made. However, some languages like vb.net allows hiding interface methods behind instance methods named completely differently, that could even be private. Therefore, if a bird variable was of type Flyable and the instance implementation would have renamed the method land(), it is that method that would be called. As little sense as it would make, it's perfectly legal for your class to determine that Flyable.fly() calls should be mapped to the land() method.

If however the variable was of FlyingBird type, then calling bird.fly() will call that exact method regardless of the Flyable interface.

Of course this is marginal because you'd normally never do something like that. Still, it shows how the compiler makes the distinction. An interface-typed variable will call the interface method, while a class-typed variable will call the method as it's defined in the class.