答:
I have experience with Ninject, not Castle Windsor, but the principles should be the same.

To understand dependency injection, it helps to recall how you wrote code without it. Typically, the DepartmentsController constructor would look like something like this:

```<code>public DepartmentsController()
{
    _repository = new DepartmentRepository();
}
</code>```

The controller depends on the repository, and by placing it in the constructor we ensure that every DepartmentsController is instantiated with a repository and begins its life in a valid state. By doing this, however, we make it more difficult to later swap one implementation of DepartmentRepository for another. In particular, if we want to isolate the DepartmentsController and test it independently, we're in trouble. How do we test this class without invoking actual calls to the database through DepartmentRepository?

Your first example improves on this scenario by creating a "seam" between the objects: a point where the two are glued or stitched together that can be separated easily, especially for tests. Instead of creating the DepartmentRepository itself, your controller can ask for it:

```<code>public object GetService(Type serviceType)
{
    return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
}
</code>```

This is called the Service Locator pattern, and some consider it bad practice. By exposing Castle Windsor in this way, you have actually lost some of its benefits. In particular, your DepartmentsController now depends on the Service Locator and its GetService method. I won't cover all of the supposed disadvantages of Service Locators, but consider what happens when your application grows and you now have numerous classes (potentially all of them) dependent upon this single class.

Your third example improves upon the Service Locator pattern by making the container invisible to your class:

```<code>public DepartmentsController(IDepartmentRepository repository)
{
    if (repository == null)
        throw new ArgumentNullException("repository");

    _repository = repository;
}
</code>```

Notice how this version has no knowledge of the kernel / container or a service locator. Instead, we have made its true dependencies explicit in the constructor rather than the means to those dependencies. In fact, by writing your classes this way, you can construct entire class libraries that are ignorant of Castle Windsor and will work perfectly fine with Ninject, another DI framework, or no container at all, without modifying the code.

How you actually register your components (the difference between examples two and three) is partly a matter of scale.

```<code>container.Register(
        Component.For<IDeliveryItemRepository>().ImplementedBy<DeliveryItemRepository>().LifestylePerWebRequest(),
        Component.For<IDeliveryRepository>().ImplementedBy<DeliveryRepository>().LifestylePerWebRequest(),
        Component.For<IDepartmentRepository>().ImplementedBy<DepartmentRepository>().LifestylePerWebRequest(),
...
</code>```

is fine for a smaller application. If the number of classes grows, you have to stomach a never ending list of bindings or find a better method. One improvement is to favor convention over configuration: if Castle Windor assumes every IDeliverItemRepository has a DeliveryItemRepository implementation, the bindings above can be skipped. However, you haven't solved anything if most of your classes require exceptional configuration; you still have a long, omniscient kernel / container registration method.

Instead, you should probably explore something like your second example. This way, your ConfigureWindsor method can use reflection to find any IWindsorInstallers present in your application without knowing about specific interfaces or implementations. You can break all of your bindings into separate modules (Ninject's name for this concept) that are discovered at runtime.

To address your last question: Castle Windsor won't know which of your N implementations to choose without you telling it. You can accomplish this through a mixture of the concepts discussed above: primarily by convention, but with IWindsorInstallers when needed to specify important details like lifecycle and conditional bindings.

Title: What am I missing in my (mis)understanding of IoC/DI/Castle Windsor?

Body:
Okay, so here's how I understand IoC and DI in Web API to work when using Castle Windsor.

Note, though, that my confidence that I understand it as I should, though, falls somewhere between my confidence I could best Dennis Rodman in a one-on-one basketball game and my confidence in his sanity.

Another way to put it is to say that I have spent the last several days reading up on IoC/DI/Castle Windsor with Web API and experimenting with it, but I still feel like wearily responding, "All down but nine, pard; set 'em up on the other alley."

I have several more specific questions on Stack Overflow about it, such as this one, but am not yet much clearer about it.

So I'm going to "talk out loud" and hope that somebody responds with something that will refine my understanding, shed some light on this opaque (to me) subject, or help unravel this Gordian knot.

Point: The basis of IoC/DI lies in passing interfaces to constructors, so that the class with the constructor does not have to instantiate its own objects; in fact, has no need to know the concrete component/class.

Point: To set this up, you need code like so in your Controllers:

```<code>private readonly IDepartmentRepository _deptsRepository;

public DepartmentsController(IDepartmentRepository deptsRepository)
{
    if (deptsRepository == null)
    {
        throw new ArgumentNullException("deptsRepository is null");
    }
    _deptsRepository = deptsRepository;
}
</code>```

Point: Some class that implements IDepartmentRepository is passed to the DepartmentsController constructor

Point: The coder doesn't do that explicitly - the IOC container (Castle Windsor, in this case) does that "automatically" by intercepting the Web API routing mechanism with its own, as with code like this, in global.asax.cs:

```<code>GlobalConfiguration.Configuration.Services.Replace(
                typeof(IHttpControllerActivator), new WindsorCompositionRoot(_container));
</code>```

Point: global.asax.cs' Application_Start() gets the ball rolling and calls the Installer/Registrar with code such as:

```<code>protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureWindsor(GlobalConfiguration.Configuration);
}

public static void ConfigureWindsor(HttpConfiguration configuration)
{
    _container = new WindsorContainer();
    _container.Install(FromAssembly.This());
    _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true));
    var dependencyResolver = new WindsorDependencyResolver(_container);
    configuration.DependencyResolver = dependencyResolver;
}
</code>```

Point: Lots of other Castle Windsor scaffolding has to be set up for this. Specifically, classes need to be "installed" (registered - I think registered would have been a better/more easily grokkable term for it).

This is one of my major "say what?"/headscratching areas. I don't know if that registration code should look like this:

```<code>public object GetService(Type serviceType)
{
    return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
}

public IEnumerable<object> GetServices(Type serviceType)
{
    if (!_container.Kernel.HasComponent(serviceType))
    {
        return new object[0];
    }

    return _container.ResolveAll(serviceType).Cast<object>();
}
</code>```

...or like this:

```<code>public class ApiControllersInstaller : IWindsorInstaller
{
    public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly() // should it be Types instead of Classes?
         .BasedOn<ApiController>()
         .LifestylePerWebRequest());
    }
}
</code>```

...or like this:

```<code>public class ServiceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IDeliveryItemRepository>().ImplementedBy<DeliveryItemRepository>().LifestylePerWebRequest(),
            Component.For<IDeliveryRepository>().ImplementedBy<DeliveryRepository>().LifestylePerWebRequest(),
            Component.For<IDepartmentRepository>().ImplementedBy<DepartmentRepository>().LifestylePerWebRequest(),
            Component.For<IExpenseRepository>().ImplementedBy<ExpenseRepository>().LifestylePerWebRequest(),
            Component.For<IInventoryItemRepository>().ImplementedBy<InventoryItemRepository>().LifestylePerWebRequest(),
            Component.For<IInventoryRepository>().ImplementedBy<InventoryRepository>().LifestylePerWebRequest(),
            Component.For<IItemGroupRepository>().ImplementedBy<ItemGroupRepository>().LifestylePerWebRequest());
    }
}
</code>```

...or elsewise...

Point: Once all this is set up, and the Controllers (and Repositories? Is there more that do I have to about them, to make them safe for CW?) have been registered by the Castle Windsor routing engine, a call to my Web API app like:

```<code>http://platypus:28642/api/Departments
</code>```

...will be resolved to a "component" (concrete class) that implements IDepartmentRepository. CW will be able to figure that out, as long as I have one class that implements IDepartmentRepository, that that is the one to silently pass to the Controller's constructor which takes an arg for a class that implements IDepartmentRepository.

But...what if there are are N classes that implement IDepartmentRepository? How does CW know which one to pass to the Controller's constructor? How can I, the lowly human in this meeting of silicon and pink squishy stuff, designate which of the N I want CW to pass to the constructor?

Body:
I have experience with Ninject, not Castle Windsor, but the principles should be the same.

To understand dependency injection, it helps to recall how you wrote code without it. Typically, the DepartmentsController constructor would look like something like this:

public DepartmentsController()
{
    _repository = new DepartmentRepository();
}

The controller depends on the repository, and by placing it in the constructor we ensure that every DepartmentsController is instantiated with a repository and begins its life in a valid state. By doing this, however, we make it more difficult to later swap one implementation of DepartmentRepository for another. In particular, if we want to isolate the DepartmentsController and test it independently, we're in trouble. How do we test this class without invoking actual calls to the database through DepartmentRepository?

Your first example improves on this scenario by creating a "seam" between the objects: a point where the two are glued or stitched together that can be separated easily, especially for tests. Instead of creating the DepartmentRepository itself, your controller can ask for it:

public object GetService(Type serviceType)
{
    return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
}

This is called the Service Locator pattern, and some consider it bad practice. By exposing Castle Windsor in this way, you have actually lost some of its benefits. In particular, your DepartmentsController now depends on the Service Locator and its GetService method. I won't cover all of the supposed disadvantages of Service Locators, but consider what happens when your application grows and you now have numerous classes (potentially all of them) dependent upon this single class.

Your third example improves upon the Service Locator pattern by making the container invisible to your class:

public DepartmentsController(IDepartmentRepository repository)
{
    if (repository == null)
        throw new ArgumentNullException("repository");

    _repository = repository;
}

Notice how this version has no knowledge of the kernel / container or a service locator. Instead, we have made its true dependencies explicit in the constructor rather than the means to those dependencies. In fact, by writing your classes this way, you can construct entire class libraries that are ignorant of Castle Windsor and will work perfectly fine with Ninject, another DI framework, or no container at all, without modifying the code.

How you actually register your components (the difference between examples two and three) is partly a matter of scale.

container.Register(
        Component.For<IDeliveryItemRepository>().ImplementedBy<DeliveryItemRepository>().LifestylePerWebRequest(),
        Component.For<IDeliveryRepository>().ImplementedBy<DeliveryRepository>().LifestylePerWebRequest(),
        Component.For<IDepartmentRepository>().ImplementedBy<DepartmentRepository>().LifestylePerWebRequest(),
...

is fine for a smaller application. If the number of classes grows, you have to stomach a never ending list of bindings or find a better method. One improvement is to favor convention over configuration: if Castle Windor assumes every IDeliverItemRepository has a DeliveryItemRepository implementation, the bindings above can be skipped. However, you haven't solved anything if most of your classes require exceptional configuration; you still have a long, omniscient kernel / container registration method.

Instead, you should probably explore something like your second example. This way, your ConfigureWindsor method can use reflection to find any IWindsorInstallers present in your application without knowing about specific interfaces or implementations. You can break all of your bindings into separate modules (Ninject's name for this concept) that are discovered at runtime.

To address your last question: Castle Windsor won't know which of your N implementations to choose without you telling it. You can accomplish this through a mixture of the concepts discussed above: primarily by convention, but with IWindsorInstallers when needed to specify important details like lifecycle and conditional bindings.


问:
How do you track third party services SSL certificates?
Recently Windows Azure Storage SSL certificate unexpectedly expired and since a lot of dependent services defaulted to "refuse to connect to a site with expired SSL certificate" that became a serious problem.

Now the SSL certificate of any web service can be retrieved by anyone at any time for validation. The picture is from the linked to question:

So it means that the information was available at all times to "anyone it might concern" and any user of the service could have noticed the upcoming expiration and for example post a message on Microsoft forums before it was too late.

However I can't find any information about how such cases are typically handled except this question for doing that in code.

Is there any kind of best practice for validating third party services SSL certificates? What tools are typically used?

答:
I have a Ruby library I'm open-sourcing to enable this with TDD – Test Driven Devops. I'm making a Python version as well. Here's how it looks, testing a web app in Ruby:

```<code>require 'spec_helper'

describe 'My app' do
  it 'is configured for ssl' do
    # New-style RSpec syntax
    expect('www.myapp.com').to have_a_valid_cert

    # Old-style RSpec syntax
    'www.weblaws.org'.should have_a_valid_cert
  end
end
</code>```

My idea is that these tests can be run periodically, say every five minutes, and notify on error.

ContentLicense: CC BY-SA 3.0

Body:
I have a Ruby library I'm open-sourcing to enable this with TDD – Test Driven Devops. I'm making a Python version as well. Here's how it looks, testing a web app in Ruby:

require 'spec_helper'

describe 'My app' do
  it 'is configured for ssl' do
    # New-style RSpec syntax
    expect('www.myapp.com').to have_a_valid_cert

    # Old-style RSpec syntax
    'www.weblaws.org'.should have_a_valid_cert
  end
end

My idea is that these tests can be run periodically, say every five minutes, and notify on error.


问:
What's the best way to undo a Git merge that wipes files out of the repo?
So imagine the following the happens (and that we're all using SourceTree):

We're all working off origin/develop.

I go on holiday for a week.

My coworker has been working locally for the past several days without merging origin/develop back in to his local develop branch.

He tries to do a push, gets told he has to merge first, and then does a pull.

He gets a conflict, stopping the automatic commit-after-a-merge from proceeding.

Assuming that Git is like SVN, my coworker discards the "new" files in his working copy and then commits the merge - wiping those "new" files from the head of origin/develop.

A weeks worth of dev work goes on on top of that revision.

I come back from holidays and find out that several days of my work is missing.

We're all very new to Git (this is our first project using it), but what I did to fix it was:

Rename "develop" to "develop_old".

Merge develop_old into a new branch "develop_new".

Reset the develop_new branch to the last commit before the bad merge.

Cherry pick each commit since then, one by one, resolving conflicts by hand.

Push develop_old and develop_new up to the origin.

At this point, develop_new is, I'm hoping, a "good" copy of all of our changes with the subsequent weeks worth of work reapplied. I'm also assuming that "reverse commit" will do odd things on a merge, especially since the next few weeks worth of work is based on it - and since that merge contains a lot of things we do want along with stuff we don't.

I'm hoping that this never happens again, but if it does happen again, I'd like to know of an easier / better way of fixing things. Is there a better way of undoing a "bad" merge, when a lot of work has gone on in the repo based on that merge?

答:
If I understood correctly, this is your situation:

```<code>    ,-c--c--c--c--M--a--a--X ← develop
o--o--y--y--y--y-´
</code>```

After some common history (o), you committed and pushed your work (y). Your coworker (c) did work on his local repository and did a bad merge (M).
Afterwards there might be some additional commits (a) on top of M.

```<code>git reset --hard develop M^2
git branch coworker M^1
</code>```

Now your graph looks exactly like before the bad merge:

```<code>    ,-c--c--c--c ← coworker
o--o--y--y--y--y ← develop
</code>```

Do a good merge (G):

```<code>git checkout develop
git merge coworker
</code>```

Resulting in:

```<code>    ,-c--c--c--c-、
o--o--y--y--y--y--G ← develop
</code>```

Now transplant the additional commits:

```<code>git reset --hard X
git rebase --onto G M develop
</code>```

This gives the final result:

```<code>    ,-c--c--c--c-、
o--o--y--y--y--y--G--a--a--X ← develop
</code>```

Be aware that this might result in more merge conflicts. Also you just changed history, i.e. all your coworkers should clone/reset/rebase to the new history.

PS: of course you should replace G, M and X in your commands by the corresponding commit id.

Body:
If I understood correctly, this is your situation:

    ,-c--c--c--c--M--a--a--X ← develop
o--o--y--y--y--y-´

After some common history (o), you committed and pushed your work (y). Your coworker (c) did work on his local repository and did a bad merge (M).
Afterwards there might be some additional commits (a) on top of M.

git reset --hard develop M^2
git branch coworker M^1

Now your graph looks exactly like before the bad merge:

    ,-c--c--c--c ← coworker
o--o--y--y--y--y ← develop

Do a good merge (G):

git checkout develop
git merge coworker

Resulting in:

    ,-c--c--c--c-、
o--o--y--y--y--y--G ← develop

Now transplant the additional commits:

git reset --hard X
git rebase --onto G M develop

This gives the final result:

    ,-c--c--c--c-、
o--o--y--y--y--y--G--a--a--X ← develop

Be aware that this might result in more merge conflicts. Also you just changed history, i.e. all your coworkers should clone/reset/rebase to the new history.

PS: of course you should replace G, M and X in your commands by the corresponding commit id.


问:
Assert equality in mstest when types may differ
I've been working on some MSTest automated test infrastructure, that is testing a tool that merges data sets into SQL Server database tables. The basic structure of the test is to:

Define the incoming dataset using anonymous types

Apply the data using the reconcile tool

Read records from the output tables

Compare result rows to input data, column by column

Example input data:

```<code>public class InputData : List<dynamic> {} // Inspired by Massive etc

InputData input = new InputData()
{
    new { ExternalID = 1, PropertyName = "hello", Agent = "test" },
    new { ExternalID = (Int64)2, PropertyName = "fred", Agent = "test" } // Fixes the problem with a cast
};
</code>```

The issue I'm dealing with, is that the type inferred on my anonymous objects will be an Int32, but the corresponding column in my target table is a bigint, and hence the record will have an Int64 value. As a result, when I use Assert.AreEqual across each column, it fails on any int fields:

```<code>Assert.AreEqual failed. Expected:<1 (System.Int32)>. Actual:<1 (System.Int64)>
</code>```

You can see I have cast the int on my second anonymous object, this can be used to fix the issue. The primary aim of these tests is to make the sample data as slim and easy to read/write as possible, and I'd prefer to avoid the visual noise of all those casts.

I'm thinking about the best way to deal with the assertions. It seems like I should use dedicated assertions based on type. I guess the real question is, how aggressive should I be in converting between types automatically?

答:
Assert.AreEqual is basically just sugar for Assert.IsTrue(object.Equals(...)). If there isn't a known comparison operator for the two argument types, they'll compare false.

dynamic is pretty smart about this, so, for example, (dynamic)(int)1 == (decimal)1.0 evaluates to true. That only works if you use the == operator, though; it won't work if you try to use object.Equals, Assert.AreEqual, ((dynamic)x).Equals(...) or anything similar. Simply casting to dynamic won't work, you need to actually use its == operator. The good news is, the dynamic == allows any operand, which means you can get this to compile in a general-purpose assertion; if the comparison is invalid (e.g. comparing int to string, then it will fail at runtime with a RuntimeBinderException.

The next best thing, if you know they're going to be numeric types, would be to cast them all to Decimal or Double, although note that if you use Double you'll have to take into account the possibility of floating-point rounding error, and you should define equality based on some threshold, typically a multiple of Double.Epsilon. Decimal is a lot simpler unless you know for certain that you'll be dealing with floating point.

I don't think that you really have a lot of other choices. I personally would not recommend string conversion because lots of classes don't override ToString, so you end up comparing two instances of something like System.Collections.Generic.List``1[System.Int32], and your assertion declares that these are equal because they have the same string representation when in fact they are not only different instances but contain completely different elements. So don't do that. String coercion can easily mask serious errors in your tests. Stick to non-lossy, all-or-nothing conversions as above.


问:
Is it possible to loosely couple an application to its framework?
Let's say I'm developing a web application. My first choice is to use PHP with Fat-Free Framework (F3) and MVC pattern. Next year, I might decide I want to switch to Zend Framework, or maybe even ASP.NET MVC. Does it make sense to try and design my application in such a way that it is loosely coupled to its framework, or is the framework too integral to make this realistic?

The only reason I ask is because it came up in conversation with a peer recently, who criticized my pie in the sky idea of loosely coupling my application to F3.

答:
I once saw Robert C. Martin give a talk where he said something along the lines of "the first decision you make is the hardest one to change later".

So my advice is to try to delay this decision if you're not exactly sure what you want to use yet. Identify pieces that you can define now, and which would easily remain independent of whatever framework you end up using.


答:
It's good that you're thinking about how to fix the repository, but if your coworker only deleted new files and didn't overwrite a lot of updates, then a much simpler approach would be to simply restore the files that were deleted.

I'd probably start by trying to just cherry-pick (onto the current head) the original commits in which you added the code that has now gone missing. If for whatever reason that doesn't work, just check out the old revision with the files you added, and re-add them in a new commit.

What you describe is actually a subset of a well-known Git anti-pattern, which for the life of me I cannot remember the name of - but the gist of it is, making any "manual edits" during a Git merge (i.e. edits that aren't actually resolving any merge conflicts but are making some totally unrelated change) is considered an extremely bad practice because they are essentially masked by the merge itself, and are easily overlooked in code reviews or debugging sessions.

So definitely explain to your coworker that this was an epic fail, but consider slapping on a band-aid before prepping for major surgery.

Title: What's the best way to undo a Git merge that wipes files out of the repo?

Body:
So imagine the following the happens (and that we're all using SourceTree):

We're all working off origin/develop.

I go on holiday for a week.

My coworker has been working locally for the past several days without merging origin/develop back in to his local develop branch.

He tries to do a push, gets told he has to merge first, and then does a pull.

He gets a conflict, stopping the automatic commit-after-a-merge from proceeding.

Assuming that Git is like SVN, my coworker discards the "new" files in his working copy and then commits the merge - wiping those "new" files from the head of origin/develop.

A weeks worth of dev work goes on on top of that revision.

I come back from holidays and find out that several days of my work is missing.

We're all very new to Git (this is our first project using it), but what I did to fix it was:

Rename "develop" to "develop_old".

Merge develop_old into a new branch "develop_new".

Reset the develop_new branch to the last commit before the bad merge.

Cherry pick each commit since then, one by one, resolving conflicts by hand.

Push develop_old and develop_new up to the origin.

At this point, develop_new is, I'm hoping, a "good" copy of all of our changes with the subsequent weeks worth of work reapplied. I'm also assuming that "reverse commit" will do odd things on a merge, especially since the next few weeks worth of work is based on it - and since that merge contains a lot of things we do want along with stuff we don't.

I'm hoping that this never happens again, but if it does happen again, I'd like to know of an easier / better way of fixing things. Is there a better way of undoing a "bad" merge, when a lot of work has gone on in the repo based on that merge?


问:
Why should we be aware of licenses?
I know this is common question, but why should a programmer be aware of software licenses as well as extensions and plugins licenses?

I'm working in a company which focuses on the business process (Ruby on Rails) and I'm curious as to why they are strict on such licenses in the project development.

What licenses should I be aware of and why?

答:
Licenses are conditional terms of use.

If you breach the terms of a license, you can be sued.  Depending upon the licenses and the legal jurisdictions involved, there can be severe penalties for not abiding by the terms of the license.  Those penalties could bankrupt a company, or could cause the company to lose their claim to their software.

Some licenses heavily restrict what you can do with code, such as the copyleft provision within GPL's source code release requirements.  Other licenses restrict usage to only academic or noncommercial use.  And other licenses have free personal versions but require paid commercial versions.

If you are in the business of writing software, then you have to carefully pick what outside software you integrate with as their licenses may impact your ability to sell your software or affect how you structure your business model.

Your product managers are being strict because they are trying to minimize risk and avoid complications created by using conflicting licenses or licenses that may harm their business goals.

Title: Why should we be aware of licenses?


问:
Do immutable objects and DDD go together?
Consider a system that uses DDD (as well: any system that uses an ORM). The point of any system realistically, in nearly every use case, will be to manipulate those domain objects. Otherwise there's no real effect or purpose.

Modifying an immutable object will cause it to generate a new record after the object is persisted which creates massive bloat in the datasource (unless you delete previous records after modifications).

I can see the benefit of using immutable objects, but in this sense, I can't ever see a useful case for using immutable objects. Is this wrong?

答: Computation using immutable objects (as in functional programming) does not necessarily imply persisting every object that is generated!</p>

ContentLicense: CC BY-SA 2.5


问:
block access to area/controller's methods but allow inherited controller to run methods, asp .net mvc5
I am trying to find out how to block a whole area/controller from being accessed by typing url website.com/area1/basecontroller/method1 (this area also contains the views that will be displayed) , while still being able to inherit said controller and use the method from original controller like so website.com/area2/extendedbasecontroller/method1.

There would not be a method1 in the extendedbasecontroller, it would just perform method1 from the basecontroller

Is it possible or could it be achieved in a different way?

答:
I don't know if this is a good way to do or not, but it looks like this accomplishes what I am trying to do:

```<code>public class BlockActionFilter : ActionFilterAttribute,IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        var area = filterContext.RouteData.DataTokens["area"].ToString();

        if(area == "area1")
        {
            filterContext.Result = new RedirectResult("~/Home/Index");
        }

        this.OnActionExecuting(filterContext);
    }
}
</code>```

I can access the methods in basecontroller in area1 by inheriting it to an extendedbasecontroller in area2 and using it via that one, but I can't directly use basecontroller in area1.

Body:
I don't know if this is a good way to do or not, but it looks like this accomplishes what I am trying to do:

public class BlockActionFilter : ActionFilterAttribute,IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        var area = filterContext.RouteData.DataTokens["area"].ToString();

        if(area == "area1")
        {
            filterContext.Result = new RedirectResult("~/Home/Index");
        }

        this.OnActionExecuting(filterContext);
    }
}

I can access the methods in basecontroller in area1 by inheriting it to an extendedbasecontroller in area2 and using it via that one, but I can't directly use basecontroller in area1.


问:
Are my novice user stories correctly composed?
Is this user story substantively correct:

As a system owner, I want everybody that uses the system to have
  to log in using a secure password and login system, to prevent
  unauthorised and random access to system data.

And then:

As a user, I want to be able to log in with my secure password, so
  that only I can access areas of the system I need to do my work.

I have several other stories for the system owner, like password format, lockouts etc. Is this a good place for these requirements? As stories for the system owner?

答:
Users never really want restricted access. I would include access restriction as system owner (also commonly referred to as "product owner") stories. Depending on how much access control is required, you may even want to specify the who and what in individual stories such as:

```<code>As a system owner I want only managers to be able to create new employees.
</code>```

Avoid specifying solutions in your stories such as describing how the roles are defined or retrieved.

I wouldn't have stories including details such as password format criteria (validation), this should be acceptance criteria for a story about registering new accounts.

Lockouts seems like a good candidate for a system owner story.

Body:
Users never really want restricted access. I would include access restriction as system owner (also commonly referred to as "product owner") stories. Depending on how much access control is required, you may even want to specify the who and what in individual stories such as:

As a system owner I want only managers to be able to create new employees.

Avoid specifying solutions in your stories such as describing how the roles are defined or retrieved.

I wouldn't have stories including details such as password format criteria (validation), this should be acceptance criteria for a story about registering new accounts.

Lockouts seems like a good candidate for a system owner story.


问:
Coding style for chained function calls
A common thing you need to do is to take a value, do something with it by passing it to a function, and then do some more with the return value, in a chain. Whenever I run into this type of scenario, I get unsure about how best to write the code.

As an example, let's say I have a number, num, and need to take the floored square root of it and turn it into a string. Here are a few possibilities (in JavaScript).

I might simply pass num to one function at a time, and replace num with the return value:

```<code>function floorSqrt(num) {
    num = Math.sqrt(num);
    num = Math.floor(num);
    num = String(num);
    return num;
}
</code>```

This is nice since I don't need the original num any more, but in practice it might be confusing to start with one thing (a number) and end up with something completely different (a string).

I can save each step in a new variable:

```<code>function floorSqrt(num) {
    var sqrtNum = Math.sqrt(num);
    var floorSqrt = Math.floor(sqrtNum);
    var stringNum = String(floorSqrt);
    return stringNum;
}
</code>```

Although it seems wasteful to declare all those variables and come up with good names for them.

Or I can just do it all as a one-liner:

```<code>function floorSqrt(num) {
    return String(Math.floor(Math.sqrt(num)));
}
</code>```

But for more than two functions that approach gets incredibly unreadable, almost like code golf.

It seems to me like the most beautiful way to do this would be with some stack-based language, which might look something like this (pseudo code):

```<code>[sqrt floor toString]
</code>```

Is there a way to do something similar with JavaScript? List some functions, run one at a time, and use the return value of each one as the argument for the next? The closest is how some libraries like jQuery or Underscore.js allow you to chain methods, something like this:

```<code>function floorSqrt(num) {
    return _.chain(num).sqrt().floor().toString().value();
}
</code>```

I'm sure many wise people have thought wise things about this. What are some thoughts on pros and cons of the different styles?

答:
TL;DR: The Reduce/Compose Functional Programming Idiom

```<code># define/import: compose(fn1, f2)(arg) => fn2(fn1(arg))
# define/import: reduce(fn, [l1, l2, l3, ...]) => fn(fn(l1, l2), l3)...

commands = [Math.sqrt, Math.floor, String]
floorSqrt = reduce(compose, commands)

# floorSqrt(2) == String(Math.floor(Math.sqrt(2)))
</code>```

Notes:

compose from Eloquent Javascript

reduce requires a 2 argument definition

Using reduce and compose is a very common idiom used when you want to setup a pipeline of transformations for data to go through.  It's both readable and elegant.

<rant>
There are too many programmers who conflate readability with familiarity and vice versa.  They believe an unfamiliar idiom is unreadable, like the reduce/compose idiom only because it is unfamiliar.  To me this behavior is more aligned with a diletante, not someone who is serious about their craft. </rant>

Title: Coding style for chained function calls

Body:
TL;DR: The Reduce/Compose Functional Programming Idiom

# define/import: compose(fn1, f2)(arg) => fn2(fn1(arg))
# define/import: reduce(fn, [l1, l2, l3, ...]) => fn(fn(l1, l2), l3)...

commands = [Math.sqrt, Math.floor, String]
floorSqrt = reduce(compose, commands)

# floorSqrt(2) == String(Math.floor(Math.sqrt(2)))

Notes:

compose from Eloquent Javascript

reduce requires a 2 argument definition

Using reduce and compose is a very common idiom used when you want to setup a pipeline of transformations for data to go through.  It's both readable and elegant.

<rant>
There are too many programmers who conflate readability with familiarity and vice versa.  They believe an unfamiliar idiom is unreadable, like the reduce/compose idiom only because it is unfamiliar.  To me this behavior is more aligned with a diletante, not someone who is serious about their craft. </rant>


答:
I (as a user) are always angry about passwords - they need to be too long, they need to be changed too often, they need to be too different (across systems), etc. etc. So my user story would go like:

```<code>As a user, I want quick and hassle-free access to my system.
</code>```

If you have really considerate users, who are worried about security and traceability, you might add:

```<code>As a user, I want to be sure that nobody without permissions can fiddle with my data.
</code>```

I guess that is as far as any user goals would go. Passwords are not supporting any user tasks, they are supporting system administration goals, and thus should only go into stories for the "system owner", where you already have them.

Title: Are my novice user stories correctly composed?

Body:
Is this user story substantively correct:

As a system owner, I want everybody that uses the system to have
  to log in using a secure password and login system, to prevent
  unauthorised and random access to system data.

And then:

As a user, I want to be able to log in with my secure password, so
  that only I can access areas of the system I need to do my work.

I have several other stories for the system owner, like password format, lockouts etc. Is this a good place for these requirements? As stories for the system owner?

Body:
I (as a user) are always angry about passwords - they need to be too long, they need to be changed too often, they need to be too different (across systems), etc. etc. So my user story would go like:

As a user, I want quick and hassle-free access to my system.

If you have really considerate users, who are worried about security and traceability, you might add:

As a user, I want to be sure that nobody without permissions can fiddle with my data.

I guess that is as far as any user goals would go. Passwords are not supporting any user tasks, they are supporting system administration goals, and thus should only go into stories for the "system owner", where you already have them.


答:
Consider not to stick to the "I want" form for this kind of requirements, since as we see from the other answers, the difference between "what the user wants" and "what the system owner wants how the user should work with the system" may be a cause of misunderstandings. The important parts of a user story are the parts describing the "who", "when/where", "what", and "why", the "I want" is just an exchangeable template.

As an example:

A user when starting to work with the system has to log in with her secure password, so that only she can access areas of the system she need to do her work.

This is formally a correct user story, just as yours. If this story describes your requirements correctly, or if it is on the correct level of abstraction for your case, is a different question.


问:
Why do C++ and Java both use the notion of "reference" but not in the same sense?
In C++ a reference argument to a function allows the function to make the reference refer to something else:

```<code>int replacement = 23;

void changeNumberReference(int& reference) {
    reference = replacement;
}

int main() {
    int i = 1;
    std::cout << "i=" << i << "\n"; // i = 1;
    changeNumberReference(i);
    std::cout << "i=" << i << "\n"; // i = 23;
}
</code>```

Analogously, a constant reference argument to a function will throw a compile time error if we try to change the reference:

```<code>void changeNumberReference(const int& reference) {
    reference = replacement; // compile-time error: assignment of read-only reference 'reference'
}
</code>```

Now, with Java, the docs say that functions arguments of non-primitive types are references. Example from the official docs:

```<code>public void moveCircle(Circle circle, int deltaX, int deltaY) {
    // code to move origin of circle to x+deltaX, y+deltaY
    circle.setX(circle.getX() + deltaX);
    circle.setY(circle.getY() + deltaY);

    // code to assign a new reference to circle
    circle = new Circle(0, 0);
}
</code>```

Then circle is assigned a reference to a new Circle object with x = y
  = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change.

To me this doesn't look at all like C++ references. It doesn't resemble regular C++ references because you cannot make it refer to something else, and it doesn't resemble C++ const references because in Java, the code that would change (but really doesn't) the reference does not throw a compile-time error.

This is more similar in behavior to C++ pointers. You can use it to change the pointed objects values, but you cannot changes the pointer's value itself in a function. Also, as with C++ pointers (but not with C++ references), in Java you can pass "null" as value for such an argument.

So my question is: Why does Java use the notion of "reference"? Is it to be understood that they don't resemble C++ references? Or do they indeed really resemble C++ references and I'm missing something?

答:
Notion of 'reference type' is a generic one, it can express both a pointer and a reference (in terms of C++), as opposed to 'value type'.
Java's references are really pointers without syntactic overhead of -> an * dereferencing.
If you look into JVM's implementation in C++, they're really bare pointers.
Also, C# has a notion of references similar to Java's, but it also has pointers and 'ref' qualifiers on function parameters, allowing to pass value-types by reference and avoid copying just like & in C++.


答:
It depends on how the immutable object is mapped in the database. If it's just a component like a  DateTime (from the Joda Time library) then changing the value will result in an update rather than an insert. However, if the immutable is more complex requiring a row in a table then you've got the bloat problem.

I suppose, although it is a weak argument, you could implement an audit trail this way. Every change to the immmutable can be tracked through the inserts. There are many better ways to do this though.

All in all having immutable domain objects (instead of merely their components) seems a bit of a mismatch with persistence.

Title: Do immutable objects and DDD go together?

Body:
Consider a system that uses DDD (as well: any system that uses an ORM). The point of any system realistically, in nearly every use case, will be to manipulate those domain objects. Otherwise there's no real effect or purpose.

Modifying an immutable object will cause it to generate a new record after the object is persisted which creates massive bloat in the datasource (unless you delete previous records after modifications).

I can see the benefit of using immutable objects, but in this sense, I can't ever see a useful case for using immutable objects. Is this wrong?


问:
How to do inference in a card game?
In the game there are 5 players, each with 8 cards in hand. No other card is present.

Using Monte Carlo (MCTS) I run many simulations of the game from the current state to the end of the match. In those simulations adversaries play with very simple dumb rules. When generating a new simulation I assign to them unknown cards with a uniform random distribution. I say a card is unknown if it is not in my hand, it is not on the table and it has not been discarded before, then it must be in someone other's hand.

However, uniform random distribution it's not the best way to distribute cards. In fact, sometimes it's straightforward to a human player a reasoning like this:

If he had 3♥ he probably would have discarded it the previous turn as it was a very good move. Then, it's very unlikely that he'll discard 3♥ in hand hereinafter.

Well, before discarding, before generating the Monte Carlo simulations, I would assign to each adversary the set of unknown cards with their probability distribution:

{ (3♥, 0.20) , (4♥, 0.12) , (5♥, 0.03) ...}.

How can I calculate those probabilities? Is there some paper or some ideas where to start from?

EDIT:
An idea: Computationally talking, would it be a good idea to run a simple Monte Carlo simulation when chosing adversaries' strategy? With simple I mean a rough, fast, simulation which ends in a small time like a second. In this way, the next turn I would have a measure of the goodness of adversaries moves and I can start doing inference from there.

答:
You are talking about attributing states of belief to the other players. This is relatively easy to do if your opponents are computers with simple algorithms; for instance, you can perform normal game-tree analysis for all possible cases and value the actions that the opponents would have made if they played deterministically and optimally according to some fixed metric.

If your opponents are programs with algorithms as sophisticated as yours or more sophisticated, then things get very tough very fast. Whatever decisions you program might be exploited by opponents who know how you're going to react, opening the path to all kinds of bluffs, swindles, automatic learning to exploit your strategy as seen in the past, etc. Human players pose the same problem, except that the best ones are even better at this. In general, even modestly complex hidden-state games against human opponents tend to become as hard as general AI to play well.

Title: How to do inference in a card game?


问:
Using Ubuntu for commercial software development
I am plaining to use Ubuntu for developing Android and php application which I will sell in market. As far as I understand Ubuntu falls under GNU GPL license.

In this case do I need to make my source code open for all?

答:
Work done on a particular operating system is not derived from it and therefore is not covered by it's license (or more properly license of any of it's components, since operating system consists of many components with different licenses).

An application is derived from libraries it links to, but Android application only links libraries that come from the Android SDK and possibly NDK and neither of those limits what you can do with the application. You would have to be careful about license of any 3rd party library you'd want to include though.


答:
The answer will depend on exactly what you're selling. Are you reselling copies of Ubuntu, or selling modified Ubuntu software? Then the Ubuntu software license becomes important.

When developers simply use Ubuntu to make something else, we're using it as a tool just like a pencil or a calculator. And Ubuntu's GPL license doesn't apply to an independent, stand-alone product we've made with it.

So, are you selling an Android app in an online app store? Then check out the terms in the developer contract. And the PHP app — are you selling files with PHP in them to someone? Or on the other hand, will the PHP code never leave your server because it's a web app? These are two different scenarios. Either way, when a developer completely writes source code from scratch, they own the copyright to it and can do what they like with it. If, though, it requires, embeds or links to other libraries when it runs, then there might be obligations enforced by the GPL or another open-source license.

Title: Using Ubuntu for commercial software development

Body:
I am plaining to use Ubuntu for developing Android and php application which I will sell in market. As far as I understand Ubuntu falls under GNU GPL license.

In this case do I need to make my source code open for all?


答:
Since licenses are not identical to contracts, because licenses are set by authors of a product not by a copyright holders originally, but a developer/author can allow or transfer rights to set a required license to third person, to so called copyright holder. This rule of course can or could be specified by a contract between a developer and a hiring company/other developer. By default right to set license is kept to the product's author or a group of authors.

In case when an author, in thine case author of an application, transfer by a contract rights to set a license on a product, he lost that right, by keep the right by be specified as an author in the product's description. It is so called inalienable right. Unlike the right to specify a license for your product that is an alienable right.

So, you shell be away of not only a license, like variaous type of EULAs (that are really contracts), and open licenses like Creative Commons, or MIT licenses, which are mostly used in Rails/Gem applications, but when you are working on a contract, of the cotract, and its containment accoding the alienable rights.

Title: Why should we be aware of licenses?

Body:
I know this is common question, but why should a programmer be aware of software licenses as well as extensions and plugins licenses?

I'm working in a company which focuses on the business process (Ruby on Rails) and I'm curious as to why they are strict on such licenses in the project development.

What licenses should I be aware of and why?


问:
What is the best way to build a static page web site from a JSON API?
I have a JSON API that includes some discusssions. I want to build a static html site on another server, pages that are built from data on that API. I am more comfortable using Rails than Node. The API is done in Node. The idea is that I periodically call the JSON api to get the data, and dynamically build the html pages on the Rails server. This way the web pages would be super fast, wouldn't have to call the JSON API. One technology that looks like it would do the job is http://middlemanapp.com/, but I haven't used it before.

Anybody done this before and have any suggestions?

My preference is to use Rails, and Heroku.

答:
Your strategy sounds fine. Though, to be exact, you don't want Rails, which is framework for building dynamic web sites, you want static site generator that uses ruby. Middleman seems to be exactly that.

I don't have experience with Middleman, but I have used nanoc for the same job. It worked fine and got exactly the benefits you described.

Yet another choice would be Jekyll. It is used by Github Pages for example, which makes me think it probably has good community support.

Any of those should be fine for you. The best choice probably comes down to personal preference.


答:
Framework lock-in can be a serious issue, but it helps to look at the problem as one of portability. Portability is not an absolute attribute, but relative to your starting point and where you might possibly want to go. By analogy, then, software is portable only in so far as you have already ported it to other environments.

Most of the development of an application inside a framework tends to be glue code, the stuff that binds the components of your framework together. Configuration files may abstract a certain amount of the glue in some systems but a lot of the fine details have to be done in code.

On the other hand, business rules and processes can be abstracted from the application. The hard part of abstraction is when the rules are implemented directly by the framework; security, accessibility and process sequencing tend to be enforced by your framework and may be the hardest to see.

If you can separate the glue portion of your application from the business rule and business process and business data portion, then you will be able to make some portions of your solution portable.

Title: Is it possible to loosely couple an application to its framework?

Body:
Let's say I'm developing a web application. My first choice is to use PHP with Fat-Free Framework (F3) and MVC pattern. Next year, I might decide I want to switch to Zend Framework, or maybe even ASP.NET MVC. Does it make sense to try and design my application in such a way that it is loosely coupled to its framework, or is the framework too integral to make this realistic?

The only reason I ask is because it came up in conversation with a peer recently, who criticized my pie in the sky idea of loosely coupling my application to F3.


答:
If you are not restricted to Javascript, many functional programming languages allow you to use an approach similar to that suggested by dietbuddha (function composition operator). I will illustrate this using Haskell.

Your solution with intermediate variables would go like this:

```<code>floorSqrt :: Float -> String
floorSqrt num = let
                  sqrtNum   = sqrt num
                  floorSqrt = floor sqrtNum
                  stringNum = show floorSqrt
                in
                  stringNum
</code>```

The one-liner would be

```<code>floorSqrt num = show (floor (sqrt num))
</code>```

or also

```<code>floorSqrt num = (show . floor . sqrt) num
</code>```

or

```<code>floorSqrt = show . floor . sqrt
</code>```

i.e. you can compose the three functions using the . operator and apply the resulting function to the argument num. By using a composite function you can leave out the argument num from the definition, as illustrated in the last example above.

In general, if you have a sequence of functions

```<code>f1, ..., fn
</code>```

where, for i ∈ {1, ..., n} : fi : ai -> bi, and for i ∈ {1, ..., n - 1} : bi = ai + 1, you can define the composite function

```<code>compositeFunction = fn .   . f1
</code>```

If all the functions you want to compose have the same type a -> a, you can apply the foldr function to the list of functions you want to compose. For example, imagine you have the function

```<code>floorSqrt :: Float -> Float
floorSqrt = (fromIntegral . floor) . sqrt
</code>```

(note that we have to insert fromIntegral because floor does not return a Float). This can be written as

```<code>floorSqrt = foldr (.) id [fromIntegral . floor, sqrt]
</code>```

where foldr corresponds to reduce in dietbuddha's answer, and . to compose. The id function (identity) is needed as a starting point for the folding / reduction (I suppose this is implicit in the JavaScript example).

You can use the above pattern for any sequence of functions f1, ..., fn where, for i ∈ {1, ..., n}, fi : a -> a:

```<code>compositeFunction = foldr (.) id [fn, ..., f1]
</code>```

In Haskell, you cannot use this last pattern for your original example because foldr requires all functions in the list to have the same type. You can use it in JavaScript because it does not have this restriction (see dietbuddha's answer).

Title: Coding style for chained function calls

Body:
A common thing you need to do is to take a value, do something with it by passing it to a function, and then do some more with the return value, in a chain. Whenever I run into this type of scenario, I get unsure about how best to write the code.

As an example, let's say I have a number, num, and need to take the floored square root of it and turn it into a string. Here are a few possibilities (in JavaScript).

I might simply pass num to one function at a time, and replace num with the return value:

```<code>function floorSqrt(num) {
    num = Math.sqrt(num);
    num = Math.floor(num);
    num = String(num);
    return num;
}
</code>```

This is nice since I don't need the original num any more, but in practice it might be confusing to start with one thing (a number) and end up with something completely different (a string).

I can save each step in a new variable:

```<code>function floorSqrt(num) {
    var sqrtNum = Math.sqrt(num);
    var floorSqrt = Math.floor(sqrtNum);
    var stringNum = String(floorSqrt);
    return stringNum;
}
</code>```

Although it seems wasteful to declare all those variables and come up with good names for them.

Or I can just do it all as a one-liner:

```<code>function floorSqrt(num) {
    return String(Math.floor(Math.sqrt(num)));
}
</code>```

But for more than two functions that approach gets incredibly unreadable, almost like code golf.

It seems to me like the most beautiful way to do this would be with some stack-based language, which might look something like this (pseudo code):

```<code>[sqrt floor toString]
</code>```

Is there a way to do something similar with JavaScript? List some functions, run one at a time, and use the return value of each one as the argument for the next? The closest is how some libraries like jQuery or Underscore.js allow you to chain methods, something like this:

```<code>function floorSqrt(num) {
    return _.chain(num).sqrt().floor().toString().value();
}
</code>```

I'm sure many wise people have thought wise things about this. What are some thoughts on pros and cons of the different styles?

Body:
If you are not restricted to Javascript, many functional programming languages allow you to use an approach similar to that suggested by dietbuddha (function composition operator). I will illustrate this using Haskell.

Your solution with intermediate variables would go like this:

floorSqrt :: Float -> String
floorSqrt num = let
                  sqrtNum   = sqrt num
                  floorSqrt = floor sqrtNum
                  stringNum = show floorSqrt
                in
                  stringNum

The one-liner would be

floorSqrt num = show (floor (sqrt num))

or also

floorSqrt num = (show . floor . sqrt) num

or

floorSqrt = show . floor . sqrt

i.e. you can compose the three functions using the . operator and apply the resulting function to the argument num. By using a composite function you can leave out the argument num from the definition, as illustrated in the last example above.

In general, if you have a sequence of functions

f1, ..., fn

where, for i ∈ {1, ..., n} : fi : ai -> bi, and for i ∈ {1, ..., n - 1} : bi = ai + 1, you can define the composite function

compositeFunction = fn .   . f1

If all the functions you want to compose have the same type a -> a, you can apply the foldr function to the list of functions you want to compose. For example, imagine you have the function

floorSqrt :: Float -> Float
floorSqrt = (fromIntegral . floor) . sqrt

(note that we have to insert fromIntegral because floor does not return a Float). This can be written as

floorSqrt = foldr (.) id [fromIntegral . floor, sqrt]

where foldr corresponds to reduce in dietbuddha's answer, and . to compose. The id function (identity) is needed as a starting point for the folding / reduction (I suppose this is implicit in the JavaScript example).

You can use the above pattern for any sequence of functions f1, ..., fn where, for i ∈ {1, ..., n}, fi : a -> a:

compositeFunction = foldr (.) id [fn, ..., f1]

In Haskell, you cannot use this last pattern for your original example because foldr requires all functions in the list to have the same type. You can use it in JavaScript because it does not have this restriction (see dietbuddha's answer).


问:
Is OCaml any good for numerical analysis?
I'm currently using C and some FORTRAN to solve numerically systems of differential equations.

I'm a bit fed up with both of these languages but I need to have some (rather) efficient code... I'm thinking of switching to OCaml.

Is it worth it?

答:
First of all, I want to make the unusual statement that for numerical computations, high-level languages are much more useful in the long run than low-level languages. Let me loosely quote a researcher from Fraunhofer Institut working in numerical simulations used in weather forecasts.

In the last decade, CPUs became 1000 times faster while algorithms became 1000*1000 faster. This means, that today's algorithms running on yesterday's CPUs will beat yesterday's algorithms running on today's CPUs by a factor of 1000.

Obviously, there is much more parameters to take into account as CPU speed and algorithms, like disks or RAM, but that statement helps us to undestand that, if you choose a low-level language, you focus on the wrong factor (1000 instead of 1000*1000).

Of course, given any specific numerical algorithm one can expect C or Fortran to beat OCaml or Common Lisp by a (actually not that) large factor.  But if you are actually interested in numerical problems and are willing to improve algorithms, you should then pick a high-level language that will allow you to express your ideas at a high level and to easily improve algorithms.

As a side note, if you consider writing numerical code in OCaml, you should definitely know about how OCaml pass parameters to functions, inline functions and unbox floats.  All of this is detailed in Xavier Leroy's notes.


问:
Can modern OO languages compete with C++'s array store performance?
I just noticed that every modern OO programming language that I am at least somewhat familiar with (which is basically just Java, C# and D) allows covariant arrays. That is, a string array is an object array:

```<code>Object[] arr = new String[2];   // Java, C# and D allow this
</code>```

Covariant arrays are a hole in the static type system. They make type errors possible that cannot be detected at compile-time, so every write to an array must be checked at runtime:

```<code>arr[0] = "hello";        // ok
arr[1] = new Object();   // ArrayStoreException
</code>```

This seems like a terrible performance hit if I do lots of array stores.

C++ does not have covariant arrays, so there is no need to do such a runtime check, which means there is no performance penalty.

Is there any analysis done to reduce the number of runtime checks necessary? For example, if I say:

```<code>arr[1] = arr[0];
</code>```

one could argue that the store cannot possibly fail. I'm sure there are lots of other possible optimizations I haven't thought of.

Do modern compilers actually do these kinds of optimizations, or do I have to live with the fact that, for example, a Quicksort always does O(n log n) unnecessary runtime checks?

Can modern OO languages avoid the overhead created by supporting co-variant arrays?

答:
or do I have to live with the fact that, for example, a Quicksort always does O(n log n) unnecessary runtime checks?

CPU performance is not monotonic, which means that longer programs can be faster than shorter ones (this is CPU dependant, and it is true for the common x86 and amd64 architectures). So it is possible that a program doing bound checking on arrays is actually faster than the program deduced from the previous by removing these bound checking.

The reason of this behaviour is that bound checking modifies the alignment of code in memory, will modify the frequency of cache hits, etc.

So yes, live with the fact that Quicksort always does O(n log n) spurious checks and optimise after profiling.

OwnerDisplayName: FredOverflow


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
This more an example of how not having coding standards can hurt.

A contractor working at a large bank insisted that following the standards were the best ever. The application was written in dBase/Clipper which he was the sole developer for and of course he came up with the standard.

Everything is in upper case. I mean everything, including the rare comments he made.

No indentation.

Variable naming was something along the lines of APRGNAME. A = scope of variable, eg P for public, PRG = first three characters of the source file that created the variable, NAME = variable name in the remaining 6 characters that dBase/Clipper allowed.

The first 4 and last 4 lines of the source code were 80 * long. Why? So he could hear the dot matrix printer starting and finishing the printing of a file. Memory is the entire program was printed via the mainframe weekly, 20,000 pages.

I'm sure there were many more that I've managed to dump from my brain.

I was a very new self-taught programmer at that stage but knew enough not to listen to the mad scientist and get the hell out of there before I asked to take over the project.

And yes we told management how bad these practices were but always got the usual "were paying this contractor top dollar he must know what he's talking about".


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Measure, Measure, Measure

So fine, measure away, but for isolating performance bugs, measuring works about as well as successive elimination. Here is the method I use.

I've been trying to track down the source of the measure-measure "wisdom". Somebody with a tall enough soapbox said it, and now it travels.


答:
Professional courtesy comes to mind. If you want other's to follow your licensing (+ fee's), then you should respect and uphold licensing within the industry.

Risk mitigation is also important to lawyers, who often try and protect businesses against bad risks. EULA and licensing of 3rd party code is all about risk management for both parties, supplier and consumer.

Title: Why should we be aware of licenses?


问:
How to represent compound elements within a database?
I need to design a database table that holds the data of programmers work hours.

The problem is that I have a compound type - two pieces of data belong to a category.

Specifically, the work hours are classified into categories: design, program, test, troubleshoot, etc... and each category is divided into two types: hours spent at work and hours spent at home.

How can I design a compound type in the database side?

I thought about storing the two types in one field like "6,2" but that creates more problems to resolve.  I would now have to convert and split data along with worrying about localization issues, missing data, or if another location was added to the categories.

Clarification:

Asking my question a different way, it's relatively easy to design a table without compound types like this:

But how to deal with it when each category is split into two types?

答:
```<code>Table
-> Relationship

Employee -> WorkHours (Hours)
WorkHours -> WorkCategory (Work, Home)
WorkHours -> HoursCategory (Design, Test, Program, Troubleshoot)
</code>```

An employee can have one or more workhours, a workhour has an hours value and relationships to lookup tables for category of work and category of kinds of hours. This should capture how many hours of what kind of work an employee did and where they did that work.

Body:
Table
-> Relationship

Employee -> WorkHours (Hours)
WorkHours -> WorkCategory (Work, Home)
WorkHours -> HoursCategory (Design, Test, Program, Troubleshoot)

An employee can have one or more workhours, a workhour has an hours value and relationships to lookup tables for category of work and category of kinds of hours. This should capture how many hours of what kind of work an employee did and where they did that work.


答:
Database tables are, by nature, two-dimensional creatures.  The simplified version in your clarification, which is hours by name and activity, works just fine because there are only to dimensions to the data (name and activity).  Introducing location adds a third dimension, and the fact that you had to start thinking about ways to store the data in something other than a native type means you've outgrown the model.

Fortunately, there's normalization, which is the process of making sure you avoid duplication in your tables by thinking about your data in terms of what all the individual pieces are and how they relate to each other.  (That last bit is why SQL databases are called relational.)

Looking at the table in your question, I see four things:

Hours worked

Employees

Activities

Locations

One thing you may notice is that you have a lot of hours worked, and each of those figures can be tied to an an employee, and activity and a location.  Those ties are the relations in your data.  Each relation is a dimension and an opportunity to split things that might be duplicated into a separate table:

```<code>CREATE TABLE employees (id NUMERIC, name VARCHAR(100))
CREATE TABLE activities (id NUMERIC, label VARCHAR(100))
CREATE TABLE locations (id NUMERIC, place VARCHAR(100))
</code>```

Each table gets populated with the possible values for those attributes, such as these one for activities:

```<code>1  'Design'
2  'Program'
3  'Test'
3  'Troubleshoot'
</code>```

Your table of hours worked can then have as many dimensions as you need by referring to the others using foreign keys:

```<code>CREATE TABLE hours_worked (
    id          NUMERIC,
    employee    NUMERIC,  -- Foreign key into employees(id)
    activity    NUMERIC,  -- Foreign key into activities(id)
    location    NUMERIC,  -- Foreign key into locations(id)
    time_spent  NUMERIC
)
</code>```

Once you've done this, you can use JOINs to do a wide variety of queries, some of which would have required writing code to query and assembly had everything been left denormalized:

```<code>-- Your table, which uses all three dimensions
SELECT employee.name, activity.label, locations.place, time_spent
FROM
  hours_worked
  JOIN employees ON hours_worked.employee = employees.id
  JOIN activity  ON hours_worked.activity = activities.id
  JOIN location  on hours_worked.location = locations.id
ORDER BY xxx -- Whatever's appropriate here

-- Number of hours worked at home, which uses only one dimension
SELECT SUM(time_spent)
FROM
  hours_worked JOIN location ON hours_worked.location = location.id
WHERE
  location.place = 'Home'
</code>```

Normalization also imparts considerable flexibility.

If your bosses decide that they also want to keep track of hours by project, your three-dimensional relationship becomes four-dimensional, and if you thought stuffing 3-D data into a 2-D model was going to be hairy, 4-D is worse.  Fortunately, a normalized database just requires the addition of another table...

```<code>CREATE TABLE projects (id NUMERIC, name VARCHAR(100))
</code>```

...and another column to hours_worked:

```<code>    project     NUMERIC,  -- Foreign key into projects(id)
</code>```

POOF!  With a very small amount of work, you've just added an additional dimension.

Are people working at coffee shops in addition to the office and at home?  Insert a row into locations and you're good to go.

Have you decided that "programming" should have been called "development?"  Change that single row in activities and any queries you do afterward will have the right label attached.

Title: How to represent compound elements within a database?

Body:
I need to design a database table that holds the data of programmers work hours.

The problem is that I have a compound type - two pieces of data belong to a category.

Specifically, the work hours are classified into categories: design, program, test, troubleshoot, etc... and each category is divided into two types: hours spent at work and hours spent at home.

How can I design a compound type in the database side?

I thought about storing the two types in one field like "6,2" but that creates more problems to resolve.  I would now have to convert and split data along with worrying about localization issues, missing data, or if another location was added to the categories.

Clarification:

Asking my question a different way, it's relatively easy to design a table without compound types like this:

But how to deal with it when each category is split into two types?

Body:
Database tables are, by nature, two-dimensional creatures.  The simplified version in your clarification, which is hours by name and activity, works just fine because there are only to dimensions to the data (name and activity).  Introducing location adds a third dimension, and the fact that you had to start thinking about ways to store the data in something other than a native type means you've outgrown the model.

Fortunately, there's normalization, which is the process of making sure you avoid duplication in your tables by thinking about your data in terms of what all the individual pieces are and how they relate to each other.  (That last bit is why SQL databases are called relational.)

Looking at the table in your question, I see four things:

Hours worked

Employees

Activities

Locations

One thing you may notice is that you have a lot of hours worked, and each of those figures can be tied to an an employee, and activity and a location.  Those ties are the relations in your data.  Each relation is a dimension and an opportunity to split things that might be duplicated into a separate table:

CREATE TABLE employees (id NUMERIC, name VARCHAR(100))
CREATE TABLE activities (id NUMERIC, label VARCHAR(100))
CREATE TABLE locations (id NUMERIC, place VARCHAR(100))

Each table gets populated with the possible values for those attributes, such as these one for activities:

1  'Design'
2  'Program'
3  'Test'
3  'Troubleshoot'

Your table of hours worked can then have as many dimensions as you need by referring to the others using foreign keys:

CREATE TABLE hours_worked (
    id          NUMERIC,
    employee    NUMERIC,  -- Foreign key into employees(id)
    activity    NUMERIC,  -- Foreign key into activities(id)
    location    NUMERIC,  -- Foreign key into locations(id)
    time_spent  NUMERIC
)

Once you've done this, you can use JOINs to do a wide variety of queries, some of which would have required writing code to query and assembly had everything been left denormalized:

-- Your table, which uses all three dimensions
SELECT employee.name, activity.label, locations.place, time_spent
FROM
  hours_worked
  JOIN employees ON hours_worked.employee = employees.id
  JOIN activity  ON hours_worked.activity = activities.id
  JOIN location  on hours_worked.location = locations.id
ORDER BY xxx -- Whatever's appropriate here

-- Number of hours worked at home, which uses only one dimension
SELECT SUM(time_spent)
FROM
  hours_worked JOIN location ON hours_worked.location = location.id
WHERE
  location.place = 'Home'

Normalization also imparts considerable flexibility.

If your bosses decide that they also want to keep track of hours by project, your three-dimensional relationship becomes four-dimensional, and if you thought stuffing 3-D data into a 2-D model was going to be hairy, 4-D is worse.  Fortunately, a normalized database just requires the addition of another table...

CREATE TABLE projects (id NUMERIC, name VARCHAR(100))

...and another column to hours_worked:

    project     NUMERIC,  -- Foreign key into projects(id)

POOF!  With a very small amount of work, you've just added an additional dimension.

Are people working at coffee shops in addition to the office and at home?  Insert a row into locations and you're good to go.

Have you decided that "programming" should have been called "development?"  Change that single row in activities and any queries you do afterward will have the right label attached.


问:
Should if/else statements be arranged by rareness of cases or difficulty of dealing with them?
In some code I'm writing right now, I have something like this:

```<code>if (uncommon_condition) {
    do_something_simple();
} else {
    do();
    something();
    long();
    and();
    complicated();
}
</code>```

Part of me thinks "It's fine the way it's written. Simple cases should go first and more complicated cases should go next." But another part says: "No! The else code should go  under the if, because if is for dealing with unusual cases and else is for dealing with all other cases." Which is correct or preferable?

答: As for such scenarios there is no thumb rule for it. But possibly we can follow to write the positive or most likely code in the if block and left out in the else block or default cases.</p>


答:
There are already great answers here, but I want to throw in my 2¢.

By using the piece of software, you've agreed to the license. Know what you are agreeing to is a general piece of advice which applies to all of life.

By using the piece of software, the legal entity you are working for is bound to the terms of the license. If this is your employer, you may be exposing them to millions of dollars in legal fees and/or personally committing a career limiting move.

By using the piece of software, you are showing that you value that software. Show respect for things you value. In software, that respect is conforming to the terms of the license. As a corollary, if you don't value a piece of software, then don't use it.

Title: Why should we be aware of licenses?


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
Generalised switch has said above :

```<code> switch(x){
  predicate1:
     dosomething();
  predicate2:
     dosomethingelse();
 }
</code>```

In Haskell :

```<code>  switch' :: a -> [(a -> Bool, b)] -> b
  switch' a [] = undefined
  switch' a (f,b):xs = if f a
                     then b
                      else switch' a xs
</code>```

Body:
Generalised switch has said above :

 switch(x){
  predicate1:
     dosomething();
  predicate2:
     dosomethingelse();
 }

In Haskell :

  switch' :: a -> [(a -> Bool, b)] -> b
  switch' a [] = undefined
  switch' a (f,b):xs = if f a
                     then b
                      else switch' a xs

OwnerDisplayName: John John


答: Scala is an OO language that has invariant, rather than covariant, arrays. It targets the JVM, so there's no performance win there, but it avoids a misfeature common to both Java and C# that compromises their type-safety for reasons of backwards compatibility.</p>

Title: Can modern OO languages compete with C++'s array store performance?

Body:
I just noticed that every modern OO programming language that I am at least somewhat familiar with (which is basically just Java, C# and D) allows covariant arrays. That is, a string array is an object array:

```<code>Object[] arr = new String[2];   // Java, C# and D allow this
</code>```

Covariant arrays are a hole in the static type system. They make type errors possible that cannot be detected at compile-time, so every write to an array must be checked at runtime:

```<code>arr[0] = "hello";        // ok
arr[1] = new Object();   // ArrayStoreException
</code>```

This seems like a terrible performance hit if I do lots of array stores.

C++ does not have covariant arrays, so there is no need to do such a runtime check, which means there is no performance penalty.

Is there any analysis done to reduce the number of runtime checks necessary? For example, if I say:

```<code>arr[1] = arr[0];
</code>```

one could argue that the store cannot possibly fail. I'm sure there are lots of other possible optimizations I haven't thought of.

Do modern compilers actually do these kinds of optimizations, or do I have to live with the fact that, for example, a Quicksort always does O(n log n) unnecessary runtime checks?

Can modern OO languages avoid the overhead created by supporting co-variant arrays?


答:
In JavaScript many people consider it best practice to write all the semicolons they would need in other C branch languages, (and a lot of them ain't afraid to point out the "error" whenever they see code that could have more semicolons). I never found a need for them, their role as visual marker is already filled by line shifts.

On a side note it is kinda funny to see a compiler requiring semicolons, but still confidently throw the error "Missing semicolon". "We both know what you meant to write, but I must reject your application because I formally ain't allowed to distinct between spaces and line shifts."

A number of other JavaScript/C-style best practices are circulating, but none of them come close in terms of hype without qualified arguments.

Edit: It is perfectly possible to minify code without semicolons Closure Compiler will insert them as needed.

Title: What popular "best practices" are not always best, and why?

Body:
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.


问:
Deploying artifacts and dependencies on another system with Maven
I am coding a Java program on my development machine. Maven packages this a myjar.jar, and I can run it from the command line using java -cp myjar.jar my.FantasticClass. It uses library somelib.jar. I use Maven, and the project is hosted on github.

When I want to run my project on the target machine, what is the best way to go?

I could package my code as a jar, grab the somelib.jar and move it to the target machine manually, but I suppose I could also check out the Maven project from github on the target machine, run it, and have Maven both generate the jar and get the somelib.jar file.

Or am I simply overlooking something?

答:
I found this solution on StackOverflow - use maven-assembly-plugin, and invoke

```<code>mvn clean compile assembly:single
</code>```

Then I can just run the jar like this:

```<code>java -jar MyJar.jar
</code>```

Here are the required additions to the POM file. My main class is demo.GraphTest

```<code>  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>demo.GraphTest</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </plugin>
    </plugins>
    </build>
</code>```

Body:
I found this solution on StackOverflow - use maven-assembly-plugin, and invoke

mvn clean compile assembly:single

Then I can just run the jar like this:

java -jar MyJar.jar

Here are the required additions to the POM file. My main class is demo.GraphTest

  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>demo.GraphTest</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </plugin>
    </plugins>
    </build>


答:
Whenever I read a User Story, my first question is "Really?"  I put myself in the role of the User and ask "Do I REALLY want that feature". Security is one of those areas where User Stories are often written from the perspective of the user of a system but, as others have pointed out, they don't want to have to login, or create complex passwords.  They just want to get to their stuff and have their stuff protected.

As well as asking the "Really?" question, I look to see if the User Story demands a particular solution. Security is, once again, a great example. Most User Stories do seem to insist on requiring passwords. But why? I like to write User Stories such that I give the developers room to consider alternatives. By doing this, we create an environment that encourages innovation. A good thing.

So, here's what I'd like to see:

As a New Member
I want to create an account quickly and easily
So that I can access Member Benefits

or maybe:

As a Current Member
I want my personal information kept private
So that I can maintain my privacy

Finally, if the "As a ... I want ... So that ..." template isn't helping you, feel free to use something else but I'd advise that you understand the reasons why (and "It's too difficult" is probably not the best answer :)


问:
How do you handle multiple developer configuration in a project?
I've been thinking lately about how I handle config changes between multiple developers on a project.

Specifically here about a Laravel project in PHP, but I guess this applies largely to all frameworks/languages.

In general would you say it's a best practice to not commit your configuration? If so what's your practice for doing this with version control such as git?

Or do you set up each configuration as a different environment config? E.g. In Laravel there are environment configs, so each developer has a directory of just their own different settings, and this is what I'm currently using. Then in the code you can set how Laravel will detect which environment it's on. This works, I'm just wondering what other developers working on projects with other developers do.

答:
You're doing it right

The benefit is that you are actually testing the mechanisms which will be used when deploying to other environments; test, staging, production, etc. Each developer will be automatically verifying that environment specific configuration is working.

I have tried the template approach and not checking in each developers configuration. This works but you will find from time to time something breaks for everyone.

OwnerDisplayName: Andrew


问:
Is it a bad practice to include all the enums in one file and use it in multiple classes?
I'm an aspiring game developer, I work on occasional indie games, and for a while I've been doing something which seemed like a bad practice at first, but I really want to get an answer from some experienced programmers here.

Let's say I have a file called enumList.h where I declare all the enums I want to use in my game:

```<code>// enumList.h

enum materials_t { WOOD, STONE, ETC };
enum entity_t { PLAYER, MONSTER };
enum map_t { 2D, 3D };
// and so on.

// Tile.h
#include "enumList.h"
#include <vector>

class tile
{
    // stuff
};
</code>```

The main idea is that I declare all enums in the game in 1 file, and then import that file when I need to use a certain enum from it, rather than declaring it in the file where I need to use it. I do this because it makes things clean, I can access every enum in 1 place rather than having pages openned solely for accessing one enum.

Is this a bad practice and can it affect performance in any way?

答:
This sort of thing becomes an issue when you have multiple developers working on the same code-base.

I have certainly seen similar global files becoming a nexus for merge collisions and all sorts of grief on (larger) projects.

However, if you are the only one working on the project, then you should do whatever you are most comfortable with, and only adopt "best practices" if you understand (and agree with) the motivation behind them.

It is better to make some mistakes and learn from them than to risk getting stuck with cargo cult programming practices for the rest of your life.


问:
Cascading "Deleted" records that aren't really deleted
Just trying to get some ideas on what people do for this scenario.
We have a system database(SQL Server 2008 R2) that has tables and every table has a field we can call "Deleted".  It's basically a bit field if its a 1 the record is deleted, if it is a 0 it is not deleted.  The field is not nullable and its default is of course 0.

We cannot allow real deletions to the database, so to get around this we set a bit field (Deleted) to true.  In our application we end up with queries that look like this:

SELECT blah FROM MyTable WHERE .. AND Deleted=0

Basically we filter for records so we only get non deleted rows.  Our issue is related records that need to cascade.  What do people prefer, should we be doing this in the server side code so that when you delete a record it delete's (Sets the deleted bit field to true) for all related records?  Or should this be a trigger that has to check this field and sets the bit field for all related records to 1?

Or are we completely on the wrong path?

答:
I've done this before with audit tables whereby every change to a database is written to an audit mirror table (Insert / Update / Delete) and the actual real items are deleted in a cascade manner.

The mirror tables are identical to the real table with the addition of 3 columns, "ChangeType", "User", "Date".

This has the dual advantage of being able to delete data correctly but also allowing for the state of the database to be recreated at any point in time and for the complete history of any item to be documented.

I'll add that for cascading deletes, generally I prefer cascading deletes on the client - the server shouldn't try to be too clever about this, if a user deletes a company and that has associated issues - the delete company action should also delete any corresponding records.

This was for a financial management system for a major investment bank so the auditability was a critical feature.


问:
Why should we be aware of licenses?
I know this is common question, but why should a programmer be aware of software licenses as well as extensions and plugins licenses?

I'm working in a company which focuses on the business process (Ruby on Rails) and I'm curious as to why they are strict on such licenses in the project development.

What licenses should I be aware of and why?

答:
As answer by means of example, consider a simple (rather common) sort of problem:

You have a problem that requires you lookup the distance in miles between two given US postal zip-codes for a search feature. It turns out there is a library available that does this super easily, so you just grab it and - problem solved! You just cut days, or weeks, out of the project schedule.

Uh...but, is that legal? Well, that's where licenses and copyright come in. Sometimes code/software is provided "free for non-commercial use", for instance, but with the requirement that everyone else has to contact the author to negotiate a contract or pay a license fee. Some licenses, especially in the GPL realm, permits any use of the code, so long as it is not compiled together with other code and sold without attribution or under a different license.

This quickly turns into something that makes you want to cry, or at least makes you willing to turn your monitor upside down and from then on do all your coding while suspended from the ceiling by your toes. It's just a filthy mess.

If software is your business and you are in charge of this, you'll need to do a lot of learning about what licenses conflict with others, pros and cons, etc. But if you are working for someone else who is kind enough to have paid out thousands in lawyer fees to develop a policy of what code/software licenses can and cannot be used in the project - stop what you are doing and go give those people a hug. They probably need it. They might sue you for it though...so maybe just say "thank you" instead.

To answer your question about specific licenses, you don't necessarily have to be aware of any particular license, just whatever the business says is and is not OK. There are so very many licenses, with so many individual incarnations and details, and in a business setting there are very different demands than in a personal project.

The final "why" is three-fold: being a good "software community" citizen by not ripping off people's work and accidentally (or intentionally) passing it off as your own or otherwise stepping one people's toes who are literally giving you hours of work for "free", not exposing the company to potentially millions of dollars in legal costs, and making sure people are getting paid for use of their work if this is appropriate.

I wish it was all unnecessary, back in the old days of the "free information" hacker dream...but in part that dream is why so many software licenses became necessary. It's an interesting history, far beyond the scope of this Q&A. But they exist, so you can either do lots of research...or take your companies word it. Their policies do exist for really, really good reasons (or at least in this particular case).

Title: Why should we be aware of licenses?


问:
What is meant by "Now you have two problems"?
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?

答:
The problem is that regex is a complicated beast, and you only solve your problem if you use regex perfectly. If you don't, you end up with 2 problems: your original problem  and regex.

You claim that it can do the work of a hundred lines of code, but you could also make the argument that 100 lines of clear, concise code is better than one line of regex.

If you need some proof of this: You can check out this SO Classic or simply comb through the SO Regex Tag


答:
There are a few things going on with this quote.

The quote is a restatement of an earlier joke:

Whenever faced with a problem, some people say "Lets use AWK." Now, they have two problems. — D. Tilbrook

It is a joke and a real dig, but it's also a way of highlighting regex as a bad solution by linking it with other bad solutions. It's a great ha ha only serious moment.

To me—mind you, this quote is purposely open to interpretation—the meaning is straight forward. Simply announcing the idea of using a regular expression has not solved the problem. In addition, you've increased the cognitive complexity of the code by adding an additional language with rules that stand apart from whatever language you are using.

Although funny as a joke, you need to compare the complexity of a non-regex solution with the complexity of the regex solution + the additional complexity of including regexes. It may be worthwhile to solve a problem with a regex, despite the additional cost of adding regexes.

Title: What is meant by "Now you have two problems"?

Body:
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?