答:
I would ask what model of interaction do you need to support?  Does your desired external interface more resemble RPC or REST?  In my experience it's usually somewhere between but mostly one or the other.

Are you consuming your own services for other projects in .Net?  This is probably the single most revealing question you can ask.   WCF does have the advantage of being able to abstract your interfaces into a separate class library and be able to build and inject your client.  As an extension to this, you can mount your WCF based project with both JSON and SOAP/WSDL endpoints, I've done it.  WCF also offers better assurances against your defined interfaces.

That said, if you expect to have clients from other platforms XML in general, let alone SOAP has a measurable overhead beyond what simple JSON endpoints have.  If you go the JSON/Web API route, then you will need to become much better at documenting how to interact with your endpoints and API.

In general, I would suggest writing a simple API document that states how you will submit data, and how you want a response for a single request object structure.  Write your test case in the most universal way, and document it as such.  I'd recommend a simple curl statement.  Then have several of your members implement this using WCF and with Web API.  Then see which wins.

Personally, despite having done some relatively large projects and implementations with WCF, I actually lean towards the simplest implementation which in my mind is actually straight WCF with using JSON results and some override behavior in the Global.asax.cs for dealing with error conditions.  If an API's documentation includes curl statements, and you can exercise all of the functionality of your API with curl examples it becomes much easier for clients to be implemented in any language that supports web interfaces.  This is really where WCF starts to fall down.  Having a well defined API with agnostic documentation is better than having structures with automated tooling when dealing with foreign systems.  Speaking as a consumer of those systems from other platforms.

One thing beyond that, is implement your client in two disparate languages.  Do a client in C#, but also do one in Node.js or Python and see how well they actually fit.  That exercise alone will help you shake out the loose ends in your API.

Title: How do I manage the technical debate over WCF vs. Web API?

Body:
I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.

Team A which supports usage of Web API, brings forward these reasons:

Web API is just the modern way of writing services (Wikipedia)

WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

SOAP is not as readable and handy as JSON

SOAP is an overhead for network compared to JSON (transport over HTTP)

No method overloading

Team B which supports the usage of WCF, says:

WCF supports multiple protocols (via configuration)

WCF supports distributed transactions

Many good examples and success stories exist for WCF (while Web API is still young)

Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.

Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.

What should I do now? How do I manage this debate in a constructive way?


问:
What is the most accepted transaction strategy for microservices
One of the major issues that I have seen occur in a system with microservices is the way transactions work when they span over different services. Within our own architecture, we have been using distributed transactions to resolve this, but they come with their own issues. Especially deadlocks have been a pain so far.

Another option seems to be some kind of custom-made transaction manager, which knows the flows within your system, and will take care of the rollbacks for you as a background process spanning over your entire system (so it will tell the other services to rollback and if they're down, notify them later on).

Is there another, accepted option? Both of these seem to have their disadvantages. The first one could cause deadlocks  and a bunch of other issues, the second one could result in data inconsistency. Are there better options?

答:
As suggested in at least one of the answers here but also elsewhere on the web, it is possible to design one microservice which persists entities together within a normal transaction if you need consistency between the two entities.

But at the same time, you might well have the situation where the entities really do not belong in the same microservice, for example, sales records and order records (when you order something to fulfill the sale). In such cases, you may well require a way to ensure consistency between the two microservices.

Traditionally distributed transactions have been used and in my experience, they work well until they scale to a size where locking becomes an issue. You can relax the locking so that really only the relevant resources (e.g. the item being sold) are "locked" using a state change, but this is where it starts to get tricky because you are entering the territory where you need to build all the logic to do this, yourself, rather than having, say a database handle it for you.

I've worked with companies that have gone down the route of building their own transaction framework for handling this complex issue, but I don't recommend it because it is expensive and takes time to mature.

There are products out there which can be bolted on to your system which take care of consistency. A business process engine is a good example and they typically handle consistency eventually and by using compensation.  Other products work in a similar way. You typically end up with a layer of software near the client(s), which deals with consistency and transactions and calls (micro)services to do the actual business processing. One such product is a generic JCA connector which can be used with Java EE solutions (for transparency: I'm the author). See http://blog.maxant.co.uk/pebble/2015/08/04/1438716480000.html for more details and a deeper discussion of the issues raised here.

Another way of handling transactions and consistency is to wrap a call to a microservice into a call to something transactional like a message queue.  Take the sales record/order record example from above - you could simply let the sales microservice send a message to the order system, which is committed in the same transaction which writes the sale to the database.  The result is an asynchronous solution which scales very well.  Using technologies like web sockets you can even get around the problem of blocking which is often related to scaling up asynchronous solutions.  For more ideas on patterns like this, see another of my articles: http://blog.maxant.co.uk/pebble/2015/08/11/1439322480000.html.

Whichever solution you end up choosing it is important to recognize that only a small part of your system will be writing things that need to be consistent - most access is likely to be read-only.  For that reason, build the transaction management only into the relevant parts of the system, so that it can still scale well.

ContentLicense: CC BY-SA 3.0


问:
How to really master MySQL?
I have been using mysql for the same amount of time I have been using PHP. However I feel about 10x more confident in PHP; or any other programming language. But I just can't seem to really really grasp SQL. I mean, I can select, update, insert, delete, join, etc. but when it comes to more complex stuff I am lost. How to write a more complicated select statement, how to use indexes properly, which engine to use, etc.

For some reason I really find the mysql docs hard to follow, but the php ones easy to follow.

I am starting to think that maybe my brain is just wired in a way that makes programming make since but sql confusing. I don't know. Most people think Regex is so confusing but to me it makes more scientific sense than how to construct an sql statement. Please don't get me wrong, I am not hating on SQL, I really like it, I just want to understand it better.

Whats the best/fastest way to really master MySQL?

When I say "master" I don't mean the guru among gurus, I mean smart enough to figure out most of the questions I ask on SO myself without needing help.

答:
In my opinion to learn SQL (and this is really for what you're asking, MySQL-specifics can come later), you should remove yourself from the control flow of PHP-style programming.  Think specifically in the paradigm of declarative languages:

SQL defines WHAT you want, not how to do it. If you can try mentally removing the latter, the former will follow in time.  Abstract this layer in your mind and let MySQL (or Oracle or whatever) worry about how.

Application logic can occur in SQL vs procedural/OO code in PHP.  For instance when making queries to the database for something, you can consistently join in a user table and maybe a permissions table to ensure the proper rights instead of making multiple pre-queries.  Inserting can be done through a similar selection (insert into ... select ...) instead of named values to ensure data validation.

Anyway, I highly recommend focusing on the Codd primatives and understanding selection, projection, joining, union, and difference.  At the end of the day, the concepts are straight-forward and you can likely accomplish 80% of what you want to do through them.  The rest can follow.

ContentLicense: CC BY-SA 2.5

Title: How to really master MySQL?


问:
Where and how to reference composite MVP components?
I am learning about the MVP (Model-View-Presenter) Passive View flavour of MVC. I intend to expose events from view interfaces rather than using the observer pattern to remove explicit coupling with presenter.

Context: Windows Forms / Client-Side JavaScript.

I am led to believe that the MVP (or indeed MVC in general) pattern can be applied at various levels of a user interface ranging from the main "Window" to an embedded "Text Field". For instance, the model to the text field is probably just a string whereas the model to the "Window" contains application specific view state (like a persons name which resides within the contained text field).

Given a more complex scenario:

Documentation viewer which contains:

TOC navigation pane

Document view

Search pane

Since each of these 4 user interface items are complex and can be reused elsewhere it makes sense to design these using MVP.

Given that each of these user interface items comprises of 3 components; which component should be nested? where? who instantiates them?

Idea #1 - Embed View inside View from Parent View

```<code>public class DocumentationViewer : Form, IDocumentationViewerView {
    public DocumentationViewer() {
        ...

        // Unclear as to how model and presenter are injected...
        TocPane = new TocPaneView();
    }
    protected ITocPaneView TocPane { get; private set; }
}
</code>```

Idea #2 - Embed Presenter inside View from Parent View

```<code>public class DocumentationViewer : Form, IDocumentationViewerView {
    public DocumentationViewer() {
        ...

        // This doesn't seem like view logic...
        var tocPaneModel = new TocPaneModel();
        var tocPaneView = new TocPaneView();
        TocPane = new TocPanePresenter(tocPaneModel, tocPaneView);
    }
    protected TocPanePresenter TocPane { get; private set; }
}
</code>```

Idea #3 - Embed View inside View from Parent Presenter

```<code>public class DocumentationViewer : Form, IDocumentationViewerView {
    ...

    // Part of IDocumentationViewerView:
    public ITocPaneView TocPane { get; set; }
}

public class DocumentationViewerPresenter {
    public DocumentationViewerPresenter(DocumentationViewerModel model, IDocumentationViewerView view) {
        ...

        var tocPaneView = new TocPaneView();
        var tocPaneModel = new TocPaneModel(model.Toc);
        var tocPanePresenter = new TocPanePresenter(tocPaneModel, tocPaneView);
        view.TocPane = tocPaneView;
    }
}
</code>```

Some better idea...

答:
I can't help but feel like you missed an obvious solution. Maybe I'm missing something here, but why doesn't your form implement all three interfaces? I don't see the need to try to keeping trances of the views inside of another view. </p>

```<code>public class DocumentationViewer :
    Form, IDocumentationViewerView, ITocPaneView, ISearchView {

    public DocumentationViewer() {
        var docPresenter = new DocumentPresenter(this);
        var tocPresenter = new TocPresenter(this);
        //...
    }
</code>```

Body:
I can't help but feel like you missed an obvious solution. Maybe I'm missing something here, but why doesn't your form implement all three interfaces? I don't see the need to try to keeping trances of the views inside of another view.

public class DocumentationViewer :
    Form, IDocumentationViewerView, ITocPaneView, ISearchView {

    public DocumentationViewer() {
        var docPresenter = new DocumentPresenter(this);
        var tocPresenter = new TocPresenter(this);
        //...
    }


问:
Starting a Windows task from Linux, what are my options?
We have server that runs data processing tasks, using Python, Django and Celery, on Linux. Once a batch of data comes in, a number of Celery tasks are scheduled and they run, some of them in parallel, some depend on the results of earlier tasks, this all works.

Now we have to implement a new task -- a proprietary Windows-only program needs to be called on some of our data files, resulting in some more files. Only one instance of this program can run at the same time (basically we have to rewrite its config.ini before we can start it each time, and there is only one such .ini). It must run on Windows, can't run under Wine.

Sharing the files is easy, there is a network mount that both sides can talk to.

But I'm not sure what the best way is to start the task from the Linux server, and know that it has finished, that would work nicely with the way we currently do the other tasks.

One option might be to give the Windows machine a tiny webserver, let it listen to a request so it can start up once it receives something, have its use its own Celery or similar, and let it call another URL on the Linux task server once it has finished.

But that seems a bit clunky, do I have better options?

答: The web service approach recommended by @Doc Brown is probably best, but if you don't want to go that route, there are several options for remote command execution from Linux to Windows: Winexe, Cygwin's OpenSSH, and eventually Microsoft's upcoming SSH support.</p>

ContentLicense: CC BY-SA 4.0


问:
Will HTML5/JS Eventually Replace All Client Side Languages?
I'm just wondering about the future of it all. IMHO, there are 4 forces that define where technology goes: Microsoft, Apple, Google, Adobe.

It looks like in Apple's iPhone/iPad iADs can now be programmed in HTML5. So does that mean HTML5 will eventually replace objective-c?

Also, Microsoft has now shifted it's focus from WPF/Silverlight to HTML5 and I assume Visual Studio 2011 will be all about tooling support for HTML5. Because that's what Microsoft do. (Tools). In a few months IE9 the last major browser will support HTML5.

Similarly Adobe is getting on the HTML5 bandwagon and allows to export flash content to HTML5 in their latest tools.

And we all know how much in bed Google is with html5. Heck, their latest Operating System (Chrome OS) is nothing but a big fat web browser.

Apps for Mobile (i.e., iPhone, Android, WM7) are very hard for a company to program especially for many different devices (each with their own language) so I'm assuming this won't last too long. I.e., HTML5 will be the unifying language. Which is somewhat sad for app developers because now users will be able to play the "cool" html5 apps for free on the web and it'll be hard to charge for them.

So are strongly-typed languages really doomed, and in the future, say 5-10 years, will client side programming only be in HTML5? Will all of us become javascript programmers? :) Because the signs are sure pointing that way...

答: Javascript is a very poor programming language. Translation from statically typed programming languages, such as Java with GWT, is becoming increasingly common. Javascript might become the same kind of unifying language as assembler — you can write in it directly, but rarely is it a good idea.</p>

OwnerDisplayName: Shnitzel

LastEditorDisplayName: Shnitzel


问:
Disabling data entry, based on a set of rules
I work on an application that services a large hospital.  The application allows users to create/edit/delete a series of data points that all relate to a specific drug being researched.  Once the data is entered and considered complete, a higher level parent table in the database is tagged with a "Production" status. We can go back to this table to determine what the status of the data is.

What we would like to do now is disable the ability for users to modify the data.  The rule for allowing / disallowing data entry is of course based on the status - if "Production" then we want to disable, otherwise it can be editable.

A few notes:

The application itself is fairly JavaScript heavy, and uses
Backbone.js to GET/POST data via AJAX in many places.

The back end is written in C# and utilizes both Web Api 2 as well as standard MVC 5 controllers.

By disable, we want to hide any Create/Update buttons & disable form inputs on the front end, and restrict access to certain controller methods that are responsible for creating/updating data in the database.

In what areas of the application would the code to restrict the ability to modify data be written?

答:
In the business layer you simply don't honor any update even if it does come from the UI.  I guess you could also do this in the data layer but that does not mean skip it in the business layer.  For that matter you could also enforce it a the database with for example triggers.

In the business layer you expose a flag / property of IsEditable (or some other name).

In the UI layer react to IsEditable properly.  Disable edit if IsEditable = false.


问:
Private method with a derivable argument - a code smell?
We're implementing a service for creating a subscription where the subscription may be linked to an order. Quick background: the purpose of this service is to allow the customer to receive the item she's subscribing to as early as possible. The solution we chose is to create a separate order for the first item before her "real" subscription starts.

Here's a snippet of the service class. I shortened the name of the directive method to remove extraneous details from the snippet:

```<code>class Subscription
  belongs_to :order
end

class SubscriptionCreator
  def call
    # ...
    return directive if directive.is_a?(String)

    # ...

    subscription = create_subscription(order: directive)
    # ...
  end

  private

  def create_subscription(order: nil)
    subscription = Subscription.new

    # ...

    subscription.order = order if order

    subscription.save!

    subscription
  end

  def directive
    # Return values:
    #   * Successful: the order created.
    #   * Error: An error message string.
    #   * Not applicable: nil.
  end
end
</code>```

Here are the main parts of the service:

SubscriptionCreator#call is the entry point.

SubscriptionCreator#directive creates the order if applicable.

SubscriptionCreator#create_subscription creates the subscription and ties it to the order if one was created.

I felt bothered about the order argument of create_subscription since create_subscription can directly call the directive method. So I proposed this change:

```<code>def call
  # ...
  return directive if directive.is_a?(String)

  # ...

  # No longer has order argument.
  subscription = create_subscription
  # ...
end

def create_subscription
  subscription = Subscription.new

  # ...

  subscription.order = directive if directive

  subscription.save!

  subscription
end
</code>```

However, the author of the service prefers the original code. He argues that it's best if create_subscription doesn't know the logic for creating the order, that is, it doesn't know about the directive method. That logic he says should belong in the call method.

He argues that with the original code, it would be easier to move create_subscription somewhere else because it would contain no domain specific logic. He adds that keeping the lower level layers free from domain logic would make methods more modular and therefore more reusable and easier to extract.

On my part, I think that removing the argument ensures that create_subscription only has one source of information for the created order. In the original code, there's the risk that the order passed to create_subscription is not the same as the result of directive.

So, what are the consequences of keeping/removing the argument from the private method?

答:
Your Subscription is associated with 0 or 1 Orders. Where those Orders come from doesn't matter to the Subscription, so passing an Order to create_subscription seems reasonable.

In the first snippet, the business of retrieving or creating the appropriate Order is separated from the business of creating the Subscription. In the second, retrieving/creating the Order is embedded in creating a Subscription, and I don't see what you gain by that. If anything, it makes the code harder to change: what if you change the way you retrieve Orders, and what if there were more than one way to retrieve an Order?

The first snippet separates the Order-retrieval business from the Subscription-creation business, and that separation of concerns would make the code easier to maintain, I think.


问:
Developing an Android application while dogfooding it
I started learning Java and Android development recently, and I'm learning by building a small app for myself. Nothing fancy, it's just a simple mileage tracker for my car. I know there are tons of them available, but I figured it would be an easy app to learn on.

Anyway, I've reached a point now where I want to dogfood the app, but I want to do it while also adding new features to it. Problem is, the app is using an SQLite database, and when I test new features I have to add / edit / remove records, but I also want to keep these records, since I'm creating them by actually using the app in my day to day life.

How do you usually approach this situation? I figured I have two options:

Dogfood a stable branch/tag of the application, and create a new application from the development branches. Basically I would have two apps, the stable version which I'm currently using, and the development instance, where I can hack and slash as I please.

Use two SQLite databases in the same app, and implement a simple switch between them.

How do you handle this situation?

答:
You can use Gradle build flavors to create two APK files from the same code base.

The two APK files would have different package name. Different package name means they can be installed on the same phone side by side & they will have different local databases.

```<code>productFlavors {
    vanilla {
        packageName "com.example.myapp"
    }

    strawberry {
        packageName "com.example.myapp.dev"
    }
}
</code>```

You can find more information about product flavors and overriding resources in this blog post.

Body:
You can use Gradle build flavors to create two APK files from the same code base.

The two APK files would have different package name. Different package name means they can be installed on the same phone side by side & they will have different local databases.

productFlavors {
    vanilla {
        packageName "com.example.myapp"
    }

    strawberry {
        packageName "com.example.myapp.dev"
    }
}

You can find more information about product flavors and overriding resources in this blog post.


问:
Copying and modifying code from project licensed with BSD-2?
I'm using a library that is licensed under a BSD-2 like license and I am wanting to override one of the methods they use and modify it slightly.

My question is, when I copy the code from the method what do I need to include in the comments for said method? Do I have to go all out and include the whole license there or can I input something more simple?

This is the license they have at the top of all the library files:

```<code>//  Copyright (c) 2008-9, the Phantom Inker.  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions
//  are met:
//
//    * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in
//       the documentation and/or other materials provided with the
//       distribution.
//
//  THIS SOFTWARE IS PROVIDED BY THE PHANTOM INKER "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
//  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
//  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
//  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</code>```

答:
Short answer: Yes. You do need to include the entire BSD "license comment" in any and all of your source distributions which contain Mr. Phantom Inker's code or modified versions thereof. This is one of the very few conditions the license imposes on you:

```<code>//    * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
</code>```

The comment as you've pasted it appears to consist of a copyright notice, a list of conditions and then a disclaimer, so all of that must be "retained" in your version.

Also, when you modify someone else's code it's best to add an additional comment saying that you modified it and the original version had so-and-so license, not because any license requires you to, but simply because it makes it clear what's going on. So you should actually have a longer comment block than the original code did.

The good news--if you were worried about this wall of text being an eyesore in your code--is that you do not necessarily have to include this comment block right on top of or in the middle of that particular method, as long as you make it sufficiently obvious what it is referring to. I would personally put all this licensing stuff at the top of the file, make sure your additional comment says something like "The code for method foo() was taken from Phantom Maker's FooLib v1.2 and modified by Brett. The FooLib v1.2 copyright notice is as follows: ", then on the actual method in question have a single line comment saying something like "For licensing information pertaining to this method, see the comments at the top of this file."

Body:
Short answer: Yes. You do need to include the entire BSD "license comment" in any and all of your source distributions which contain Mr. Phantom Inker's code or modified versions thereof. This is one of the very few conditions the license imposes on you:

//    * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.

The comment as you've pasted it appears to consist of a copyright notice, a list of conditions and then a disclaimer, so all of that must be "retained" in your version.

Also, when you modify someone else's code it's best to add an additional comment saying that you modified it and the original version had so-and-so license, not because any license requires you to, but simply because it makes it clear what's going on. So you should actually have a longer comment block than the original code did.

The good news--if you were worried about this wall of text being an eyesore in your code--is that you do not necessarily have to include this comment block right on top of or in the middle of that particular method, as long as you make it sufficiently obvious what it is referring to. I would personally put all this licensing stuff at the top of the file, make sure your additional comment says something like "The code for method foo() was taken from Phantom Maker's FooLib v1.2 and modified by Brett. The FooLib v1.2 copyright notice is as follows: ", then on the actual method in question have a single line comment saying something like "For licensing information pertaining to this method, see the comments at the top of this file."


问:
COCOMO II SLOC count for web application development
What type of SLOC do you take into account for estimating web application development projects with COCOMO II?

For instance, suppose you have to estimate a web application project that will probably result in those SLOC counts, based on what you know about similar previous projects:

Python (back-end REST API) - 10'000 SLOC

JavaScript (front-end single page app) - 12'000 SLOC

HandleBars (templating) - 8'000 SLOC

SASS (css preprocessing) - 3'000 SLOC

JSON/XML/YAML (data and configuration) - 1'000 SLOC

YAML (server deployment recipes and tasks) - 1'000 SLOC

Would you only enter Python and JS SLOC or would you take everything into account?

答:
You include every line of code and configuration that took you time to write.  It is doubtful that the 1 kSLOC of JSON and XML appeared out of thin air.  If you fail to do this, you will underestimate the amount of effort to create the product.

On the other hand, it is likely the case that writing 1 kSLOC of JSON will take a different amount of time than writing 1 kSLOC of Python or Javascript.  For that matter, it is also likely that 1 kSLOC of Python is different than 1 kSLOC of JavaScript.

You will need to keep track of how much time is spent generating the code for those other technologies and figure out what their SLOC to time conversion is. It is unlikely to be exactly the same as JavaScript or Python, but thats a starting spot for developing an estimate (just make sure you give enough uncertainty in the estimate to account for it).


问:
How To Know When To Stop Testing?
I know this is a very very basic question. For some software applications there are a large almost infinitely high number of test cases for an application. It is not practical to test all those test cases. How do we decide when to stop testing? (other than "when money runs out"). </p>

答:
Glenford Myers's book The Art of Software Testing has a simple but well principled rule for this: Testing is complete when you have stopped finding bugs. Or, more practically, when the rate at which you find new bugs greatly slows down.

Bugs tend to "cluster" in certain modules and certain functions: The moment you find a bug in one, you know that you should look in it further for more bugs. To find bugs, you can use the techniques of blackbox testing, whitebox testing, and mutation testing. As long as you are finding bugs, you know that your testing process is working!

To visualize your progress, chart the number of bugs your team has found per day. If the chart slopes down, then you know the techniques your team is using aren't going to find them anyway. Of course, if you believe your techniques aren't up to par, then please read Myers's book an apply the principles.

Now, there is a chance that you might just be short of missing a new patch of bugs, and the rate of finding bugs would have greatly increased had you continued testing for a little bit more. However, if you believe your techniques are sound, this is unlikely.

Title: How To Know When To Stop Testing?


问:
Will an assembly language book for intel x86 processor be compatible with amd processors?
I'm wanting to get an assembly book to learn assembly, and was wandering if i get a book for intel x86 processor will there be any problems assembling the code on an amd processor?</p>

答:
You will mostly have the same instructions.

There is an instruction named "CPUID" which lets you among other things identify the processor. Obviously it will give different results on AMD and Intel CPUs. And once you know which processor you have, you need to follow the instructions in AMD and Intel manuals separately to get more information about the processor.

Each processor has a different set of features (for example MMX, SSE, SSE2, SSE3 and so on), and you use the CPUID instruction to find what features are available. Once a feature is available, it is the same on all processors. Some instructions were only ever available on one processor; those instructions are usually not used by anybody.


问:
Is using a lot of free third party libraries a good thing?
For your proprietary projects at work?

Problems I can imagine are: more dlls (can be a problem when for example you have to include a big DLL but you only need few functions in that library), a lot of license statements you have to take care of when releasing your product, the reliability of the library, etc.

Any other potential problems? What is your opinion?
(info: I'm using .NET at work)

答: IMO third party libraries are very good thing, but I have a rule that can use only libraries that have source code. On my previous job we used Delphi and that policy saved our butts so many times since many Delphi 3rd party vendors went out of the business, you never know.</p>


问:
How imperative is the need of specifications being written down in case of a new project?
I have a new project to deal with. I'm the only one to deal with it currently (a kind of a personal project). It's likely that in the future there will be more contributors to it.

Taking in account the best practices when it comes to talk about project management, how much is there a need for the project specifications to be written down? Is it imperative, or is it something that is left to the choice of development team?

N.B. By specifications I mean the set of guidelines that a developer uses in order to get implemented the targeted object of project involved.

Note: I'm not asking about subjective choices (although such examples are well appreciated). I'm asking about some theoretical aspects, if there are any, regarding this issue.

答:
As @Tracker1 already mentioned it depends.

The most important thing is managing expectations. Let me explain...

In a standard software project you follow some kind of a software life-cycle process. The main steps or phases are: requirements gathering, planning, development, maintenance and obsoleting.

In all of these steps there are stake-holders involved and it is their expectations that determine what you must do and how detailed and to what extend you have to document each step in the process and which steps are needed.

That includes, what you call specifications, but what is more commonly know as requirements. From the requirements follow the architecture and the design of the software.

It is important to find out the expectations of your stake-holders. These are the people that are going to use the software; that are going to pay for the development of the software; that will have to market and sell the software; QA (Quality Assurance) will be interested in safety and regulatory aspects of your software; the IT department will be interested in what  hardware, software packages and development environment you would like to use, etc.

Out of these expectations should come a 'contract' that records the requirements and how to verify that the requirements have been met. This can range from a simple, one-page document to a large number of lengthy documents nailing down every possible detail.

This 'contract' is very important to prevent discussions and arguments at a later stage. It lists what is included and, very important, what is not included and what is required for the project to succeed. It also lists the responsibilities of each party involved. It should also include a time-frame and a budget (not only money but also resources).

Where I work, we make medical devices containing medical software, so we have very strict rules around what we must do and what we must document.

For instance, if we want to sell our products in the U.S., we have to comply with IEC 652304. We are audited by the FDA every few years to ensure that we actually do what we say we do ;-)


问:
Hard-copy approaches to time tracking
I have a problem: I suck at tracking time-on-task for specific feature/defects/etc while coding them.  I tend to jump between tasks a fair bit (partly due to the inherit juggling required by professional software development, partly due to my personal tendancy to focus on the code itself and not the business process around code).

My personal preference is for a hard-copy system.  Even with gabillions of pixels of real-estate on-screen I find it terribly distracting to keep a tracking window convienient; either I forget about it or it gets in my ways.

So, looking for suggestions on time-tracking.  My only requirement is a simple system to track start/stop times per task.  I've considered going as far as buying a time-clock and giving each ticket a dedicated time-card.  When I start working on it, punch-in; when done working, punch-out.

答:
This is not a "hardcopy" solution, but I think it would be exactly what you need: It won't take pixels away from you, but it can help give you a realistic idea of what you've been up to.

You can implement this yourself or use a package like TimeSnapper or RescueTime. Set up a program to take a random snapshot of your screen. For example, it might take one every 7 to 12 minutes; it's important that it's random so you don't try to synchronize with it. Then, at the end of the day--or week-- look at the screen shots (around 48 or so) and see what you were up to.

This technique also works surprisingly well if you randomly go between tasks frequently. Over a long enough time period, you're still getting a very realistic picture of what you're up to.

Warning! If you do this, you might find out how much time you spend on StackExchange!

Title: Hard-copy approaches to time tracking


问:
How do you avoid dominant solutions in multi-objective simulated annealing?
Imagine an RPG game were you can cary N items, and you want to maximise your damage, attack speed and armour, given a set of items.

I implemented simulated annealing where a permutation simply replaces a random item, and I compute the energy with some damage calculations.

This works well for attack speed and damage, and tends to find items that provide both. But adding armour never gives good results.

I have tried a weighted sum, but the result is always N armour items or N weapons.

This paper suggests picking a random or average energy function, but this gives very bad results as soon as I use conflicting objectives.

Are there good probability functions for this task, or should I use another algorithm?

答:
You say "maximise your damage, attack speed and armour".  I think the answer to your question is to accurately define what this means.

You can only "maximise" a single value. If you have multiple values you need to provide a function to turn them into this single value you want to maximise.

What makes a "good" function for this is entirely application specific. When you say "random or average energy functions" gives bad results - what makes these results bad?

I think you end up a bit stuck if you say you want to "maximise" something and then say you also want to exclude certain types of solutions which do maximise that thing. So the key is to combine your values in a way that actually matches what you want to achieve rather than try to predetermine what outcomes are valid in the first place - if that makes sense!?

EDIT: If you took all your 3 values and normalised them to the range [0, 1] and then pass these into a quadratic function (e.g. 4x - 4x^2) and add the results then you are reducing the value of higher inputs (i.e. 1 maps to 0), so you are more likely to get solutions that combine inputs around (0.5).

But as mentioned all you're really doing here is picking a function to produce an output. What you should do is pick the function based on the "real world problem" - i.e. how the relative inputs of attack speed, armour etc perform in the game.


问:
Track Bug fixes in code
I am working in a project in which at many point I need to change the code and fix the bug of the system but how can I inform other team members about this change? Usually I add single line comment to that particular point or create task in eclipse and write bug fix as follows,

```<code>//Fixed PRJ110-345 called checkAndClear to clear myObject
myObject = myObject.checkAndClear();
</code>```

But this does not look good when I change something in properties or sql file of the project.

Moreover I need to search for this PRJ110-345 to find the bug fixed or use regular expression to find all issue number but those might have solved by other team member.

What is the best way to keep track of issues in the code among the team member ?

Sometimes I can not differentiate between my solved bugs and other team member's bug fix. Currently we don't have different accounts for issue tracking system (JIRA) and team leader just distributes the Bugs among team member and it's difficult for me to track my fixes every time.

答:
If you try to record the fixes in code, you'll end up with a mess of comments over time that will leave the code unreadable.

As a minimum, you could record the Jira number - PRJ110-345 - in the comment when checking your code in to eg git, or whichever source control solution you are using.

Another option in to use Stash and link that to Jira. That way, your changes show up in Jira.

Arguably the best solution though is to create a new branch for each issue. That way all changes related to PRJ110-345 get stored in a PRJ110-345 branch. When complete, merge back to master. That way you have a complete record of all changes accessible by just examining the history of the branch.

Title: Track Bug fixes in code


答:
Giving every line of source code a reference to all the tickets that affected it is not feasible. That's simply too much information, and most of it will be outdated soon after you write it. These kinds of comments are valuable, but they should be commit comments in your version control system, rather than code comments in your source files.

But if I'm reading your post correctly:

I am working in a project in which at many point I need to change the
  code and fix the bug of the system but how can I inform other team
  members about this change?

It sounds like your real concern is how to ensure that the rest of your team will know why this line of code is the way it is the next time they read it. In other words, how to make the code readable. There are usually other ways of accomplishing this which do scale better.

If clearing these objects is a normal thing, and everyone on the team is familiar with the concept of checkAndClear(), simply make the code a bit more self-documenting:

```<code>checkedObject = uncheckedObject.checkAndClear();
</code>```

Most of the time, this sort of thing should be enough.

If this is an unusual thing that requires some kind of explanation, then in addition to being self-documenting, leave a comment explaining the real issue:

```<code>// Normally we don't need to clear these objects manually, but this one
// comes from Foo.lib which sometimes returns garbage values
checkedObject = uncheckedObject.checkAndClear();
</code>```

I would only leave an explicit reference to a ticket in the code if we are expecting some future change to the code, and the ticket is about making that change happen:

```<code>// TODO: refactor Foo.lib to stop returning garbage values (PRJ1234)
</code>```

This prevents anyone from opening a duplicate ticket, or duplicating any of the work that's already being done for that ticket, and the bug tracker is more likely to have additional information if anyone has done some work on it.

Title: Track Bug fixes in code

Body:
I am working in a project in which at many point I need to change the code and fix the bug of the system but how can I inform other team members about this change? Usually I add single line comment to that particular point or create task in eclipse and write bug fix as follows,

```<code>//Fixed PRJ110-345 called checkAndClear to clear myObject
myObject = myObject.checkAndClear();
</code>```

But this does not look good when I change something in properties or sql file of the project.

Moreover I need to search for this PRJ110-345 to find the bug fixed or use regular expression to find all issue number but those might have solved by other team member.

What is the best way to keep track of issues in the code among the team member ?

Sometimes I can not differentiate between my solved bugs and other team member's bug fix. Currently we don't have different accounts for issue tracking system (JIRA) and team leader just distributes the Bugs among team member and it's difficult for me to track my fixes every time.

Body:
Giving every line of source code a reference to all the tickets that affected it is not feasible. That's simply too much information, and most of it will be outdated soon after you write it. These kinds of comments are valuable, but they should be commit comments in your version control system, rather than code comments in your source files.

But if I'm reading your post correctly:

I am working in a project in which at many point I need to change the
  code and fix the bug of the system but how can I inform other team
  members about this change?

It sounds like your real concern is how to ensure that the rest of your team will know why this line of code is the way it is the next time they read it. In other words, how to make the code readable. There are usually other ways of accomplishing this which do scale better.

If clearing these objects is a normal thing, and everyone on the team is familiar with the concept of checkAndClear(), simply make the code a bit more self-documenting:

checkedObject = uncheckedObject.checkAndClear();

Most of the time, this sort of thing should be enough.

If this is an unusual thing that requires some kind of explanation, then in addition to being self-documenting, leave a comment explaining the real issue:

// Normally we don't need to clear these objects manually, but this one
// comes from Foo.lib which sometimes returns garbage values
checkedObject = uncheckedObject.checkAndClear();

I would only leave an explicit reference to a ticket in the code if we are expecting some future change to the code, and the ticket is about making that change happen:

// TODO: refactor Foo.lib to stop returning garbage values (PRJ1234)

This prevents anyone from opening a duplicate ticket, or duplicating any of the work that's already being done for that ticket, and the bug tracker is more likely to have additional information if anyone has done some work on it.


答:
You shouldn't track bug fixes in the code. It might make sense to track some unfixed bugs in the code, as a warning to other developers that look at that code that it has bugs that you didn't get around to fixing it. Something like:

```<code>//Currently crashes - see PRJ110-345
myObject.initialize();
</code>```

But noting in the code that the bug has been fixed is pointless, because the bug is something that shouldn't have been part of the code in the first place - why documenting something that isn't there and shouldn't be there? I can easily introduce new bugs to your code by randomly typing commands into it - for example I can set myObject to null at random places. Are you going to document on every line why myObject isn't set to null on that line?

The place to put these comments is in the source control - and it sounds like you are not using source control, so you should start using one - I suggest Git. A source control (among other things it does) represents the history of your project as commits - each commit is a diff that (together with previous commits) describes how the code looked before the change and how it looks after the change, and allows you to enter a commit message that describes the change - what you did and/or why. This is where you document the bug fix.

So, instead of looking at comments in the code you look at commit messages and see what your teammates did - here is how it looks in on BitBucket. That way, your code stays clean but you still get access to all the info.

Title: Track Bug fixes in code

Body:
You shouldn't track bug fixes in the code. It might make sense to track some unfixed bugs in the code, as a warning to other developers that look at that code that it has bugs that you didn't get around to fixing it. Something like:

//Currently crashes - see PRJ110-345
myObject.initialize();

But noting in the code that the bug has been fixed is pointless, because the bug is something that shouldn't have been part of the code in the first place - why documenting something that isn't there and shouldn't be there? I can easily introduce new bugs to your code by randomly typing commands into it - for example I can set myObject to null at random places. Are you going to document on every line why myObject isn't set to null on that line?

The place to put these comments is in the source control - and it sounds like you are not using source control, so you should start using one - I suggest Git. A source control (among other things it does) represents the history of your project as commits - each commit is a diff that (together with previous commits) describes how the code looked before the change and how it looks after the change, and allows you to enter a commit message that describes the change - what you did and/or why. This is where you document the bug fix.

So, instead of looking at comments in the code you look at commit messages and see what your teammates did - here is how it looks in on BitBucket. That way, your code stays clean but you still get access to all the info.


问:
Genesis of C++ temporary object lifetime extension
I'm revising a proposal to expand the C++ feature where "temporary" objects cease to be temporary when attached to a name by binding a reference. Here's a sample of the classic behavior (not the proposal):

```<code>int && i = 3 + 3; // Calculate 3+3 and give a name to the result.
int j = 3 + 3; // Create a named variable, calculate 3 + 3, and copy the result in.

// Similar outcomes, but not exactly the same when using more complex types:

struct haz_int {
    int member;
    ~ haz_int() { std::cout << "No haz!\n"; }
};
int value = has_int{ 3 }.member; // Create a haz_int, copy its member out.
int && value = haz_int{ 3 }.member; // Retain entire haz_int and name its member.
</code>```

Who invented temporary lifetime extension, and why? D&E, the 1994 retrospective by language inventor Stroustrup, doesn't mention it in its section on the topic. According to D&E, the lifetime of temporary objects was contentious during the early standardization process, so it's a little surprising it was reopened and tweaked. On the other hand, it's possible that he neglected to mention it as a minor detail. This seems doubtful though because his stated purpose in that section is:

I will present two issues, name lookup and lifetime of temporaries, to illustrate the difficult and detailed work done. The majority of the committee's efforts are expended on such issues.

The earliest working draft of the standard posted on the ISO working group site, from September 1993, says (§8.4.3 References),

… if and only if the reference is to a const and an object of type T can be created from the initializer, such an object will be created. The reference then becomes a name for that object.

…

The lifetime of a temporary object created in this way is the scope in which it is created (3.5). Note that a reference to a class B can be initialized by an object of a class D provided B is an accessible and unambiguous base class of D (in that case a D is a B); see 4.7.

Update:

The proposal paper archives go back further. From July 1993, N0305 by Dag Brück is very similar to Stroustrup's summary of the debate in D&E. It mentions:

Also note that a reference may be bound to a temporary, in which case the temporary has the lifetime of the enclosing scope, see Section 8.4.3 of the Working Paper.

So, apparently the lifetime extension rule predates the general rule for the lifetime of temporaries!

答:
N0345 Lifetime of temporaries explicitly bound to references, by John Bruns and from September 1993, is what fleshed out the details of lifetime extension.

The paper briefly mentions a motivation for the preexisting, simpler form of lifetime extension, which is to avoid copying class objects. It also mentions reliably letting function arguments be refactored into named objects.

It proposes a stronger rule than the one ultimately adopted:

For any statement explicitly binding a reference to a temporary, the lifetime of all temporaries in the statement are extended to match the lifetime of the reference.

Perhaps my proposal will find support, being in the middle ground between this original ideal and the status quo.


问:
Open Source License that prohibits verbatim resale?
I was taking a look at this question here:

Open Source License that prevents re-selling

And it makes some good points on how open source is defined by its ability for resale...

However, I still have a bit of a concern of verbatim resale. I don't mind letting my code be changed, edited, modified, shared, etc... what would strike me as offensive though is if I released my application on a store, and someone decides to take my package/application, make no changes to it whatsoever, and release it in the same store at a competing price.

I would be fine if he say released it under a different translation, or added a feature, some documentation, or packaged it for a different platform... but to copy verbatim to snatch up some royalties, seems like that this would only be detrimental to the open source community and discourage developers who are brave enough to let their code be open in the first place.

Is there a strategy, clause, or a specific open source license that combats this type of behaviour? If I perhaps create and bundle a trademark inside my program, would this prevent it being sold verbatim?

答:
I think you may be fighting a losing battle; I'm not sure how "I want to make my source code available to others to do more or less what they want to" (the definition of open source) is compatible with "I want to keep others from undercutting me on price."

With that said, there are a few strategies that may or may not help:

Trademark the product name, logo, etc. This would mean that cloning could still happen, but any clones couldn't use your name. Examples: Red Hat clone CentOS couldn't refer to Red Hat by name (it described itself as "based on a prominent North American Linux vendor"); the Firefox trademarks mean that Debian calls their version of Firefox "Iceweasel."

As @Delnan points out, this could easily backfire, since it doesn't prevent people from releasing under a different name and building up their own brand.

Don't open source everything. Open all of the libraries and supporting code but keep your core functionality closed (example: GitHub); or open the core but make add-ons proprietary (examples: numerous); or open the PC / Mac version but keep the mobile port proprietary. For games, you can open the code but copyright the assets (levels, graphics, etc.) (examples: DOOM, ToME).

Even something as simple as opening the components but keeping the build scripts and packaging closed could be enough of a road block to stop parasites until you're reasonably popular; at that point, you can hopefully compete on other terms.

Let it go. Patrick McKenzie talks about feeling "violated" when someone pirates your commercial software and wanting "a security system [that] includes dead-locks, pitbulls, a batallion of US Marines with shoot-to-kill-orders, and some cleverly disguised booby-traps involving acid or flaming oil, or perhaps just flaming acid"; although he's discussing commercial software, maybe the same philosophy applies here.

If your product doesn't see much success, then the existence of parasites isn't really hurting you. If your product does see success, then if you do your product right - create something that meets people's needs, and treat people well - then you'll have fans, and you'll have a community, and this will provide some protection against parasites. You won't stop every abuse, but you'll do well enough.

Or maybe not. I'm not an expert here.


问:
Implementing a requirement with a decorator and ensuring its usage
In a shared library I have a function that is widely used.
I'm implementing a requirement for the function to override its behavior when the entities are in a specific state.

I have decided on implementing this requirement with the decorator pattern.

All of my clinets program against an interface for this service and most of them use a IoC container, others use bastard injection.

How should I force or guide the clients to use my decorator?
Without my decorator the service wouldn't do the new requirement for the system.

I was thinking of having the service implementation internal and have a public factory for creating the service as an interface but then my factory couldn't use the lifestyles of the IoC container.

Any suggestions?

答: I would suggest using a facade object to hide the detail of the requirement for the decorator. The facade would simply create the service and its decorator behind the scenes, and then forward client requests to them. By presenting a simpler interface you make it easier for clients to use your service, avoid the need for a separate factory api and make it easier for you to add new features in future.</p>


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答: When the deadline is near, and requirements change, design changes, and you spend 16 hours in office, that is evil. </p>

Title: Is anything in programming truly evil?


问:
Why "Fork me on GitHub"?
I understand how GitHub works, but one thing I've been confused about is, why almost every OSS project lately has a "Fork me on GitHub" link on their homepage. For example,

http://jqtjs.com/, http://www.daviddurman.com/flexi-color-picker/, and others.

Why is this so common? Is it that they want/need code validation, checking for security/performance improvements that they may not know how to do?

Is it meant to show that this is a collaborative project - you're welcome to add improvements?

Do they work for GitHub, or want to promote their service? Oddly enough, I don't think I've seen a "Fork project on Bitbucket" logo recently.

My first reaction to that logo was that the project probably needs to be modified (forked) in order to integrate it with anything useful - or that they are encouraging fragmented codebase, encouraging everyone to make their own fork of the project. But I don't think that is the intent.

答:
it's another way to say "patches are welcome".

instead of sending wishes and feature requests, people can send pull request where the original author review, validate and merge the pull request.

historically forking is a hostile action done by group that is in conflict with the management of the original project, for example Sun's OpenOffice used to reject fast C/C++ SVG plugin because it prefers its own slow broken Java-based plugin for political reasons.

In most cases forks are bad, and carried by envy people or people from selfish companies who have plans that do that is not shared with the original community and is not in align with it (ex. Canonical) and example of this is libav/avconv (which is a fork of FFMPEG), in those cases the original community have higher quality, security, and they welcome patches that is aligned with community plans.

Dan Walsh noted the old definition of fork

I have been in open source for a long time, and my definition of a
  "fork" might be dated. I think of a "fork" as a hostile action taken
  by one group to get others to use and contribute to their version of
  an upstream project and ignore the "original" version. For example,
  LibreOffice forking off of OpenOffice or going way back Xorg forking
  off of Xfree86.

Then he compared that with github's fork

Nowadays, GitHub has changed the meaning. When a software repository
  exists on GitHub or a similar platform, everyone who wants to
  contribute has to hit the "fork" button, and start building their
  patches. As of this writing, Docker on GitHub has 9,860 forks,
  including ours. By this definition, however, all packages that
  distributions ship that include patches are forks. Red Hat ships the
  Linux Kernel, and I have not heard this referred to as a fork. But it
  would be considered a "fork" if you’re considering any upstream
  project shipped with patches a fork.

Title: Why "Fork me on GitHub"?


答:
Is there […] a specific open source license that combats this type of behaviour?

No, there is no such license. And there cannot be. The ability to sell the software is a crucial part of the Open Source Definition. Any license that prohibits selling is by definition not Open Source.

If I perhaps create and bundle a trademark inside my program, would this prevent it being sold verbatim?

Yes, it would. If you trademark the name of your program, then anybody who wants to sell it would need to buy a trademark license from you, and you could simply refuse to sell them one. Thus, they would need to change the name of your software.

OTOH, if they need to edit the software anyway to change the name, they could just keep the name, and edit some other minor part, thus no longer making it a verbatim copy, and as a result legal to sell.

Title: Open Source License that prohibits verbatim resale?

Body:
I was taking a look at this question here:

Open Source License that prevents re-selling

And it makes some good points on how open source is defined by its ability for resale...

However, I still have a bit of a concern of verbatim resale. I don't mind letting my code be changed, edited, modified, shared, etc... what would strike me as offensive though is if I released my application on a store, and someone decides to take my package/application, make no changes to it whatsoever, and release it in the same store at a competing price.

I would be fine if he say released it under a different translation, or added a feature, some documentation, or packaged it for a different platform... but to copy verbatim to snatch up some royalties, seems like that this would only be detrimental to the open source community and discourage developers who are brave enough to let their code be open in the first place.

Is there a strategy, clause, or a specific open source license that combats this type of behaviour? If I perhaps create and bundle a trademark inside my program, would this prevent it being sold verbatim?


问:
Porting security from Java/.NET to PHP
This probably a rather naive question given my limited knowledge in the code I've been looking at, but I want to get my head around it before I start diving into writing actual code myself.

I'm writing a common set of tools for PHP and most of my inspiration has come from the .NET framework.  The ironic thing is that I have never used the .NET framework, but I do understand C# and can therefore port the concepts I "do" understand from Mono.

But I have run into a bit of a wall, System.Security.  As I browse over the API docs, and the Mono security implementations on Github, I quickly feel like none of features could ever be applied to PHP.  My current confusion is as follows:

```<code>PermissionSet ps1 = new PermissionSet(PermissionState.None);
ps1.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open));
Console.WriteLine(ps1.ToXml().ToString());
</code>```

So here is a basic example.  What I want to do in PHP is create an application partially governed by permissions on the "environment" level.  That is to say, one machine shouldn't be able to perform certain actions that another might.  For instance, machine A, shouldn't be allowed to TCP to machine B.

But when I look at the code in the example, I don't really understand why it makes any difference.  My current understanding is that this is not "setting" the permissions, but "checking" them.  And the permission itself is predefined somewhere else, I.E. in the machine.

I have looked over Java's implementation of the same feature, and side by side .NET looks a lot more in-depth.  I would like to incorporate this concept into my own PHP code, but right now I don't know how I would do it.

Are the permissions entirely arbitary? does .NET "impose" restrictions? or simply provide security diagnostics to the application?  If the last one is true, then porting to PHP is not only possible, but may actually be quite useful.  However I know that in PHP, the second one is impossible.

Could someone please clear up what the Java and .NET security namespaces do, and give me an idea of how feasible it is to port to other languages.

答:
Every language has a runtime which connects your code with the outside world. In the case of Java and .NET, this runtime includes a security model. E.g. if a Java application wants to open a file, that request has to pass through the runtime. The runtime can then deny that request. Note that this is not implemented on a library level within the language, but on a language implementation level. From within the runtime, you can only check what you are allowed to do, but not grant yourself new permissions.

Therefore, you can't just implement a security model in another language: you security layer would need some way to perform the security-sensitive action, but that same way would be available to any other code in that language, so your security layer could be bypassed. Instead, this security model needs to be in the runtime itself (in the case of PHP, this would be the interpreter in the default implementation).

I have seen one exception: Perl's Safe module can control which opcodes are available to a piece of code being compiled, which can serve as a coarse sandbox. Here, the runtime doesn't itself provide the security model, but the dynamic nature of the runtime is exploited to implement a security model on top of it.

PHP does have a couple of sandboxing mechanisms: E.g. Runkit can restrict the functions that can be called by a sandboxed piece of code. A common sandboxing technique is also to override built-in functions by versions that check permissions, but that only works as long as there is no way to get the original version back. This can be a viable approach when rewriting compiled code to be sandboxed, but rewriting-based security approaches are prone to miss obfuscated calls.

Title: Porting security from Java/.NET to PHP


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
The where and why are usually going to be:

familiarity

desired language features

specific libraries you want to use

performance requirements

For server side programming you can often choose from a myriad of different languages, compiled or interpreted.  Usually the choice of language is driven by which platform you or your team will be most effective on.  Or if you don't yet have a team, the availability of skills in the market.

On a side note I don't really understand deciding to use C/C++ based on performance (only) since many scripting languages are extensible with C/C++.  You get the benefit of a rapid development language coupled with the ability to migrate the slow portions into C/C++ extensions.  Certainly if your doing systems programming where every op counts it's understandable, but in most app development I don't get it.


问:
How does Luhn algorithm relate to cryptograpic hash functions?
What I am interested is the similarities and differences between the two. It is my understanding to present time that Luhn algorithm is a type of checksum function same as some cryptographic hash functions.

From what I have read, the hash functions cannot be reversed as it is a "one-way" function, mathematically speaking, where's it seems same does not apply with the Luhn algorithm.

I would appreciate any input on this particular subject matter. Your insight is very much appreciated.

答:
The difference is in usage and properties necessary for the usages.

Checksums basically detect (and sometimes correct) small amounts of non-malicious, unintentional data corruption:

invalid input

transmission errors

storage degredation

In all uses, a checksum and data are combined so that the original data can be recovered. In most encodings, the checksum is appended to the original, but you could have a checksum function that is more hash-like, where the original data doesn't appear directly in the output. Base-64 encoding, while not a checksum or hash, is an example of an encoding that doesn't include unmodified input in its output.

Numeric data can be viewed as a point in some space (sometimes called a "code space"), with each digit a coordinate. Checksums generally work by spreading out valid data (in more formal terms, it maximizes the Hamming distance between strings) in the space. Around each valid datapoint is a sphere of invalid points that are closest to it. Creating a code can also be viewed as finding an efficient sphere packing.

If received data isn't a valid datapoint, it indicates an error; the nearest valid datapoint is assumed to be the transmitted value (if there is a nearest; sometimes, the received data may be equidistant to two or more, in which case the error can't be corrected). In particular, the amount of error must be ≤ 1/2 the minimum distance between data points.

Like hashes, checksums lack inverses in terms of the generated check digits. This usually doesn't matter, as the original data are transmitted along with the check digits and the whole point of a checksum is to find the inverse of the coded representation.

Hash function uses:

index data for storage & retrieval (hash tables, caches)-

if similar data have similar hashes, the hash function can be used in algorithms to find matching or similar data

file IDs in P2P networks and (document or code) repositories

data integrity: detect invalid data; detect (but not correct) whether data has been changed/corrupted. Allows for a much higher amount of corruption than checksums, and can be used to detect tampering (intentional changes)-

shorten digital signatures. The signature is the actual detection mechanism, but the digest (sc. the hash of a document or message) can be encrypted instead of the document to reduce the signature size

verification-

passwords

proof-of-work: some problems involving hashes (e.g. finding pre-images or collisions) have high resource costs (e.g. processor time), so finding an answer can indicate the system spent resources to do the work-

crypto-currency

P2P defense measures

key derivation (e.g. in WPA/WPA2)

Depending on the usage, the hash and original data may be kept separate,  unlike checksums. Each usages of hashes also imply a number of properties (e.g. pre-image resistances) that don't matter with checksums.

The discipline that combines all this and more is coding theory.


问:
What is it about functional programming that makes it inherently adapted to parallel execution?
I've been reading over and over that functional languages are ideal (or at least very often useful) for parallelism.  Why is this?  What core concepts and paradigms are typically employed and which specific problems do they solve?

On an abstract level, for example, I can see how immutability might be useful in preventing race conditions or other problems stemming from resource competition, but I can't put it any more specifically than that.  Please note, however, that my question is broader in scope than just immutability -- a good answer will provide examples of several relevant concepts.

答:
Minimised shared state

What is it about functional programming that makes it inherently adapted to parallel execution?

The pure nature of the functions (referential transparency), i.e. having no side effects, leads to fewer shared objects and hence less shared state.

A simple example is;

```<code>double CircleCircumference(double radius)
{
  return 2 * 3.14 * radius; // constants for illustration
}
</code>```

The output is solely dependent on the input, there is no state that is included; in contrast to a function such as GetNextStep(); where the output is dependent on what the current step is (typically held as a data member of an object).

It is the shared state that needs access to be controlled via mutexes and locks. Having stronger guarantees about shared state allows for better parallel optimisations and better parallel composition.

Referential Transparency and pure expressions

More detail on what referential transparency is can be found here on Programmers.SE.

[It] means that you can replace any expression in the program with the result of evaluating that expression (or vice versa) without changing the meaning of the program. Jörg W Mittag

Which in turn allows pure expressions that are used to construct pure functions - functions that evaluate to the same result given the same input arguments. Each expression can thus be evaluated in parallel.

Body:
Minimised shared state

What is it about functional programming that makes it inherently adapted to parallel execution?

The pure nature of the functions (referential transparency), i.e. having no side effects, leads to fewer shared objects and hence less shared state.

A simple example is;

double CircleCircumference(double radius)
{
  return 2 * 3.14 * radius; // constants for illustration
}

The output is solely dependent on the input, there is no state that is included; in contrast to a function such as GetNextStep(); where the output is dependent on what the current step is (typically held as a data member of an object).

It is the shared state that needs access to be controlled via mutexes and locks. Having stronger guarantees about shared state allows for better parallel optimisations and better parallel composition.

Referential Transparency and pure expressions

More detail on what referential transparency is can be found here on Programmers.SE.

[It] means that you can replace any expression in the program with the result of evaluating that expression (or vice versa) without changing the meaning of the program. Jörg W Mittag

Which in turn allows pure expressions that are used to construct pure functions - functions that evaluate to the same result given the same input arguments. Each expression can thus be evaluated in parallel.


答:
The main reason is that referential transparency (and even more so laziness) abstracts over the execution order. This makes it trivial to parallelize evaluation.

For example, if both a, b, and || are referentially transparent, then it doesn't matter if in

```<code>a || b
</code>```

a gets evaluated first, b gets evaluated first, or b doesn't get evaluated at all (because a was evaluated to true).

In

```<code>a || a
</code>```

it doesn't matter if a gets evaluated once or twice (or, heck, even 5 times … which wouldn't make sense, but doesn't matter nonetheless).

So, if it doesn't matter in which order they are evaluated and it doesn't matter whether they are evaluated needlessly, then you can simply evaluate every sub-expression in parallel. So, we could evaluate a and b in parallel, and then, || could wait for either one of the two threads to finish, look what it returned, and if it returned true, it could even cancel the other one and immediately return true.

Every sub-expression can be evaluated in parallel. Trivially.

Note, however, that this is not a magic bullet. Some experimental early versions of GHC did this, and it was a disaster: there was just too much potential parallelism. Even a simple program could spawn hundreds, thousands, millions of threads and for the overwhelming majority of sub-expressions spawning the thread takes much longer than just evaluating the expression in the first place. With so many threads, context switching time completely dominates any useful computation.

You could say that functional programming turns the problem on its head: typically, the problem is how to break apart a serial program into just the right size of parallel "chunks", whereas with functional programming, the problem is how to group together parallel sub-programs into serial "chunks".

The way GHC does it today is that you can manually annotate two subexpressions to be evaluated in parallel. This is actually similar to how you would do it in an imperative language as well, by putting the two expressions into separate threads. But there is an important difference: adding this annotation can never change the result of the program! It can make it faster, it can make it slower, it can make it use more memory, but it cannot change its result. This makes it way easier to experiment with parallelism to find just the right amount of parallelism and the right size of chunks.

Title: What is it about functional programming that makes it inherently adapted to parallel execution?

Body:
I've been reading over and over that functional languages are ideal (or at least very often useful) for parallelism.  Why is this?  What core concepts and paradigms are typically employed and which specific problems do they solve?

On an abstract level, for example, I can see how immutability might be useful in preventing race conditions or other problems stemming from resource competition, but I can't put it any more specifically than that.  Please note, however, that my question is broader in scope than just immutability -- a good answer will provide examples of several relevant concepts.

Body:
The main reason is that referential transparency (and even more so laziness) abstracts over the execution order. This makes it trivial to parallelize evaluation.

For example, if both a, b, and || are referentially transparent, then it doesn't matter if in

a || b

a gets evaluated first, b gets evaluated first, or b doesn't get evaluated at all (because a was evaluated to true).

In

a || a

it doesn't matter if a gets evaluated once or twice (or, heck, even 5 times … which wouldn't make sense, but doesn't matter nonetheless).

So, if it doesn't matter in which order they are evaluated and it doesn't matter whether they are evaluated needlessly, then you can simply evaluate every sub-expression in parallel. So, we could evaluate a and b in parallel, and then, || could wait for either one of the two threads to finish, look what it returned, and if it returned true, it could even cancel the other one and immediately return true.

Every sub-expression can be evaluated in parallel. Trivially.

Note, however, that this is not a magic bullet. Some experimental early versions of GHC did this, and it was a disaster: there was just too much potential parallelism. Even a simple program could spawn hundreds, thousands, millions of threads and for the overwhelming majority of sub-expressions spawning the thread takes much longer than just evaluating the expression in the first place. With so many threads, context switching time completely dominates any useful computation.

You could say that functional programming turns the problem on its head: typically, the problem is how to break apart a serial program into just the right size of parallel "chunks", whereas with functional programming, the problem is how to group together parallel sub-programs into serial "chunks".

The way GHC does it today is that you can manually annotate two subexpressions to be evaluated in parallel. This is actually similar to how you would do it in an imperative language as well, by putting the two expressions into separate threads. But there is an important difference: adding this annotation can never change the result of the program! It can make it faster, it can make it slower, it can make it use more memory, but it cannot change its result. This makes it way easier to experiment with parallelism to find just the right amount of parallelism and the right size of chunks.


问:
How does Functional Programming's immutability feature work with CQS?
Given immutability (which is often encouraged and said to be one of building blocks of functional programming) and CQS (which says that commands should not return a value other than void/unit), how do these work together?

For example:

How would you perform a series of commands (eg multiple file copies, which can throw all kinds of exceptions but should not crash the program), and collect their success or failure+reason in a list of results?

I can imagine some solutions in OO like throwing events or giving access to a Report instance (either static or passing it in by reference), but what are the possibilities in functional languages which do not break CQS?

答:
CQS is an idiom from object oriented languages that is designed to help avoid the confusion that can be caused when a function unexpectedly mutates state or interacts with the environment.

This is not a problem for a functional language. In functional languages, all such interaction is explicit in the signatures of the functions involved. Hence, CQS serves no purpose in a functional language: commands are by necessity separate due to the fact that they must both consume and return an object representing the part of the environment that they interact with. This object is typically a monad, and such a monad can be used for many purposes, including accumulating results and errors.


问:
Usage - Factory Pattern vs Dependency Injection
Okay, this question is not on which is better. It is more about when to use Dependency Injection vs Factory.

I have done a bit of research and it goes like this.

DIP:

Provides loose coupling, through IoC. The class does not need to know how it got the dependencies. IoC Containers take the control of providing the dependencies.

Factory:

It is a creation pattern, used to generate the dependencies for a class. It also provides loose coupling since the class is no more directly creating its dependencies.

To me it seems like DI can be used in most of the situations to inject the Dependencies and Factories can be left out altogether. I've been using Spring (for a year now) and most of the times a class needs 1 or 2 particular dependencies and Spring makes the stuff quite easy.

Taking about Factories, one scenario I think of wherein DI would turn out to be a little cumbersome, is when a class needs certain dependency based on some condition.

Something like this:

```<code>class Bike {
private Engine engine;
private Model model;

public initEngine() {
  if(model == 'VINTAGE')
    engine = new CaseIronEngine();

  else if(model == 'MODERN')
    engine = new AluminiumAlloyEngine();

 ..
 ..
}
}
</code>```

In this case DI would not be that straightforward, and Factory should be an ideal solution.

So kindly shed some thoughts over this. Many articles on the web mention that DI is kind of a replacement for Factory Patterns. But still there is no concrete article on which one would be better choice under which circumstance.

Some articles mentioning DI as next big thing are as follows:

http://tutorials.jenkov.com/dependency-injection/dependency-injection-replacing-factory-patterns.html

http://tutorials.jenkov.com/dependency-injection/dependency-injection-replacing-factory-patterns.html

答:
You pretty much hit the nail on the head.

Dependency injection is a great choice when you want to get dependencies that are known and unchanging at runtime or compile-time, depending on how you configure. Let's assume that you have a mailer in your application implemented by IMailer and you can use a TextBasedMailer or HtmlBasedMailer. You either build the application or use a configuration file to tell the DI framework what implementation to use.

Now, let's say that the IMailer to use depends on a preference for a user. Some users want plaintext e-mails, other HTML. The moment you request the IMailer instance you need some kind of logic to determine what mailer to resolve to. This logic would probably be isolated in a class and at that point you are pretty much using the Factory pattern, even if you are not calling it that.

Note that these two are not mutually exclusive. For example, let's say your application can mail attachments in a user-chosen format. You would implement different IAttachmentGenerators such as PdfAttachmentGenerator, HtmlAttachmentGenerator, WordAttachmentGenerator,... You could have an AttachmentFactory that gets the list of IAttachmentGenerators via DI and resolves the correct Generator to use based on the user preference. In this case, you are using DI AND a factory.


问:
Will HTML5/JS Eventually Replace All Client Side Languages?
I'm just wondering about the future of it all. IMHO, there are 4 forces that define where technology goes: Microsoft, Apple, Google, Adobe.

It looks like in Apple's iPhone/iPad iADs can now be programmed in HTML5. So does that mean HTML5 will eventually replace objective-c?

Also, Microsoft has now shifted it's focus from WPF/Silverlight to HTML5 and I assume Visual Studio 2011 will be all about tooling support for HTML5. Because that's what Microsoft do. (Tools). In a few months IE9 the last major browser will support HTML5.

Similarly Adobe is getting on the HTML5 bandwagon and allows to export flash content to HTML5 in their latest tools.

And we all know how much in bed Google is with html5. Heck, their latest Operating System (Chrome OS) is nothing but a big fat web browser.

Apps for Mobile (i.e., iPhone, Android, WM7) are very hard for a company to program especially for many different devices (each with their own language) so I'm assuming this won't last too long. I.e., HTML5 will be the unifying language. Which is somewhat sad for app developers because now users will be able to play the "cool" html5 apps for free on the web and it'll be hard to charge for them.

So are strongly-typed languages really doomed, and in the future, say 5-10 years, will client side programming only be in HTML5? Will all of us become javascript programmers? :) Because the signs are sure pointing that way...

答:
It also depends on the skill of majority of developers and the tools they use. The technology giants you mention can drive a technology based on the tools they provide. For example, people say HTML5 is Flash killer but I feel thats just too far away there are many Flash developers and it is a daunting task to shift their skills to JavaScript. What eventually happens the skill remains same but output becomes different. In this case, Adobe comes out with HTML5 conversion tool.

Also, you have to think about performance of client applications. Where it is necessary, platform specific tool will be utilized. Takes games and iOS apps for example. I know WebGL is coming out good but I feel people still use C to create games. Or they'll create a game language that creates high performance games. Apple initially wanted only webapps but when developers saw the wonders of Cocoa they jumped on it to create classy apps.

To sum it up, there will always be new tools/language/technologies that'll always be cooler than the current ones.


问:
Is it better to call a function that doesn't have an effect at that point, IF it improves code clarity?
I have three views in my program (iOS app). Only one of them is ever active at the same time so I set the visibility off for two of them and switch visibility as the user presses buttons. The views are initialized as visible so I set the visibility off in code before the main view shows.

I can do

```<code>[view1 setAlpha:0.0f];
[view2 setAlpha:0.0f];
</code>```

for two of the views, but now the third one (the one that should be visible at the start of the app) is not addressed. I put a

```<code>[view3 setAlpha:1.0f];
</code>```

after the first two, because I think it keeps it clear that there are in fact three views, not two as one might think when seeing the code. How do other programmers do this? Is it purely preference or are there some conventions?

If the call is very heavy, it's obviously better to not call it when that isn't necessary, but I was wondering about small things like my example.

答:
I would believe that adding a comment explaining that the call is unneeded (and why) is best.

(perhaps, the fact that a call is unneeded, or that you need a comment about that, might be a code smell)


问:
Grouping algorithm
We've developed an algorithm that depending on the check-in time of some workers and their living place, calculates the way to group them into some vehicles and the route which must be followed by the vehicles to carry them to the workplace. This has been accomplished using the TSP (Travelling Salesman Problem) algorithm and some other customisation.

We want to go beyond and improve it. For the time being, vehicles' seats capacity are fixed to 4 (5 places but one occupied by the driver) and we want to make this amount "variable". In other words, we want to, prior to the execution of the main algorithm, determine the combinations of vehicles (and their free seats) which may be needed. It is important to know that when I speak of vehicles, I speak about types of vehicles, e.g. Vehicle A is of 4 seats, Vehicle B is of 7 seats, and so on. So I'm not talking about having one Audi A8 of 5 seats, Seat Ibiza of 5 seats, one Bus of 20 seats, say.

So far, what I've thought up is the following:

Determine workers' groups.

Determine how many vehicles will be needed and their (free) seats. That's what I'm asking in that question [a].

The user selects the preferred combination and goes on.

Apply the algorithm which is already developed using the combination of vehicles and see whether it reaches a feasible solution.

My question is how to develop the [a] algorithm. The following example will show you the result of the execution of [a]:

Imagine we have the following people to group into vehicles of 4, 7, 10 seats free.

After the execution of [a], we will have as a result:

G3 (2 workers): One vehicle of 4 seats free (vehicles with more seats free are discarded).

G2 (2 workers): one vehicle of 4 seats free (vehicles with more seats free are discarded).

G1 (9 workers):

Option A: 3 vehicles of 4 seats.

Option B: 1 vehicle of 4 seats and another one of 7.

Option C: 2 vehicles of 7 seats.

Option D: one vehicle of 10 seats.

I've thought of an approximation:

Create the types of vehicles and add them to a sorted list (sorting criterion must be the seats).

For each group of workers, do:

Calculate combinations [b].

Print results on screen.

So the main problem is how to develop [b].

Any suggestions? Sorry if I've explained myself badly.

答:
I've come up with a possible solution: make use of Constraint Satisfaction Problem to solve it.

There will be one constraint per Group, as follows:

workers amount of the group <= sum per each vehicle(vehicle amount X vehicle's seats)

The only variable there is the vehicle amount, the rest are constants. So, in my example there would be the following contraints:

9 <= 4x + 7y + 10z

2 <= 4a + 7b + 10c

2 <= 4j + 7k + 10i

I found several libraries (JaCoP, Drools and OptaPlanner), and I'm currently using the first one. But I don't know how to define these constraints properly...

Title: Grouping algorithm


问:
Pre-calculate values or not on Raspberry Pi
Say that you want to rotate something 360 steps 100 times. You now have a choise to pre-calculate 360 sin and cos values once and then use the stored values 100 times, or you can calculate sin and cos every time.

As far as I understand on modern CPUs you're better off just calculating sin and cos each time because the CPU is many times faster than memory access anyway. However, on a slower CPU like the one used on a RPi (not version 2) would this still hold? or is it slow enough that pre-calculating values is better? A Raspberry Pi has a 700 MHz single core processor.

答:
As far as I understand on modern CPUs you're better off just calculating sin and cos each time because the CPU is many times faster than memory access anyway.

Sure, main memory access costs many CPU cycles, where a CPU would be idle waiting for data.

But that completely ignores that modern CPUs have memory caches (some have 3 levels of cache on the die, commonly referred to as L1, L2 and L3). This memory access is much faster than main memory access (though L1 is faster than L2 which is faster than L3).

If your program is designed well enough and with cache locality in mind, a calculated local variable (the result of your sin and cos calculations, for instance) will be fetched from cache and not main memory (or might even reside in a CPU register). This will be faster than re-calculating.

To see which one is faster, you would need to try both approaches, in a real-world scenario (so, using your actual application) and time it.


答:
Most modern languages will perform table lookups rather than calculate sin and cos values.  If the value is between two table values, it'll average the two together (weighted average).

If I'm not mistaken, the same should be true for calling sin/cos in a raspberry pi program, though it is still technically performing a table lookup that you could otherwise avoid by pre-calculating into an array.

My guess is that pre-calculating rotation values only to use once would not be faster and you'd be using up a bit of memory.  If you have to perform another rotation, the difference would likely be marginal.  However my advice would be to try it to be sure.

Title: Pre-calculate values or not on Raspberry Pi

Body:
Say that you want to rotate something 360 steps 100 times. You now have a choise to pre-calculate 360 sin and cos values once and then use the stored values 100 times, or you can calculate sin and cos every time.

As far as I understand on modern CPUs you're better off just calculating sin and cos each time because the CPU is many times faster than memory access anyway. However, on a slower CPU like the one used on a RPi (not version 2) would this still hold? or is it slow enough that pre-calculating values is better? A Raspberry Pi has a 700 MHz single core processor.