问:
Legal Applications of Metamorphic Code
Firstly, I would like to state that I already understand the 'vx' applications for Metamorphic code. I am not here to ask a question related to any of those topics as that would be inappropriate in this context.

I would like to know if anyone has ever used 'Metamorphic' code in practice, for purposes other than those previously stated, if so, what was the reasoning for using said concept.

In essence I am trying to discover a purpose for this concept, if any, other than circumventing anti-virus scanners and the like.

答:
Optimisation can be done by metamorphism. You could, at least in theory, release a binary that would work on any x86 CPU. When running the program, you'd have a menu item "optimize code for current CPU", which would decompile methods and recompile them in a more efficient manner.

In fact, that's how a JIT compiler works*. Any JITted code could be considered metamorphic, since the code that actually runs isn't in the executable file; it is compiled with optimisations for the specific machine, when it's needed.

* Actually, a JIT compiler doesn't actually decompile a method and rewrites it; the original method is usually just a stub that says "please compile this method from this bytecode representation, then call it" - after the first time it is run the method is replaced with the compiled version.

Title: Legal Applications of Metamorphic Code


问:
Is it good idea to require to commit only working code?
Sometimes I hear people saying something like "All committed code must be working". In some articles people even write descriptions how to create svn or git hooks that compile and test code before commit.

In my company we usually create one branch for a feature, and one programmer usually works in this branch. I often (1 per 100, I think and as I think with good reason) do non-compilable commits. It seems to me that requirement of "always compilable/stable" commits conflicts with the idea of frequent commits. A programmer would rather make one commit in a week than test the whole project's stability/compilability ten times a day. For only compilable code I use tags and some selected branches (trunk etc).

I see these reasons to commit not fully working or not compilable code:

If I develop a new feature, it is hard to make it work writing a few lines of code.

If I am editing a feature, it is again sometimes hard to keep code working every time.

If I am changing some function's prototype or interface, I would also make hundreds of changes, not mechanical changes, but intellectual. Sometimes one of them could cause me to carry out hundreds of commits (but if I want all commits to be stable I should commit 1 time instead of 100).

In all these cases to make stable commits I would make commits containing many-many-many changes and it will be very-very-very hard to find out "What happened in this commit?".

Another aspect of this problem is that compiling code gives no guarantee of proper working.

So is it good idea to require every commit to be stable/compilable?

Does it depends on branching model or CVS?

In your company, is it forbidden to make non compilable commits? Is it (and why) a bad idea to use only selected branches (including trunk) and tags for stable versions?

答:
Q: Is it good idea to require to commit only working code?

A: It depends

You should have at least 3 kinds of branches in your repository (although sometimes 2 of those are the same).

Production : The code residing in a branch destined for production should always work (as in compiles and passes all the tests). Committing stuff that doesn't pass the tests is a grave offense and steps should be taken so that it never happens (daily, hourly, etc. builds with tests). Code should compile and pass tests.

Latest : This branch holds the latest stable code. This is where every new feature should start from and end in. This is also the branch that holds the code that will eventually make its way into the production branch. Code should compile and pass tests.

Feature : Anything can happen in feature branches. You could be in the middle of a big refactoring or writing a lot of new code. You don't want to lose any of that work so you commit often, even stuff that doesn't work. However, if you're working on a feature with multiple people you might want to set up some ground rules such as code should compile or decide that after a certain point, the branch should be stabilized and tests should pass thereafter. Code does not have to compile or pass the tests (unless decided by the team working on the feature).

For the sake of simplicity, I used commit in my text above, but this also applies to the commit/push combo of distributed version control systems.

OwnerDisplayName: Astronavigator

ContentLicense: CC BY-SA 3.0


答:
Sometimes I hear people saying something like "All committed code must
  be working".

That's a fine rule, but it should be applied with some common sense. Rules for what's acceptable to commit should depend on where you're committing the code.

It's common to use a branching strategy that includes some or all of the following:

developer-specific branches

task-specific branches

a main development branch

release candidate branches

testing branches

a production branch

version branches

patch branches

Different people have different ideas about what sort of rules should govern commits, and in any case the rules for a given organization should be spelled out in the organization's SDLC. Still, it seem pretty clear that the rules should be increasingly restrictive as you move from the top of the list to the bottom. So, for example, developers might not be allowed to commit anything at all to types below the main development branch on the list above. Certainly, anything committed to the main development branch should not just compile, but work (i.e. pass all tests).

But what about developer and task branches? It seems obvious that code committed to a task-specific branch shouldn't need to pass all tests. The whole point of a task-specific branch is to provide version control while the task is being completed; if you could only check in "working" code, you might only commit to a task-specific branch once, when you'd finished the task. So, you might make a rule that code committed to task branches should compile, but doesn't necessarily need to pass all tests.

Developer-specific branches should be even less restrictive. Developer branches should be like private work areas where you can try things out. Being able to commit code to a developer branch gives developers the freedom to try things without worrying about losing work. It eliminates most of the risk associated with trying out an idea without knowing ahead of time that it'll work.

In some articles people even write descriptions how to create svn or
  git hooks that compile and test code before commit.

Again, such hooks can be useful for monitoring commits to the main development branch, production branch, etc., but should not be applied to developer branches. A hook like that could be used to automatically indicate whether a given task passes all tests, but it shouldn't prevent a commit.

Title: Is it good idea to require to commit only working code?

Body:
Sometimes I hear people saying something like "All committed code must be working". In some articles people even write descriptions how to create svn or git hooks that compile and test code before commit.

In my company we usually create one branch for a feature, and one programmer usually works in this branch. I often (1 per 100, I think and as I think with good reason) do non-compilable commits. It seems to me that requirement of "always compilable/stable" commits conflicts with the idea of frequent commits. A programmer would rather make one commit in a week than test the whole project's stability/compilability ten times a day. For only compilable code I use tags and some selected branches (trunk etc).

I see these reasons to commit not fully working or not compilable code:

If I develop a new feature, it is hard to make it work writing a few lines of code.

If I am editing a feature, it is again sometimes hard to keep code working every time.

If I am changing some function's prototype or interface, I would also make hundreds of changes, not mechanical changes, but intellectual. Sometimes one of them could cause me to carry out hundreds of commits (but if I want all commits to be stable I should commit 1 time instead of 100).

In all these cases to make stable commits I would make commits containing many-many-many changes and it will be very-very-very hard to find out "What happened in this commit?".

Another aspect of this problem is that compiling code gives no guarantee of proper working.

So is it good idea to require every commit to be stable/compilable?

Does it depends on branching model or CVS?

In your company, is it forbidden to make non compilable commits? Is it (and why) a bad idea to use only selected branches (including trunk) and tags for stable versions?


问:
Killer semi-unique programming language features
When learning a new programming language you sometimes come across a language feature which
makes you wish you had it in your other programming languages that you know.

What are some language feature which were at the time of learning very new to you and that you wish your other programming languages had.

An example of this is generators in Python or C#.
Other examples may include list comprehensions in Python, template in C++ or LINQ in .NET or lazy evaluation in Haskell.

What other semi-unique language features have you come across which were completely new and enlightening to you?  Are there other features of older programming languages which were unique and have fallen out of fashion?

答:
C# Properties

```<code>/// <summary>
/// Get ID
/// </summary>
public int ID
{
    get; set;
}
</code>```

vs

(Java)

```<code>/**
 * Name of user
 */
private String name;

/**
 * Gets name of user
 * @return Name of user
 */
public String getName() {
    return this.name;
}

/**
 * Sets name of user.
 * @param name
 */
public void setName(final String name) {
    this.name = name;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
C# Properties

/// <summary>
/// Get ID
/// </summary>
public int ID
{
    get; set;
}

vs

(Java)

/**
 * Name of user
 */
private String name;

/**
 * Gets name of user
 * @return Name of user
 */
public String getName() {
    return this.name;
}

/**
 * Sets name of user.
 * @param name
 */
public void setName(final String name) {
    this.name = name;
}


答:
I do not agree with the principle: "Commit often (every evening) so you don't lose your work." A version control system is there to store meaningful revisions of your code, not as a backup facility. You can use backups (zip / copy / rsync) to save all your current changes.

I think you should only commit code that compiles. For this: update / merge the current state of the repository, compile locally, commit. The time you spend removing conflicts locally is time that otherwise will be spent by several members of your team when they retrieve your changes. Do not force others to fix your errors, if possible.

You should also try to commit complete features, as it is more difficult to track changes that have been committed at different stages. If you are working on very complex features, consider working in a branch and then merging everything to the main branch in one step.


问:
Write own messaging system vs. utilize existing ones
We are trying to have our own startup, with a middleware application to glue small applications with enterprise legacy systems.

for such middle-ware to function properly, we will need some sort of messaging system to make different components talk to each other in a reliable way.
the alternatives are:

use an existing messaging system, such as 0MQ, jBOSS, WebSphere MQ, etc.

build our own messaging system the way we see the problem

I am more biased towards the later option for the following reasons:

to have more control over our final product

to avoid any licensing problems later on

to learn about messaging while writing the code

to invent something new, that might cost us lots of $$$ if reused an existing system

What would you do if in my shoes?

答:
Since you are a startup I would say it depends on two things.

Do you have any time constraints on this?

Will building your own messaging system give you an advantage?

I don't know what kind of business your startup is in but in general its best to focus on great user experience in the beginning. The code running in the back may be awful but the user will never know that, he'll just notice if the user interface is easy to use.

So given that you have some time constraints, if the messaging system doesn't give you anything that makes a great difference for your application, I would use an existing one.

It's tested, it's used and there is a knowledge base.


答:
Use one of the freely available open source messaging systems. As long as you only use the library using the published API you should not experience any licensing problems.

Also look into using one of the standard APIs like (JMS,AMQ etc) so that you can "hotswap" to any messaging library your customer prefers.

In the "Enterprise" world Websphere MQ is pretty ubiquitous and many large sites have a "if its messaging it must be Websphere" policy so you should at least be compatible if you don't want to lose custom.

Title: Write own messaging system vs. utilize existing ones

Body:
We are trying to have our own startup, with a middleware application to glue small applications with enterprise legacy systems.

for such middle-ware to function properly, we will need some sort of messaging system to make different components talk to each other in a reliable way.
the alternatives are:

use an existing messaging system, such as 0MQ, jBOSS, WebSphere MQ, etc.

build our own messaging system the way we see the problem

I am more biased towards the later option for the following reasons:

to have more control over our final product

to avoid any licensing problems later on

to learn about messaging while writing the code

to invent something new, that might cost us lots of $$$ if reused an existing system

What would you do if in my shoes?


问:
What does 'stage' mean in git?
I find git hard to understand as I could not find the meaning of the words used for the actions. I have checked the dictionary for the meaning of 'stage' and none of the meanings were related to source control concepts.

What does 'stage' mean in the context of git?

答:
Since everyone so far has answered it the "formal" way, let me do this with alternatives to enhance learning with the power of metaphors.

So the staging area is like:

a cache of files that you want to commit

not a series of tubes but actually a dump truck, ready to move the work you load it with, in to the repository

a magical place where selected files will be turned into stone with your wizardry and can be magically transported to the repository at your whim

the yellow brick road for the files to go happily to the repository (or fall off if you want to revert)

the fictional place at the sea port where files are received a pair of cement shoes and then thrown into the repository sea

the receptions desk at the library, you put the files there for the librarian to prepare for filing into the library

a box where you put things in before shoving it under your bed, where your bed is a repository of boxes you've previously have shoved in

the loading bay of files before it goes into the repository warehouse with the power loader

the filter of an electric drip coffee maker, if the files are like the coffee powder, then the committed files are the brewed coffee

the Scrooge McDuck's office next to the vault, the files are like the coins before they go into the vault of his massive Money Bin

the pet store, once you bring a pet home you're committed

It's magical!

Title: What does 'stage' mean in git?


答:
There are plenty of possible applications. For example, evolutionary and genetic programming methods are widely used in practice (and there is a lot of current research as well).

One of the most mundane (and thus practical) applications is generating stress-tests for compilers via mutating a piece of code with the known behaviour into a much larger but still equivalent code.

Title: Legal Applications of Metamorphic Code

Body:
Firstly, I would like to state that I already understand the 'vx' applications for Metamorphic code. I am not here to ask a question related to any of those topics as that would be inappropriate in this context.

I would like to know if anyone has ever used 'Metamorphic' code in practice, for purposes other than those previously stated, if so, what was the reasoning for using said concept.

In essence I am trying to discover a purpose for this concept, if any, other than circumventing anti-virus scanners and the like.


问:
How to fundamentally approach creating a 'financial planner' application?
I want to create a financial planning application (for personal use), for which the overall functionality will be this:

User (me..) can create different 'scenarios'.

Each scenario is configured with different incomings/outgoings.

Scenarios can be 'explored' in a calendar format with projections taking into account tax, interest (on both debt and savings) and so on and so forth.

My problem lies in how to fundamentally approach the project.

I've considered:

When creating incomings/outgoings for a script to apply them to each day in a 'days' table of a database, acting as a method of caching. This means that if I wanted to look at January 14th, 2074 there aren't thousands of cycles of calculations to run through and the result can just be pulled.

Do each calculation dynamically, but again, I'm finding it hard to visuallize how I would handle different tax allowances (I'm based in the UK by the way), payrises and 'changes' to my incomings/outgoings.

I've sat on this for a couple of days and am struggling to come up with an elegant approach to my problem.

There may well be software out there that does what I'm looking to do (in fact I'm sure it is) but I would like to develop this myself for learning purposes, to be able to add it to my personal life 'toolset' and to allow me to expand on it in the future.

Many thanks to all who have any input on my dilemna.

答:
Before starting please check palo bi... İt is a very nice excel integrated solution... İt will inspire you a lot' if you didnt see yet

İ think excel is a better platform for financial stuff,

Your calendar views can be pivot table aggregations maybe?

For small applications
Your every income can be line in excel
Your senarios can be sheets maybe,

But when size increases you will need olap s dimentional approach...

I just wanted to write some abstract thoughts of me...


问:
Where we should put validation for domain model
I still looking best practice for domain model validation. Is that good to put the validation in constructor of domain model ?  my domain model validation example as follows:

```<code>public class Order
 {
    private readonly List<OrderLine> _lineItems;

    public virtual Customer Customer { get; private set; }
    public virtual DateTime OrderDate { get; private set; }
    public virtual decimal OrderTotal { get; private set; }

    public Order (Customer customer)
    {
        if (customer == null)
            throw new  ArgumentException("Customer name must be defined");

        Customer = customer;
        OrderDate = DateTime.Now;
        _lineItems = new List<LineItem>();
    }

    public void AddOderLine //....
    public IEnumerable<OrderLine> AddOderLine { get {return _lineItems;} }
}

public class OrderLine
{
    public virtual Order Order { get; set; }
    public virtual Product Product { get; set; }
    public virtual int Quantity { get; set; }
    public virtual decimal UnitPrice { get; set; }

    public OrderLine(Order order, int quantity, Product product)
    {
        if (order == null)
            throw new  ArgumentException("Order name must be defined");
        if (quantity <= 0)
            throw new  ArgumentException("Quantity must be greater than zero");
        if (product == null)
            throw new  ArgumentException("Product name must be defined");

        Order = order;
        Quantity = quantity;
        Product = product;
    }
}
</code>```

Thanks for all of your suggestion.

答:
There's an interesting article by Martin Fowler on that subject that highlights an aspect most people (including me) tend to overlook:

But one thing that I think constantly trips people up is when they
  think object validity on a context independent way such as an isValid
  method implies.

I think it's much more useful to think of validation as something
  that's bound to a context - typically an action that you want to do.
  Is this order valid to be filled, is this customer valid to check in
  to the hotel. So rather than have methods like isValid have methods
  like isValidForCheckIn.

From this follows that the constructor should not do validation, except perhaps some very basic sanity checking shared by all contexts.

Again from the article:

In About Face Alan Cooper advocated that we shouldn't let our ideas of
  valid states prevent a user from entering (and saving) incomplete
  information. I was reminded by this a few days ago when reading a
  draft of a book that Jimmy Nilsson is working on. He stated a
  principle that you should always be able to save an object, even if it
  has errors in it. While I'm not convinced that this should be an
  absolute rule, I do think people tend to prevent saving more than they
  ought. Thinking about the context for validation may help prevent
  that.


答:
To add to the other excellent answers, here's where the name for "stage" comes from:

I checked the dictionary for the meaning of stage and none of the
  meanings was related to source control concepts.

In English, "to stage" can mean

organize and participate in (a public event): UDF supporters staged a
  demonstration in Sofia

(from http://oxforddictionaries.com/definition/stage )

The name "staging" for the git feature derives from this meaning: When staging, you are preparing and organizing a commit. Of course a commit is not quite the same as a performance, but it is an important event in a VCS :-).

Title: What does 'stage' mean in git?

Body:
I find git hard to understand as I could not find the meaning of the words used for the actions. I have checked the dictionary for the meaning of 'stage' and none of the meanings were related to source control concepts.

What does 'stage' mean in the context of git?


问:
What should be tested in Javascript?
At work, we've just started on a heavily Javascript based application (actually using Coffeescript, but still), of which I've been implementing an automated test system using JsTestDriver and fabric.

We've never written something with this much Javascript, so up until now we've never done any Javascript testing. I'm unsure what exactly we should be testing in our unit tests. We've written JQuery plugins for various things, so it's quite obvious that they should be verified for correctness as much as possible with JsTestDriver, but everyone else in my team seems to think that we should be testing the page level Javascript as well.

I don't think we should be testing page level Javascript as unit tests, but instead using a system like Selenium to verify everything works as expected. My main reasoning for this is that at the moment, page level Javascript tests are guaranteed to fail through JsTestDriver, because they're trying to access elements on the DOM that can't possibly exist.

So, what should be unit tested in Javascript?

答:
Test algorithms. GUI-closely related parts are more depended on specific browser so have to be tested using selenium-like utils.

Your code, of course, must contain algorithms as an isolated pieces of code, if it doesn't then unit testing is almost impossible.

jquery plugins, btw, are not easy unit-testable.

Title: What should be tested in Javascript?


问:
What JavaScript inconsistencies should I look out for?
I remember reading some "funny" examples once of weird results JavaScript can give when you, for example, add strings to numbers etc. Does anyone have any good examples or a link to the blog that I might have read them on? Which ones are likely to catch a programmer out in the real world?</p>

答:
The biggest gotcha in JavaScript is that the == operation performs type type coercion and should almost always be avoided.  Instead you should use the === to do a true boolean comparison.

For example, because of type coercion., 1 == true is true, but 1 === true is false. The == operator often hides type errors.

As a further illustration of true and false in this context these cases From Crockford's The Elements of JavaScript Style are illustrative.

```<code>'' == '0' // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' \t\r\n ' == 0 // true
</code>```

Body:
The biggest gotcha in JavaScript is that the == operation performs type type coercion and should almost always be avoided.  Instead you should use the === to do a true boolean comparison.

For example, because of type coercion., 1 == true is true, but 1 === true is false. The == operator often hides type errors.

As a further illustration of true and false in this context these cases From Crockford's The Elements of JavaScript Style are illustrative.

'' == '0' // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' \t\r\n ' == 0 // true

ContentLicense: CC BY-SA 4.0


问:
The perfect crossfade
I find it hard to describe this problem in words, which is why I made a video (45 seconds) to illustrate it. Here's a preview of the questions, please have a look at it on Vimeo: http://vimeo.com/epologee/perfect-crossfade

The issue of creating a flawless crossfade or dissolve of two images or shapes has been recurring to me in a number of fields over the last decade. First in video editing, then in Flash animation and now in iOS programming. When you start googling it, there are many workarounds to be found, but I really want to solve this without a hack this time.

The summary:

What is the name of the technique or curve to apply in crossfading two semi-transparent, same-colored bitmaps, if you want the resulting transparency to match the original of either one?

Is there a (mathematical) function to calculate the neccessary partial transparency/alpha values during the fade?

Are there programming languages that have these functions as a preset, similar to the ease in, ease out or ease in out functions found in ActionScript or Cocoa?

Update: In addition to the video, I've made a sample project (requires Xcode and iOS SDK) and posted it on github. It shows the same animation as the video but this time with squares: https://github.com/epologee/StackOverflow-Example-Code

答:
You can use the exponential decay function:

```<code>Alpha1(time) = 1 - exp(-time / (0.2 * transitionTime)); // fade in
Alpha2(time) = 1 - Alpha1(time); // fade out
</code>```

Your graph looks more like:

```<code>Alpha1(time) = sin(time * 0.5 * pi / transitionTime); // fade in
Alpha2(time) = cos(time * 0.5 * pi / transitionTime); // fade out
</code>```

Title: The perfect crossfade

Body:
You can use the exponential decay function:

Alpha1(time) = 1 - exp(-time / (0.2 * transitionTime)); // fade in
Alpha2(time) = 1 - Alpha1(time); // fade out

Your graph looks more like:

Alpha1(time) = sin(time * 0.5 * pi / transitionTime); // fade in
Alpha2(time) = cos(time * 0.5 * pi / transitionTime); // fade out


问:
Should a unit/integration test that may result in an infinite loop have a clear assertion?
Unit: A multithreaded unit reads data of a queue and processes it, sending it off to another queue. When the last item is processed (null value found) the process stops.

Test: Place a set of known data in the queue and run. Check that data placed on the output queue is correct.

If the unit is incorrectly programmed, it may continue trying to read and process nulls of the queue. This may or may not result in an exception (using Java as the example language). So this test could conceivably cause an infinite loop.

Should the test keep track of the number of items read off the queue and throw an error if more than the specified number of elements is read? or should the test continue to run, knowing that the runner(human) will see that it is not ending?

答: The test in this case is "For_Given_Input_Output_Is_As_Predicted". The moment the output will never match the prediction (i.e. it exceeds the number of items inserted), you can reliably treat the test as failed. So that is what you should do.</p>


问:
How many are too many interfaces on a class?
I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>

答:
"Too many" is subjective: programming style? performance? conformance to standards? precedents? just plain sense-of-comfort/confidence?

So long as your code behaves right and presents no maintainability issues, 23 could even be the new norm. Someday I could then say, "You can do an excellent piece of work with 23 interfaces, see: Jonas Elfström".


答:
This is fairly generic advice for any problem, but it may help.

Start with the data. Work out what information you'll need to store, how each piece of information relates to the others. If you get the data structure wrong, you can spend an incredible amount of time writing code to "force" it into the correct structure.

Caching is "easy to apply" late in the day, as it's generally adding new tables and memory stores. It's best to get the system working first (proof of concept), then cache the data at the bottlenecks you find during real usage. Otherwise you may find yourself making incredibly complex on-demand caches for data that is only used once in the project's lifetime. (Note that "easy to apply" is dependent on you getting the data right, and encapsulating well. However, these are important anyway.)

Start small. If you look at all the complexities you will go mad. Accountants and Financial Software Companies are paid a lot for a reason. Start with one specific plan to begin with, and work on generalising once you've got that locked down. Working on the small will allow you to detect the actual issues you'll have to deal with when you reach the large, rather than the issues you currently think you'll have to deal with.

Remember this is primarily a self-development project. You're not being pressured to estimate and date, and the penalty for failure is zero. Feel free to experiment and throw away code that doesn't work.

Title: How to fundamentally approach creating a 'financial planner' application?

Body:
I want to create a financial planning application (for personal use), for which the overall functionality will be this:

User (me..) can create different 'scenarios'.

Each scenario is configured with different incomings/outgoings.

Scenarios can be 'explored' in a calendar format with projections taking into account tax, interest (on both debt and savings) and so on and so forth.

My problem lies in how to fundamentally approach the project.

I've considered:

When creating incomings/outgoings for a script to apply them to each day in a 'days' table of a database, acting as a method of caching. This means that if I wanted to look at January 14th, 2074 there aren't thousands of cycles of calculations to run through and the result can just be pulled.

Do each calculation dynamically, but again, I'm finding it hard to visuallize how I would handle different tax allowances (I'm based in the UK by the way), payrises and 'changes' to my incomings/outgoings.

I've sat on this for a couple of days and am struggling to come up with an elegant approach to my problem.

There may well be software out there that does what I'm looking to do (in fact I'm sure it is) but I would like to develop this myself for learning purposes, to be able to add it to my personal life 'toolset' and to allow me to expand on it in the future.

Many thanks to all who have any input on my dilemna.


问:
Can anyone help solve this complex algorithmic problem?
I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations.

You know the amount of gas that each station has.

You know the amount of gas you need to GO from one station to the next one.

Your car starts with 0.

You can only drive clockwise.

The question is: Create an algorithm, to know from which gas station you must start driving so that you complete a full circle.

As an exercise to me, I would translate the algorithm to C#.

答:
It looks like a derivation of the shortest path algorithm, so you basically consider each station to be a vertex of a graph, and the edges are weighted to their distance (in terms of fuel).

Then you can use an adaptation of Dijkstra to solve it -> http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm


问:
Be liberal in what you accept... or not?
[Disclaimer: this question is subjective, but I would prefer getting answers backed by facts and/or reflexions]

I think everyone knows about the Robustness Principle, usually summed up by Postel's Law:

Be conservative in what you send; be liberal in what you accept.

I would agree that for the design of a widespread communication protocol this may make sense (with the goal of allowing easy extension), however I have always thought that its application to HTML / CSS was a total failure, each browser implementing its own silent tweak detection / behavior, making it near impossible to obtain a consistent rendering across multiple browsers.

I do notice though that there the RFC of the TCP protocol deems "Silent Failure" acceptable unless otherwise specified... which is an interesting behavior, to say the least.

There are other examples of the application of this principle throughout the software trade that regularly pop up because they have bitten developpers, from the top off my head:

Javascript semi-colon insertion

C (silent) builtin conversions (which would not be so bad if it did not truncated...)

and there are tools to help implement "smart" behavior:

name matching phonetic algorithms (Double Metaphone)

string distances algorithms (Levenshtein distance)

However I find that this approach, while it may be helpful when dealing with non-technical users or to help users in the process of error recovery, has some drawbacks when applied to the design of library/classes interface:

it is somewhat subjective whether the algorithm guesses "right", and thus it may go against the Principle of Least Astonishment

it makes the implementation more difficult, thus more chances to introduce bugs (violation of YAGNI ?)

it makes the behavior more susceptible to change, as any modification of the "guess" routine may break old programs, nearly excluding refactoring possibilities... from the start!

And this is what led me to the following question:

When designing an interface (library, class, message), do you lean toward the robustness principle or not ?

I myself tend to be quite strict, using extensive input validation on my interfaces, and I was wondering if I was perhaps too strict.

答:
Overapplication of Robustness leads to you guessing what the user wanted, which is fine right up till you get it wrong. It also requires the completely misguided faith that your customers won't abuse your trust and create random gibberish which just happens to work, but that you won't be able to support in version 2.

Overapplication of Correctness leads to you denying your customers the right to make minor errors, which is fine right up until they complain that their stuff works fine on your competitor's product, and tell you what you can do with your 5,000 page standard that has the word "DRAFT" still scrawled on the cover in crayon, and at least 3 experts claim is fundamentally flawed, and 200 more honest experts say they don't fully understand.

My personal solution has always been deprecation. You support them, but tell them they're doing wrong, and (if possible) the easiest path to correctness. That way, when you turn the bug-feature off 10 years down the line, you at least have the paper trail to state that "we warned you this might happen."


问:
Does HTML5 have a feature that enables a user to add an icon to the Apps screen when "installing", and if not, when are they planning to add it?
I know that the mobile bookmark bubble might sort of work for iOS, but it isn't going in the same section.  And for Android, bookmarking is really not going to cut it for a mobile HTML5 application install since users just don't think to go to their bookmarks and that bookmark process takes two or three steps.

To me this issue of getting the application (bookmark) installed pretty much makes the rest of the HTML 5 features aimed at mobile HTML much less useful.  I can't realistically expect users to prefer the bookmark install and launch process over regular apps, so I can realistically expect them to ignore my mobile HTML5 application and use a native app.

The groups behind mobile HTML 5 features do seem to be pushing for HTML 5 apps adoption with things like Application Cache etc.  To me it seems obvious that the bookmark bubble is not going to cut it.  Someone please tell me they have addressed this or at least are working on it?

答:
HTML 5 is not an app language, but rather a webpage language.

You can of course use it as a client side for web apps, however, I think someone would have to write a real app per mobile platform for wrapping the links with an wrapper app that can be installed, or the OS providers could enable pseudo-installing links.


答:
I would say that the limit should be a smaller number than 23 - more like 5 or 7,

however, this does not include any number of interfaces that those interfaces inherit or any number of interfaces implemented by base classes.

(So altogether, N + any number of inherited interfaces, where N <= 7.)

If your class implements too many interfaces, it is probably a god-class.

Title: How many are too many interfaces on a class?

Body: I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>


问:
Is there a language or design pattern that allows the *removal* of object behavior or properties in a class hierarchy?
A well-known shortcoming of traditional class hierarchies is that they are bad when it comes to modeling the real world. As an example, trying to represent animals' species with classes. There are actually several problems when doing that, but one that I never saw a solution to is when a sub-class "loses" a behavior or property that was defined in a super-class, like a penguin not being able to fly (there are probably better examples, but that's the first one that comes to my mind).

On the one hand, you don't want to define, for every property and behavior, some flag that specifies if it is at all present, and check it every time before accessing that behavior or property. You would just like to say that birds can fly, simply and clearly, in the Bird class. But then it would be nice if one could define "exceptions" afterward, without having to use some horrible hacks everywhere. This often happens when a system has been productive for a while. You suddenly find an "exception" that doesn't fit in the original design at all, and you don't want to change a large portion of your code to accommodate it.

So, are there some language or design patterns that can cleanly handle this problem, without requiring major changes to the "super-class", and all the code that uses it? Even if a solution only handles a specific case, several solutions might together form a complete strategy.

After thinking more, I realize I forgot about the Liskov Substitution Principle. That is why you can't do it. Assuming you define "traits/interfaces" for all major "feature groups", you can freely implement traits in different branches of the hierarchy, like the Flying trait could be implemented by Birds, and some special kind of squirrels and fish.

So my question could amount to "How could I un-implement a trait?" If your super-class is a Java Serializable, you have to be one too, even if there is no way for you to serialize your state, for example if you contained a "Socket".

One way to do it is to always define all your traits in pairs from the start: Flying and NotFlying (which would throw UnsupportedOperationException, if not checked against). The Not-trait would not define any new interface, and could be simply checked for. Sounds like a "cheap" solution, in particular if used from the start.

答:
AFAIK all inheritance based languages are built on the Liskov Substitution Principle. Removing/disabling a base class property in a subclass would clearly violate LSP, so I don't think such a possibility is implemented anywhere. The real world is indeed messy, and can't be precisely modeled by mathematical abstractions.

Some languages provide traits or mixins, precisely to deal with such problems in a more flexible manner.


问:
Introducing Programming To a Mathematician
I currently am a programmer, I'm almost 16 years of age and have pretty much narrowed my careers down to something involving a Computer Science degree or Electrical Engineering degree (I know they are quite different but this question is about my friend) but my friend isn't so sure.

He is very interested in maths and is very good at it and I think he would enjoy programming but he isn't willing to try it (edit he is willing to try but has never done before). Can anyone give me an suggestions for a language or tool that he could dabble in programming (at a reasonably basic level I assume) to solve maths problems or involve some kind of maths.

As I say he enjoys maths a lot but I think he would enjoy programming, the problem is I don't want him to be put off by the stuff that isn't relevant at introductory levels such as memory allocation et al. I know that is very important but the point is that I want him to learn a bit of programming with maths then hopefully if he is interested enough he can start learning programming as programming.

Edit:
Its not that he's completely uninterested - more that he hasn't actively explored the area before, maybe because he isn't informed about it. I wouldn't want to force him to do something he doesn't want to, I see this as more of a little push so that he can learn about programming. If he doesn't like it - fair enough, I can't control that and don't want to but if he turns out to enjoy it - this push will have been the right thing.

答:
If your friend enjoys formal logic, and finds Artificial Intelligence interesting, he might like to take a look at Prolog.

With this language, you state your predicates (initial assumptions, "facts") and rules of inference ("relations"), and then ask questions.

Prolog then goes off and works out whether the question can be answered using only the given facts and relations, and if so, tells you the answer.

So you tell it that "tom is a cat" and "all cats are animals" and ask "is tom an animal?" and you'll get the answer "true".

Or you can ask it to "list all the animals that you know about" and you'll get the single item list "tom".

Of course the syntax is a little more complicated than that, but you get the general idea.


问:
How do you make CS students and future programmers aware of the various software licenses and their nuances?
To be specific:

How would you include it as part of curriculum? Would it be too boring to just introduce them as a pure law subject? Are there any course structure available or can we derive one? What are the books that could be used?

I would like to see that - after going through the course - candidate is well aware of "what software licenses are and what they are good for". Various implications of not knowing it in it's proper sense. What licenses they should use for their own code. What to consider when they are trying to use certain libraries or tools in their project and gauge risks/rewards associated with it. The idea is to let them make informed choices when they are professionals/practitioners in field of programming and not make them substitute for a lawyer or even a paralegal who is going to fight the case or draft things.

答:
In my second or third year of undergraduate education, my university offered a new course called Patents and Trade Secrets. Regardless of its name, it was a general intellectual property course geared toward engineers and scientists about various legal concerns that could arise in industry related to patents, trademarks, copyright, and trade secrets. When I took it, there were less than 10 people in the class and over half were enrolled in computer science, software engineering, information technology, or computer engineering. Therefore, parts of the course were tailored to include information relevant to the computing profession, such as patentability of source code and open source software licenses. Note that when I took the course, the university was on a quarter system, meaning the class met for a total of 4 hours a week for 10 weeks.

I think that this is an appropriate approach. Universities should offer an intellectual property course suitable for non-legal professionals in business, science, and engineering with the intent of exposing them to topics that might come up on the job. One of the topics, especially if there are a number of students in the computing field in the course, should be software licenses. I don't know how feasible it is to create an entire course on software licenses, in a 10 week quarter or a 15 week semester schedule, though.


答:
I think you should show your friend some different variants, like:

C

LISP/Scheme

BASIC

bourne-shell

Prolog

I think C and LISP are good starting points, showing that different languages can be better suited for different tasks. I don't believe in using Haskell or Erlang for everything.

Machine code (or assembler) for a simple processor might be interesting too. I have always been happy I started with machine code on my first C64. (MOS 6510) Hands-on experience that is hard to get as an adult with limited time to "waste".

Title: Introducing Programming To a Mathematician

Body:
I currently am a programmer, I'm almost 16 years of age and have pretty much narrowed my careers down to something involving a Computer Science degree or Electrical Engineering degree (I know they are quite different but this question is about my friend) but my friend isn't so sure.

He is very interested in maths and is very good at it and I think he would enjoy programming but he isn't willing to try it (edit he is willing to try but has never done before). Can anyone give me an suggestions for a language or tool that he could dabble in programming (at a reasonably basic level I assume) to solve maths problems or involve some kind of maths.

As I say he enjoys maths a lot but I think he would enjoy programming, the problem is I don't want him to be put off by the stuff that isn't relevant at introductory levels such as memory allocation et al. I know that is very important but the point is that I want him to learn a bit of programming with maths then hopefully if he is interested enough he can start learning programming as programming.

Edit:
Its not that he's completely uninterested - more that he hasn't actively explored the area before, maybe because he isn't informed about it. I wouldn't want to force him to do something he doesn't want to, I see this as more of a little push so that he can learn about programming. If he doesn't like it - fair enough, I can't control that and don't want to but if he turns out to enjoy it - this push will have been the right thing.


答:
First, YES, any language that allows easy object dynamic modification would allow you to do that. In Ruby, for example, you can easily remove a method.

But as Péter Török said, it would violate LSP.

In this part, I'll forget about LSP, and assume that :

Bird is a class with a fly() method

Penguin must inherit from Bird

Penguin can't fly()

I don't care if it is a good design or if it matches real world, as it is the example provided in this question.

You said :

On the one hand, you don't want to define for every property and
  behavior some flag that specifies if it is at all present, and check
  it every time before accessing that behavior or property

It looks like what you want is Python's "asking for forgiveness rather than permission"

Just make your Penguin throw an exception or inherit from a NonFlyingBird class that throws an exception (pseudo code) :

```<code>class Penguin extends Bird {
     function fly():void {
          throw new Exception("Hey, I'm a penguin, I can't fly !");
     }
}
</code>```

By the way, whatever you choose : raising an exception or removing a method, in the end, the following code (supposing that your language supports method removal ) :

```<code>var bird:Bird = new Penguin();
bird.fly();
</code>```

will throw a runtime exception.

Title: Is there a language or design pattern that allows the *removal* of object behavior or properties in a class hierarchy?

Body:
A well-known shortcoming of traditional class hierarchies is that they are bad when it comes to modeling the real world. As an example, trying to represent animals' species with classes. There are actually several problems when doing that, but one that I never saw a solution to is when a sub-class "loses" a behavior or property that was defined in a super-class, like a penguin not being able to fly (there are probably better examples, but that's the first one that comes to my mind).

On the one hand, you don't want to define, for every property and behavior, some flag that specifies if it is at all present, and check it every time before accessing that behavior or property. You would just like to say that birds can fly, simply and clearly, in the Bird class. But then it would be nice if one could define "exceptions" afterward, without having to use some horrible hacks everywhere. This often happens when a system has been productive for a while. You suddenly find an "exception" that doesn't fit in the original design at all, and you don't want to change a large portion of your code to accommodate it.

So, are there some language or design patterns that can cleanly handle this problem, without requiring major changes to the "super-class", and all the code that uses it? Even if a solution only handles a specific case, several solutions might together form a complete strategy.

After thinking more, I realize I forgot about the Liskov Substitution Principle. That is why you can't do it. Assuming you define "traits/interfaces" for all major "feature groups", you can freely implement traits in different branches of the hierarchy, like the Flying trait could be implemented by Birds, and some special kind of squirrels and fish.

So my question could amount to "How could I un-implement a trait?" If your super-class is a Java Serializable, you have to be one too, even if there is no way for you to serialize your state, for example if you contained a "Socket".

One way to do it is to always define all your traits in pairs from the start: Flying and NotFlying (which would throw UnsupportedOperationException, if not checked against). The Not-trait would not define any new interface, and could be simply checked for. Sounds like a "cheap" solution, in particular if used from the start.

Body:
First, YES, any language that allows easy object dynamic modification would allow you to do that. In Ruby, for example, you can easily remove a method.

But as Péter Török said, it would violate LSP.

In this part, I'll forget about LSP, and assume that :

Bird is a class with a fly() method

Penguin must inherit from Bird

Penguin can't fly()

I don't care if it is a good design or if it matches real world, as it is the example provided in this question.

You said :

On the one hand, you don't want to define for every property and
  behavior some flag that specifies if it is at all present, and check
  it every time before accessing that behavior or property

It looks like what you want is Python's "asking for forgiveness rather than permission"

Just make your Penguin throw an exception or inherit from a NonFlyingBird class that throws an exception (pseudo code) :

class Penguin extends Bird {
     function fly():void {
          throw new Exception("Hey, I'm a penguin, I can't fly !");
     }
}

By the way, whatever you choose : raising an exception or removing a method, in the end, the following code (supposing that your language supports method removal ) :

var bird:Bird = new Penguin();
bird.fly();

will throw a runtime exception.


答:
Peter has mentioned the Liskov Substitution Principle, but I feel that needs explaining.

Let q(x) be a property provable about objects x of type T. Then q(y) should be
  provable for objects y of type S where S is a subtype of T.

Thus, if a Bird (object x of type T) can fly (q(x)) then a Penguin (object y of type S) can fly (q(y)), by definition. But that's clearly not the case. There are also other creatures which can fly but aren't of type Bird.

How you deal with this depends on the language. If a language supports multiple inheritance then you should use an abstract class for creatures which can fly; if a language prefers interfaces then that is the solution (and the implementation of fly should be encapsulated rather than inherited); or, if a language supports Duck Typing (no pun intended) then you can just implement a fly method on those classes that can and call it if it's there.

But every property of a superclass should apply to all of its subclasses.

[In response to edit]

Applying a "trait" of CanFly to Bird is no better. It is still suggesting to calling code that all birds can fly.

A trait in the terms you defined it is exactly what Liskov meant when she said "property".


答:
Unfortunately the so called "robustness principle" doesn't lead to robustness. Take HTML as example. Much trouble, tears, waste of time and energy could have been avoided if browsers had strictly parsed HTML from the beginning instead of trying to guess the meaning of malformed content.

The browser should simply have displayed an error message instead of trying to fix it under the covers. That would have forced all the bunglers to fix their mess.

Title: Be liberal in what you accept... or not?

Body:
[Disclaimer: this question is subjective, but I would prefer getting answers backed by facts and/or reflexions]

I think everyone knows about the Robustness Principle, usually summed up by Postel's Law:

Be conservative in what you send; be liberal in what you accept.

I would agree that for the design of a widespread communication protocol this may make sense (with the goal of allowing easy extension), however I have always thought that its application to HTML / CSS was a total failure, each browser implementing its own silent tweak detection / behavior, making it near impossible to obtain a consistent rendering across multiple browsers.

I do notice though that there the RFC of the TCP protocol deems "Silent Failure" acceptable unless otherwise specified... which is an interesting behavior, to say the least.

There are other examples of the application of this principle throughout the software trade that regularly pop up because they have bitten developpers, from the top off my head:

Javascript semi-colon insertion

C (silent) builtin conversions (which would not be so bad if it did not truncated...)

and there are tools to help implement "smart" behavior:

name matching phonetic algorithms (Double Metaphone)

string distances algorithms (Levenshtein distance)

However I find that this approach, while it may be helpful when dealing with non-technical users or to help users in the process of error recovery, has some drawbacks when applied to the design of library/classes interface:

it is somewhat subjective whether the algorithm guesses "right", and thus it may go against the Principle of Least Astonishment

it makes the implementation more difficult, thus more chances to introduce bugs (violation of YAGNI ?)

it makes the behavior more susceptible to change, as any modification of the "guess" routine may break old programs, nearly excluding refactoring possibilities... from the start!

And this is what led me to the following question:

When designing an interface (library, class, message), do you lean toward the robustness principle or not ?

I myself tend to be quite strict, using extensive input validation on my interfaces, and I was wondering if I was perhaps too strict.


问:
What's Microsoft's strategy on Windows CE development?
Lots of specialized mobile devices use Windows CE or Windows Mobile.

I'm not talking about smart phones here -- I know that Windows Phone 7 is Microsoft's current technology of choice here. I'm talking about barcode readers, embedded devices, industry PDAs with specialized hardware, etc... the kind of devices (Example 1, Example 2) where Windows Phone Silverlight development is not an option (no P/Invoke to access the hardware, etc.).

Since direct Compact Framework support has been dropped in Visual Studio 2010, the only option to develop for these device currently is to use outdated development tools (VS 2008), which already start to cause trouble on modern machines (e.g. there's no supported way to make the Windows Mobile Device Emulator's network stack work on Windows 7).

Thus, my question is: What are Microsoft's plans regarding these mobile devices? Will they allow native applications on Windows Phone, such that, for example, barcode reader drivers can be developed that can be accessed in Silverlight applications? Will they re-add "native" Compact Framework support to Visual Studio and just haven't found the time yet? Or will they leave this niche market?

答:
Given my experience with Microsoft I am not sure they know themselves.

Windows Phone 7 is still based on Windows CE (6.5), but the platform is hidden under thick layer of .NET. At work we have a C++ application that was developed for WCE and is now ported to a couple of other platforms, so we also inquired at Microsoft how we could port that application to WP7. The answer was along the lines of "$company did it, so it must be possible. By the way, you need to renew your .NET certification". It seems $company (our competitor) only has (or had at the time; didn't check since) a mock up or demo, not a working product.

I'd really suggest you start looking for some embedded Linux vendor. If you have existing CF code, you should be able to get it working using Mono.


答:
As others have mentioned you would have to go against LSP.

However, it can be argued that a subclass is merely an arbitary extension of a super class. It's a new object in it's own right and the only relation to the super class is that it's used a foundation.

This can make logical sense, rather then saying Penguin is a Bird. Your saying Penguin inherits some subset of behaviour from Bird.

Generally dynamic languages allow you to express this easily, an example using JavaScript follows below:

```<code>var Penguin = Object.create(Bird);
Penguin.fly = undefined;
Penguin.swim = function () { ... };
</code>```

In this particular case, Penguin is actively shadowing the Bird.fly method it inherits by writing a fly property with value undefined to the object.

Now you may say that Penguin cannot be treated as a normal Bird anymore. But as mentioned, in the real world it simply cannot. Because we are modelling Bird as being a flying entity.

The alternative is to not make the broad assumption that Bird's can fly. It would be sensible to have a Bird abstraction which allows all birds to inherit from it, without failure. This means only making assumptions that all subclasses can hold.

Generally the idea of Mixin's apply nicely here. Have a very thin base class, and mix all other behaviour into it.

Example:

```<code>// for some value of Object.make
var Penguin = Object.make(
  /* base class: */ Bird,
  /* mixins: */ Swimmer, ...
);
var Hawk = Object.make(
  /* base class: */ Bird,
  /* mixins: */ Flyer, Carnivore, ...
);
</code>```

If your curious, I have an implementation of Object.make

Addition:

So my question could amount to "How could I un-implement a trait?" If your super-class is a Java Serializable, you have to be one too, even if there is no way for you to serialize your state, for example if you contained a "Socket".

You don't "un-implement" a trait. You simply fix your inheritance hierachy. Either you can fulfill your super classes contract or you shouldn't be pretending your are of that type.

This is where object composition shines.

As an aside, Serializable does not mean everything should be serialized, it only means "state you care about" should be serialized.

You should not be using a "NotX" trait. That's just horrendous code bloat. If a function expects a flying object, it should crash and burn when you give it a mammoth.

Body:
As others have mentioned you would have to go against LSP.

However, it can be argued that a subclass is merely an arbitary extension of a super class. It's a new object in it's own right and the only relation to the super class is that it's used a foundation.

This can make logical sense, rather then saying Penguin is a Bird. Your saying Penguin inherits some subset of behaviour from Bird.

Generally dynamic languages allow you to express this easily, an example using JavaScript follows below:

var Penguin = Object.create(Bird);
Penguin.fly = undefined;
Penguin.swim = function () { ... };

In this particular case, Penguin is actively shadowing the Bird.fly method it inherits by writing a fly property with value undefined to the object.

Now you may say that Penguin cannot be treated as a normal Bird anymore. But as mentioned, in the real world it simply cannot. Because we are modelling Bird as being a flying entity.

The alternative is to not make the broad assumption that Bird's can fly. It would be sensible to have a Bird abstraction which allows all birds to inherit from it, without failure. This means only making assumptions that all subclasses can hold.

Generally the idea of Mixin's apply nicely here. Have a very thin base class, and mix all other behaviour into it.

Example:

// for some value of Object.make
var Penguin = Object.make(
  /* base class: */ Bird,
  /* mixins: */ Swimmer, ...
);
var Hawk = Object.make(
  /* base class: */ Bird,
  /* mixins: */ Flyer, Carnivore, ...
);

If your curious, I have an implementation of Object.make

Addition:

So my question could amount to "How could I un-implement a trait?" If your super-class is a Java Serializable, you have to be one too, even if there is no way for you to serialize your state, for example if you contained a "Socket".

You don't "un-implement" a trait. You simply fix your inheritance hierachy. Either you can fulfill your super classes contract or you shouldn't be pretending your are of that type.

This is where object composition shines.

As an aside, Serializable does not mean everything should be serialized, it only means "state you care about" should be serialized.

You should not be using a "NotX" trait. That's just horrendous code bloat. If a function expects a flying object, it should crash and burn when you give it a mammoth.


答: The typical way to handle such a situation is to throw something like an UnsupportedOperationException (Java) resp. NotImplementedException (C#).


问:
Producer-consumer pattern with consumer restrictions
I have a processing problem that I am thinking is a classic producer-consumer problem with the two added wrinkles that there may be a variable number of producers and there is the restriction that no more than one item per producer may be consumed at any one time.  I will generally have 50-100 producers and as many consumers as CPU cores on the server.  I want to maximize the throughput of the consumers while ensuring that there are never more than one work item in process from any single producer.

This is more complicated than the classic producer-consumer problem which I think assumes a single producer and no restriction on which work items may be in progress at any one time.  I think the problem of multiple producers is relatively easily solved by enqueuing all work items on a single work queue protected by a critical section.

I think the restriction on simultaneously processing work items from any single producer is harder because I cannot think of any solution that does not require each consumer to notify some kind of work dispatcher that a particular work item has been completed so as to lift the restriction on work items from that producer.  In other words, if Consumer2 has just completed WorkItem42 from Producer53, there needs to be some kind of callback or notification from Consumer2 to a work dispatcher to allow the work dispatcher to release the next work item from Producer53 to the next available consumer (whether Consumer2 or otherwise).

Am I overlooking something simple here?  Is there a known pattern for this problem?  I would appreciate any pointers.

答:
It sounds to me like your concurrency issue could be solved by using one queue per producer, where each producer queue refuses to dole out another work item until the previous one has completed. Then you just need each consumer to select fairly from amongst the non-empty producer queues. This should be pretty efficient if all producers generate work items at roughly the same rate and all work items require roughly the same amount of processing by the consumer.

If different producers generate work items at different rates or require different amounts of processing, you may need to change the priority to stop lower rate producers (or those producing higher complexity work units) effectively getting priority over higher rate (or low workload) producers.

One example would be for consumers to select the producer queue with the most items, not just those with no items, unfortunately this could produce other kinds of inefficiencies. How you balance your next work item priorities will thus require tweaking according to the dynamics of the system.


答:
Technically you can do this in pretty much any dynamic/duck typed language (JavaScript, Ruby, Lua, etc.) but it is almost always a really bad idea. Removing methods from a class is a maintenance nightmare, akin to using global variables (ie. you can't tell in one module that the global state hasn't been modified elsewhere).

Good patterns for the problem you described is Decorator or Strategy, designing a component architecture. Basically, rather than removing unneeded behaviors from sub-classes, you build objects by adding the needed behaviors. So to build most birds you'd add the flying component, but don't add that component to your penguins.


答:
Test everything you can.

Pure logic can be tested easily.

If your code interacts with the DOM or the network, it's much harder.

If you can abstract out a piece of code to work on an arbitrary DOM element instead of a specific one, then you can test it more easily. (Make the element to work on a parameter).

Code that uses Ajax can be tested by simply calling the callback function with fixed data. I've had some tests where I overwrote $.ajax with my own function. Just make sure you put the real one back when you're done!

What you'll find is that "page level javascript" really means, "tightly coupled code," and if you decouple the parts of the code, you can test them independently.

(Selenium is not a unit testing tool. It's great for high-level scenarios, but you can't test-drive with it, and it doesn't work in an isolated environment.)

Title: What should be tested in Javascript?

Body:
At work, we've just started on a heavily Javascript based application (actually using Coffeescript, but still), of which I've been implementing an automated test system using JsTestDriver and fabric.

We've never written something with this much Javascript, so up until now we've never done any Javascript testing. I'm unsure what exactly we should be testing in our unit tests. We've written JQuery plugins for various things, so it's quite obvious that they should be verified for correctness as much as possible with JsTestDriver, but everyone else in my team seems to think that we should be testing the page level Javascript as well.

I don't think we should be testing page level Javascript as unit tests, but instead using a system like Selenium to verify everything works as expected. My main reasoning for this is that at the moment, page level Javascript tests are guaranteed to fail through JsTestDriver, because they're trying to access elements on the DOM that can't possibly exist.

So, what should be unit tested in Javascript?


答:
I think the pattern you're looking for is good old polymorphism. While you might be able to remove an interface from a class in some languages, it's probably not a good idea for the reasons given by Péter Török. In any OO language, though, you can override a method to change its behavior, and that includes doing nothing. To borrow your example, you might provide a Penguin::fly() method that does any of the following:

nothing

throws an exception

calls the Penguin::swim() method instead

asserts that the penguin is underwater (they do sort of "fly" through the water)

Properties can be little easier to add and remove if you plan ahead. You can store properties in a map/dictionary/associative array instead of using instance variables. You can use the Factory pattern to produce standard instances of such structures, so a Bird coming from the BirdFactory will always start out with the same set of properties. Objective-C's Key Value Coding is a good example of this sort of thing.

Note: The serious lesson from the comments below is that while overriding to remove a behavior can work, it's not always the best solution. If you find yourself needing to do this in any significant way you should consider that a strong signal that your inheritance graph is flawed. It's not always possible to refactor the classes you inherit from, but when it is that's often the better solution.

Using your Penguin example, one way to refactor would be to separate flying ability from the Bird class. Since not all birds can fly, including a fly() method in Bird was inappropriate and lead directly to the kind of problem you're asking about. So, move the fly() method (and perhaps takeoff() and land()) to an Aviator class or interface (depending on language). This lets you create a FlyingBird class that inherits from both Bird and Aviator (or inherits from Bird and implements Aviator). Penguin can continue to inherit directly from Bird but not Aviator, thus avoiding the problem. Such an arrangement might also make it easy to create classes for other flying things: FlyingFish, FlyingMammal, FlyingMachine, AnnoyingInsect, and so on.


答:
Fly() is in the first example in: Head First Design Patterns for The Strategy Pattern, and this is a good situation as to why you should "Favour composition over inheritance.".

You could mix composition and inheritance by having supertypes of FlyingBird, FlightlessBird that have the correct behaviour injected by a Factory, that the relevant subtypes e.g. Penguin : FlightlessBird get automatically, and anything else really specific gets handled by the Factory as a matter of course.


问:
I want to start using TDD. Any tips for a beginner?
I never used an automated test mechanism in any of my projects and I feel I'm missing a lot. I want to improve myself, so I have to start tackling some issues I've been neglecting like this and trying Git instead of being stuck on SVN.

What's a good way to learn TDD? I'll probably be using Eclipse to program in Java. I've heard of JUnit, but I don't know if there's anything else I should consider.

答:
You could start by working on coding katas.  Pick an algorithm (e.g. decimal-to-Roman numeral conversion, scoring a bowling game, Conway's game of life, etc.) and try to use TDD to work on the solution.

Your solution structure will likely to be very simple (much simpler than your real-world production code): one class for the test fixture and one class containing the algorithm under test.  And the class under test having no dependencies is another plus.  You could use the simplicity of this setup to quickly get the hang of the red-green-refactor loop.

Which tool you use for your TDD katas doesn't really matter as long as you stick to the principles.  However, JUnit plugin for Eclipse is very easy to use, so it's an excellent choice.


问:
How to do thread management in C++?
We use pthread for thread management in C based systems. pthread is in general compilable by C++ compiler (like g++). However, what are the better ways of abstractions for threads in C++?

Also, for making any system to be working in a multi-threaded system, it is also important to make thread safe. What are the standard libraries that requires alternative (installs) to be thread safe or are they unsafe for multi-threaded environments?

Is smart pointers, templates require special measures to make it safe?

What are the best practices for the thread managements in C++?

答:
If you use C++11, threading is part of standard library and components where it makes sense like smart pointers are thread-safe (collections generally require you lock them yourself).

If you are using Boost, have a look at boost.thread. It is base for what was standardized in C++11 (most new things in C++11 come from boost).

Title: How to do thread management in C++?


问:
Which specific practices could be called "software craftsmanship" rather than "software engineering"?
Although not a new idea there seems to have been a big increase in the interest in software craftsmanship over the last couple of years (notably the often recommended book Clean Code's full title is Clean Code: A Handbook of Agile Software Craftsmanship).

Personally I see software craftsmanship as good software engineering with an added interest in ensuring that the end result is a joy to work with (both as an end user and as someone maintaining that software) - and also that its focus is more at the coding level of things than the higher level process things.

To draw an analogy - there were lots of buildings constructed in the 50s and 60s in a very modern style which took very little account of the people who would be living in them or how those buildings would age over time. Many of those buildings rapidly developed into slums or have been demolished long before their expected lifespans. I'm sure most developers with a few years under their belts will have experienced similar codebases.

What are the specific things that a software craftsman might do that a software engineer (possibly a bad one) might not?

答:
The software craftsmanship movement was initiated in reaction to the failures and unsatisfying results of "traditional" software engineering that (along with the carelessness of some developers) today lead to distrust from stakeholders and users towards our profession.

Its goal is twofold : restoring trust in programmers, and in order to do so, raising the bar of software quality and developer skills.

Sw craftsmanship promotes technical practices such as :

SOLID design principles

Design patterns

TDD ("double entry accounting" metaphor)

...

And team/organizational practices :

Pair Programming

Mentoring

Code katas

Dojos / code retreats

...

So I'd say the difference between the 2 is clear : software craftsmanship tries to address a large part of the problems software engineering has had in 40+ years existence which today make our discipline look unreliable and crippled with a history of failures.


问:
Has anyone used Sproutcore?
Has anyone used Sproutcore for a web application? If so, can you give me a description of your experience? I am currently considering it, but I have a few concerns. First, the documentation is bad/incomplete, and I'm afraid that I'll spend lots of time figuring things out or digging through source code. Also, I'm a bit hesitant to use a project that is relatively new and could undergo significant changes.

Any thoughts from people who have developed in Sproutcore are appreciated!

EDIT/PS: Yes, I've seen this post: https://stackoverflow.com/questions/370598/sproutcore-and-cappuccino . However I'm interested in a bit lengthier description of Sproutcore itself from someone who's used it for a significant project.

答:
Just browse through the sproutcore group posts at google groups to get a feel for what's going on.

Some weeks ago someone complained about the docs, being a newbie, and basically what he got was: "if you don't like it, why don't you help create the docs"... well duh!!

You'll see issues like this since it's inception. Also a few weeks ago someone asked the group how to create a hyperlink using Sproutcore. I mean, LOL, it takes hours to create a simple hyperlink apparently.

Sproutcore doesn't advertise who's using their framework in the wild: usually not a good sign.

It is claimed (not by sproutcore itself afaik) that Apple uses it, but if you look closely you'll see that Apple has it's own codebase.

I personally found sproutcore to be riddled with bugs, the lack of a simple tableview annoying, incomplete or non-working examples, and the absence of documentation and even the absence of complete TESTS is just not a good base to build upon.

OwnerDisplayName: Sam Lee

Title: Has anyone used Sproutcore?

OwnerDisplayName: Bradly S


答:
We are using sproutcore more then year.

First I developed using version 0.9 which was excellent but had performance issues, related to KVO, Large datasets etc. But since SproutCore is Javascript (close to javascript) we were able to solve them for our application. For me actually, SproutCore taught me proper way of javascript coding. I was learning Javascript and SproutCore same time.

Somewhere around July they released SproutCore 1.0 pre-alpha. API was changed significantly so converting our application to newer version was a project in itself. And documentation was zero at that time.

Now things are changed, There is documentation and very nice wiki. New tutorials and documentation added each day.

If you thinking to use/evaluate SproutCore this is right time. And each day SproutCore amaze me with capability and power it contains. Still there is lots of rough edges, which reduces everyday.

Some Resources:

SproutCore Wiki

API Docs

Recent addition for data store API (which is very important part)

Title: Has anyone used Sproutcore?

Body:
Has anyone used Sproutcore for a web application? If so, can you give me a description of your experience? I am currently considering it, but I have a few concerns. First, the documentation is bad/incomplete, and I'm afraid that I'll spend lots of time figuring things out or digging through source code. Also, I'm a bit hesitant to use a project that is relatively new and could undergo significant changes.

Any thoughts from people who have developed in Sproutcore are appreciated!

EDIT/PS: Yes, I've seen this post: https://stackoverflow.com/questions/370598/sproutcore-and-cappuccino . However I'm interested in a bit lengthier description of Sproutcore itself from someone who's used it for a significant project.

OwnerDisplayName: nexneo


答:
I am using SproutCore and it is simply great. We switched from jQuery to SproutCore, since jQuery offers a small set of utilities and SproutCore offers a nice high-level architecture.

We evaluated these Javascript libraries in the following order:

Prototype, which felt ok but jQuery has more support and books etc.

jQuery, which felt great but it didn't have any support for a nice high-level architecture and we started to build one, but it took too much time.

Cappuccino, which has a nice high-level architecture but lacks roadmap and documentation

SproutCore THE SOLUTION, since this offers a nice high-level architecture and it has a nice built-in build system

Our top list:

SproutCore is the WINNER

jQuery is a good toolkit

Cappuccino looks promising but is not quite yet there

Prototype is ok, but in my opinion not as good as jQuery

Of course there are more toolkits, but these are the ones we evaluated. As a conclusion I can highly recommend SproutCore to anyone who is building a desktop class applications using Javascript. If you just need some simple Javascript, like date pickers etc., I recommend jQuery.

Just one more tip. At the time of writing this answer the SproutCore 1.0 is the latest stable version. Unfortunately it is quite old and we are using the latest version that can be found from the SproutCore's Github page. I can highly recommend that.

Title: Has anyone used Sproutcore?

OwnerDisplayName: Pekka Mattila


答:
If you are trying to get into SproutCore I recommend that you dig into the SproutTweets sample application.  Many of the more powerful constructs (states, dynamically loaded frameworks, a useful example of a datasource) are in there.

You can find the SproutTweets application on github
http://github.com/sproutit/sproutcore-samples/tree/master/apps/sproutweets/

Also be aware that running the sample in Safari with the web inspector gives a more useful set of error messages.

The sc-server contains a proxy which can be used to access your own REST data source running on a local web server.  Refer to the buildfile in the sprouttweets sample app above to see how that works.

The included proxy in the sc-serve is pretty limited.  If your having issues with your data layer requests give sc-build then deployment on your local web server a try instead of the proxy.  We found issues with our 401 authentication loops and streaming of large dataset responses (chuncked encoding).

Even if you have no intention of using SproutCore in a production application you owe it to yourself to explore it further to see a powerful approach to javascript application programming -- especially the KVO and mixins (aspects) stuff.  Lots of great architecture to ponder and learn from.

Last point -- the IRC channel can be far more helpful than other sources of information, second only to some deep diving in the google group discussions.

Title: Has anyone used Sproutcore?

OwnerDisplayName: Ira Miller


答:
I worked with a company using SC for their flagship app redesign.  Here are my thoughts:

I really like the MVC layout of an SC app. It is something I think other JS frameworks lack.  Their binding framework makes updating views a snap.

The best documentation was in the code itself.

The need better documentation/more examples.  Their examples are enough to get you started, but advanced things will stump most users.

The data access layer is too complicated.  Its a huge mystery.  They need to really shore up documentation or provide more examples to pave the way so people can use it properly.  On the other hand, it seems to be a really powerful almost ORM framework.

I like the fact that they stress testing.

Lack of a grid is a real drag.  Many if not most apps need grids.  That said, SC is a fully featured MVC framework, not a framework of widgets(components) list EXTJS.

A lot of the code seemed overly complex.  Anytime a method gets to be longer than 10-30 lines it should really be broken up to increase readability.

Perhaps the biggest consideration is this:  if you are working a project and considering SC, you are going to have real trouble finding competent developers to work on it.  So it might be good for a small personal project, but you are taking a risk with a large project that will need maintenance.

The IRC support was phenomenal.  The guys on that channel are really helpful.

Title: Has anyone used Sproutcore?

OwnerDisplayName: hvgotcodes


答:
I have used SproutCore in the past.   I was assigned a project to develop automated web testing scripts using the tool called Selenium RC.  Selenium RC was built to target regular HTML id's and classes, but SproutCore compiles the element IDs so that the element IDs are pseudo random, so I had to figure out the API for SproutCore so I could fish out the element IDs from the view tree.

SproutCore has a close analogy to compilers.  If you have too many elements that you're importing creating for your web page, there's a chance you'll have a namespace collision on the IDs if you were to build your application with jQuery.   When you're building your web page with jQuery, all the IDs of HTML elements are globals.  There's no such thing as local scope as in a compiled or interpreted language.

SproutCore ends up managing the HTML content for you.   The views are built up using javascript and then compiled.  If you go through the SproutCore tutorial (and I agree SproutCore is lacking in documentation so you should try to avoid it for a business application), you'll see that your finished project has ID elements of "sc-###".  Namespace collisions become resolved on the website giving you the potential to work faster.

However, there's major concerns.  They documentation doesn't do a good enough job explaining why people should use it.  The project is opensource, but digging your way down to understand the lower level javascript for how the views are built become painful.  Javascript is a functional language, but I just find something wrong with dynamic functional languages.   There's just too much flexibility.   I'm plugging Scala.

The last issue.  SproutCore can be slow.  But it's a price to pay

Title: Has anyone used Sproutcore?

OwnerDisplayName: DetriusXii


问:
Is the term "web portal" obsolete?
My boss uses the term "portal" for the project I work on all the time.

To me, the word makes me think of Yahoo in the late 90s. Does the word "portal" have old-school connotations, or is it just me? Do you think it's ok to use it or will it drag our client's perception of the product down into the middle-ages?

答:
Original meaning of "web portal" was coined in mid-90's based on analogy, that users would enter the virtual world (the web) stepping through the portal. Sounds totally cheesy nowadays, but that was the marketese of the 90's.

Basically that would be kind of site, which user would set as default in the browser and use it to navigate to other sites. At that time most portals would be aggregating all kind of content, and also would provide content directories (one of the last directories to be still alive is ODP (aka DMOZ)).

The problem with directories was that with the Web rapidly growing they couldn't keep up. They've been made obsolete by generic web search.

So really, what killed portals is Google. But on the other hand, google.com kind of fits wider definition of portal. It is a page that many users have set as their default page in the browser, and it is page that they use to navigate to other pages.

Other meanings - by late 1990's "portal" became most abused buzzword, so any startup building any kind of web site would call it "a portal" just to get piece of dot-com rush (which later was known as dot-com bubble).

Title: Is the term "web portal" obsolete?


问:
Are there any good examples of open source C# projects with a large number of refactorings?
I'm doing research into software evolution and C#/.NET, specifically on identifying refactorings from changesets, so I'm looking for a suitable (XP-like) project that may serve as a test subject for extracting refactorings from version control history.

Which open source C# projects have undergone large (number of) refactorings?

Criteria
A suitable project has its change history publicly available, has compilable code at most commits and at least several refactorings applied in the past. It does not have to be well-known, and the code quality or number of bugs is irrelevant. Preferably the code is in a Git or SVN repository.

The result of this research will be a tool that automatically creates informative, concise comments for a changeset. This should improve on the common development practice of just not leaving any comments at all.

答:
Mono.cecil was heavily refactored in the 0.9 version if I am not mistaken. Up to that point it was in .net 1.1

Cecil is an open source project that you can use as an alternative to System.Reflection.
As you can tell from the link the  project's history is publicly available at github.

Since the project doesn't yet have a stable api chances are you'll get to see the changes happening in the future.

Good luck with the tool!


答:
Let me start by mentioning (like everyone else) the Liskov Substitution Principle, which explains why you shouldn't do this. However the issue of what you should do is one of design. In some cases it may not be important that Penguin can't actually fly. Maybe you can have Penguin throw InsufficientWingsException when asked to fly, as long as you are clear in the documentation of Bird::fly() that it may throw that for birds that can't fly. Of have a test to see if it really can fly, though that bloats the interface.

The alternative is to restructure your classes. Let's create class "FlyingCreature" (or better an interface, if you are dealing with the language that allows it). "Bird" doesn't inherit from FlyingCreature, but you can create "FlyingBird" that does. Lark, Vulture and Eagle all inherit from FlyingBird. Penguin doesn't. It just inherits from Bird.

It's a bit more complicated than the naive structure, but it has the advantage of being accurate. You will note that all the expected classes are there (Bird) and the user can usually ignore the 'invented' ones (FlyingCreature) if it is not important whether your creature can fly or not.


问:
Communication Between Different Technologies in a Distributed Application
I had to a incorporate several legacy applications and services in a network-distributed application. The existing services and applications are written using different languages and technologies, including: java, C#.Net and C++; all running on MS Windows machines. Now I'm wondering about the communication mechanism between them. What is the simple and standard way? Thanks! PS. communications include simple message sending and remote method invocations.</p>

答:
You could try using ZeroMQ, a modern, open source library for networked communications that has bindings for C++, .NET, Java and most languages you can think of.

From the ZeroMQ landing page:

```<code>The socket library that acts as a concurrency framework.
 Ø  Faster than TCP, for clustered products and supercomputing.
 Ø  Carries messages across inproc, IPC, TCP, and multicast.
 Ø  Connect N-to-N via fanout, pubsub, pipeline, request-reply.
 Ø  Asynch I/O for scalable multicore message-passing apps.
 Ø  Large and active open source community.
 Ø  30+ languages including C, C++, Java, .NET, Python.
 Ø  Most OSes including Linux, Windows, OS X.
 Ø  LGPL free software with full commercial support from iMatix.
</code>```

ZeroMQ does not specify the format of your messages so you can use whatever serialization you prefer, although you'd want a serialization that was type compatible with .NET/Java/C++.

Body:
You could try using ZeroMQ, a modern, open source library for networked communications that has bindings for C++, .NET, Java and most languages you can think of.

From the ZeroMQ landing page:

The socket library that acts as a concurrency framework.
 Ø  Faster than TCP, for clustered products and supercomputing.
 Ø  Carries messages across inproc, IPC, TCP, and multicast.
 Ø  Connect N-to-N via fanout, pubsub, pipeline, request-reply.
 Ø  Asynch I/O for scalable multicore message-passing apps.
 Ø  Large and active open source community.
 Ø  30+ languages including C, C++, Java, .NET, Python.
 Ø  Most OSes including Linux, Windows, OS X.
 Ø  LGPL free software with full commercial support from iMatix.

ZeroMQ does not specify the format of your messages so you can use whatever serialization you prefer, although you'd want a serialization that was type compatible with .NET/Java/C++.


答:
The Subtext blogging engine is a pretty good example – started life as a very classic ASP.NET app with zero testability and tight data coupling and grew up alot over the course of several years and more than a bit of refactoring all while not breaking legacy access and data models. It is a lot more like many line of business apps .NET developers work on professionally than many of the other examples.

Comparison to criteria:

Publicly available change history: check, see google code SVN.

Several refactorings in the past: yes, most definitely. You can read about the efforts and logic involved in these refactoring effrots on Phil Haack's blog.

Compilable commits: generally yes, they haven't broken the product and jumped on the continuous integration bandwagon relatively early.

Title: Are there any good examples of open source C# projects with a large number of refactorings?

Body:
I'm doing research into software evolution and C#/.NET, specifically on identifying refactorings from changesets, so I'm looking for a suitable (XP-like) project that may serve as a test subject for extracting refactorings from version control history.

Which open source C# projects have undergone large (number of) refactorings?

Criteria
A suitable project has its change history publicly available, has compilable code at most commits and at least several refactorings applied in the past. It does not have to be well-known, and the code quality or number of bugs is irrelevant. Preferably the code is in a Git or SVN repository.

The result of this research will be a tool that automatically creates informative, concise comments for a changeset. This should improve on the common development practice of just not leaving any comments at all.


答:
As someone pointed out above in the comments, penguins are birds, penguins don't fly, ergo not all birds can fly.

So Bird.fly() should not exist or be allowed to not work. I prefer the former.

Having FlyingBird extends Bird have a .fly() method would be correct, of course.


问:
What's wrong with circular references?
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!

答:
When you tie two bits of code together, you effectively have one large piece of code. The difficulty of maintaining a bit of code is at least the square of its size, and possibly higher.

People often look at single class (/function/file/etc.) complexity and forget that you really should be considering the complexity of the smallest separable (encapsulatable) unit. Having a circular dependency increases the size of that unit, possibly invisibly (until you start trying to change file 1 and realize that also requires changes in files 2-127).

Title: What's wrong with circular references?


答:
Isn't the real problem that you're assuming Bird has a Fly method?  Why not:

```<code>class Bird
{
    // features that all birds have
}

class BirdThatCanSwim : Bird
{
    public void Swim() {...};
}

class BirdThatCanFly : Bird
{
    public void Fly() {...};
}

class Penguin : BirdThatCanSwim { }
class Sparrow : BirdThatCanFly { }
</code>```

Now the obvious problem is multiple inheritance (Duck), so what you really need are interfaces:

```<code>interface IBird { }
interface IBirdThatCanSwim : IBird { public void Swim(); }
interface IBirdThatCanFly : IBird { public void Fly(); }
interface IBirdThatCanQuack : IBird { public void Quack(); }

class Duck : BirdThatCanFly, IBirdThatCanSwim, IBirdThatCanQuack
{
    public void Swim() {...};
    public void Quack() {...};
}
</code>```

Body:
Isn't the real problem that you're assuming Bird has a Fly method?  Why not:

class Bird
{
    // features that all birds have
}

class BirdThatCanSwim : Bird
{
    public void Swim() {...};
}

class BirdThatCanFly : Bird
{
    public void Fly() {...};
}

class Penguin : BirdThatCanSwim { }
class Sparrow : BirdThatCanFly { }

Now the obvious problem is multiple inheritance (Duck), so what you really need are interfaces:

interface IBird { }
interface IBirdThatCanSwim : IBird { public void Swim(); }
interface IBirdThatCanFly : IBird { public void Fly(); }
interface IBirdThatCanQuack : IBird { public void Quack(); }

class Duck : BirdThatCanFly, IBirdThatCanSwim, IBirdThatCanQuack
{
    public void Swim() {...};
    public void Quack() {...};
}