答:
There are two kinds of code here: Your code, and someone else's code.

The code that YOU wrote is yours.  You can mark it any way you want.

The code that someone ELSE wrote, that you included in your project, is NOT yours.  This includes code that you modified, as opposed to originated.  You got that code under the terms of their license, presumably BSD, and you are required by law to continue to observe the terms of their license.

Among other things, that means that you can't change the copyright notice and license on their code.

Having said all that, here's the ground reality.  There exist scumbags.  The scumbags will grab your code, regardless of your notices, remove the notices, file off the serial numbers, and do what they want.  When and if you discover what one scumbag did, you will have the opportunity to spend thousands or tens of thousands of dollars going after him.  While you are going after him, fifty other scumbags will be doing the same thing.

If you choose to work in an arena in which you must distribute source code, you accept that you are going to have to deal with scumbags who will ignore the law and copy your code.  Client-side Javascript is inherently such an arena.  If you don't want to deal with scumbags copying your code for their profit, you need to work in an arena in which you don't have to distribute source code.  Deal with it.

Title: Licensing code "not for reuse"

Body:
I have a client-side Javascript framework that is publicly available and BSD licensed.  Each file says it is copyright me, the date, all rights reserved, and the BSD license text.

I am making a project which uses - and adapts and makes code changes to - my BSD licensed framework.  Although obviously browsers will download and execute this code, I don't want to BSD license my derived project.  I don't object to people seeing my code, but I don't want them to cut-n-paste and make derivatives of my project.

What boilerplate text do I put at the top of each file?

I would like to include a link to my BSD-licensed framework too.  How should I phrase that?


问:
Is it appropriate to have positive comments in code reviews, or is it exclusively for constructive criticism?
I have been doing a lot of code review lately, and I am unsure of the positive and negative effects and professionalism of putting positive and/or funny comments in code reviews.

We use Github as our code review platform on my team, so the comments are viewable by anyone.  I generally try to use this platform so the entire process from start to finish is visible and historical.

答:
Commenting in a code review is managing

Treat comments as a tool of management

Inserting comments into a code review is a form of management. As such, it should be approached as a tool of management.

Use managerial practices when commenting

There is a structure to managing people where the goal is to meet a desired outcome. Some of the main approaches to management will not apply in comments but most will. The applicable topics include environment, leadership, organizing, and controlling.

Environment

Culture

The environment dictates the style of management. The culture and environment of the workplace should be kept in mind when using any tools of management. Usually this is affected by the industry and the size of the company or entity being managed.

Style

If there is a lighthearted culture then that may come across in the style of management being used. If there are very strict guidelines, policies, and consequences then that should be reflected in the style used. So if everyone is on board for a star wars joke referencing droids and a weak minded stormtrooper then a comedic interjection may be applicable. However, if there are dire consequences of not taking the end result seriously then it may need to be avoided.

Leadership

Fundamentals

There are three main pillars of leadership to consider when commenting. Namely they are vision, communication, and judgement.

Vision

It is important when to keep the grand vision in mind when explaining or giving instructions. In comments, this could mean pointing out how small changes affect the project as a whole, what the implications are of taking different approaches, or a tip of the hat to separation of concerns.

Communication

Being a good communicator is important in many aspects of life. It is no different in comments. Employing a wise level of brevity is important - especially since comments shouldn't take much space. Get to the point early, and then back it up with an example if necessary. In a larger organization, this may also include the need to send out a communique or memo if the issue is not localized to one review session.

Judgement

It is important that strategy is used when judging whether or not comments need to be made, and what the changes need to be. Your judgement does not always need to be correct, but it does need to be consistently correct especially when large judgement calls are made.

Organizing

From a managerial standpoint, organizing will refer to keeping the end goal in mind and ensuring that processes are aligned to follow a set of rules. Comments should also keep this in mind in that the comments should when possible build on each other to make sure that the flow of design is followed. It will also be important to keep in mind the scope of the code being reviewed in order to reduce coupling and follow the overall design.

Controlling

Controlling the actions of those being managed is a delicate process. While being firm it should also be kept in mind that the people are important. There are several managerial skills to use while controlling others. These skills are political, conceptual, interpersonal, diagnostic, and technical.

Political

Politics can be found any time there is interaction between people. It is a huge topic, but in a general sense politics revolves around influence. It is important to keep in mind the personal and professional politics at work when making a comment. This could be related to an instruction, a joke, or even a question.

Conceptual

Managing through conceptualization is an important tool. It requires a complex analysis of the situation at hand. When commenting it can be beneficial to include some of the analysis used to come up with the conclusion or change indicated in the review.

Interpersonal

Interpersonal skills are very important when managing. This is also a large topic. Some of the important things to consider with interpersonal skills are mentoring, constructive criticism, and "harpooning".

Mentoring

It is important that management is seen more as a mentor than as an antagonist. In a code review, this means that sometimes it will be beneficial to include a nod to a design pattern or approach which could be used to improve a situation.

Constructive Criticism

Criticism is important because it invokes reflection. However, criticism should be kept as positive as possible when it can be. This means offering valid evidence to support the criticism, and also ensuring that the tone used is not negative. When reviewing code this could include showing an exception or possible scenario which would generate an error while implying a solution instead of showing every place which was incorrect when the whole piece of code would need to be replaced anyway.

"Harpooning"

"Harpooning" is when you figuratively harpoon someone to the ground. This is done by breaking them down step by step without any reprieve until the point that they feel unable to get up. If you harpoon a person in a code review or elsewhere you will lose their cooperation. It is important to avoid breaking someone down excessively.

Executive Summary

Treat comments in a code review as a managerial tool. Keep in mind that comments should be brief, to the point, and constructive. Also ensure that while commenting the person being reviewed is taken into consideration.

ContentLicense: CC BY-SA 3.0


问:
Adding base-class (inherited) functionality to classes that you don't control
I have a set of classes from a 3rd party library. These classes use an inheritance structure to share logic. I would like to add a layer of abstraction in the middle of their inheritance tree to add functionality to all of the children (concrete) implementations.

Here is a simplified example of the classes in the 3rd party lib:

```<code>public interface IAnimal
{
    bool IsMammal { get; }
}

public abstract class Animal : IAnimal
{
    public abstract bool IsMammal { get; }
    public string Name { get; set; }
}

public class Cat : Animal
{
    public override bool IsMammal { get { return true; } }
    public void Pur() {}
}

public class Dog : Animal
{
    public override bool IsMammal { get { return true; } }
    public void Fetch() {}
}

public class Snake : Animal
{
    public override bool IsMammal { get { return false; } }
    public void ShedSkin() {}
}
</code>```

I would like to add the concept of an AnimalWithSuperPower. These types of animals should have 1 additional Property; SuperPower. I would like to be able to have classes like CatWithSuperPower which derive from Cat, AnimalWithSuperPower, & Animal so that I can access all the functionality of those.

Here is the definition of SuperPower:

```<code>public enum SuperPower { Invisibility, SuperStrength, XRayVision }
</code>```

My first idea was to use multiple inheritance. But unfortunately, C# doesn't support multiple base classes.

```<code>private abstract class AnimalWithSuperPower : Animal
{
    public SuperPower SuperPower { get; set; }
}

// doesn't compile because you can't extend 2 classes
private class DogWithSuperPower : AnimalWithSuperPower, Dog {}
</code>```

My next attempt uses a combination of inheritance, composition, and generics to try to deliver the functionality of the base classes.

```<code>private abstract class AnimalWithSuperPower<TAnimalType> : Animal where TAnimalType : IAnimal
{
    public SuperPower SuperPower { get; set; }

    protected readonly TAnimalType Animal;

    protected AnimalWithSuperPower()
    {
        Animal = (TAnimalType) Activator.CreateInstance(typeof(TAnimalType));
    }
}

private class SuperCat : AnimalWithSuperPower<Cat>
{
    public override bool IsMammal { get { return Animal.IsMammal; } }
}

private class SuperCatWithPur : AnimalWithSuperPower<Cat>
{
    public override bool IsMammal { get { return Animal.IsMammal; } }

    public void Pur() // needing duplicate pass-through methods/properties like this is painful :(
    {
        Animal.Pur();
    }
}

private static void ExampleUsage()
{
    var invisibleCat = new SuperCat { SuperPower = SuperPower.Invisibility };
    invisibleCat.Pur(); // doesn't compile - can't access Pur() method because doesn't extend Cat

    var xrayCat = new SuperCatWithPur { SuperPower = SuperPower.XRayVision };
    xrayCat.Pur(); // only works because I exposed the method with the EXACT same signature
}
</code>```

This solution is not very good (IMO) because of these reasons:

SuperCat and SuperCatWithPur aren't actually instances of Cat

any method you wish to use from Cat needs to be mirrored in the container class

feels kind of messy: AnimalWithSuperPower is an Animal but it also takes an Animal type parameter

I also tried doing it with an extension method but it wasn't any better than the above two attempts:

```<code>private abstract class AnimalWithSuperPower : Animal
{
    public SuperPower SuperPower { get; set; }
}

private static AnimalWithSuperPower WithSuperPower(this Animal animal, SuperPower superPower)
{
    var superAnimal = (AnimalWithSuperPower) animal;
    superAnimal.SuperPower = superPower;
    return superAnimal;
}

private static void ExampleUsage()
{
    var dog = new Dog { Name = "Max" };
    var superDog = dog.WithSuperPower(SuperPower.SuperStrength);
    superDog.Fetch(); // doesn't compile - superDog isn't an instance of Dog
}
</code>```

If I had control of the 3rd party classes, I could likely do this cleanly by introducing a new class in the middle of the inheritance tree, but I can't

My Question:

How can I model AnimalWithSuperPower so that:

instances are considered of types Cat (or appropriate sub-class), Animal, & AnimalWithSuperPower

all the methods and properties are available without extra pass-through calls

答:
Why don't you just use interfaces?

If you're concerned about sharing functionality, you can use extension methods to serve as your pseudo-base class.  It's not exactly ideal, but it should get what you're looking for done.

Something along the lines of:

```<code>public interface IAnimalWithSuperPower {
    public SuperPower power { get; set; }
}

public class SuperCat : Cat, IAnimalWithSuperPower {
    public SuperPower power { get; set; }
    public SuperCat() {
        SuperPower = SuperPower.SuperStrength;
    }
}

public static void UseSuperPower(this IAnimalWithSuperPower animal) {
    animal.power.doSomething();
}
</code>```

Body:
Why don't you just use interfaces?

If you're concerned about sharing functionality, you can use extension methods to serve as your pseudo-base class.  It's not exactly ideal, but it should get what you're looking for done.

Something along the lines of:

public interface IAnimalWithSuperPower {
    public SuperPower power { get; set; }
}

public class SuperCat : Cat, IAnimalWithSuperPower {
    public SuperPower power { get; set; }
    public SuperCat() {
        SuperPower = SuperPower.SuperStrength;
    }
}

public static void UseSuperPower(this IAnimalWithSuperPower animal) {
    animal.power.doSomething();
}


问:
Should validation rules be tested?
If I have a method taking input and giving output, it's a no-brainer that tests should be written. But what about things like validation rules?

For example, I add a validation rule that a certain property must be at least 5 characters long. Should I then write a UI test to check for an error message when the form field is empty? Assume that the validation library itself works fine, the only thing I do is add a one-liner to specify this rule.

I'm leaning towards no, because I'd only be duplicating the validation rules, and if the rules itself are set up incorrectly, the test will probably also be incorrect. However, I'd very much like to hear people's opinion and experience on this.

答: It'll only take a few lines of code to test it, and that will 1 - give you confidence that the spec is still being met if you change the code, and 2 - make the tests a better documentation of the spec. Remember that unit tests are documentation and regression tests, not just proof that your first implementation works.</p>

Title: Should validation rules be tested?


问:
By the definition of a Tree(ADT), is it "wrong" for a node to add a sibling?
The title pretty much says it all. I'm just having a little computer science exercise and am building a Tree. I want a node to be able to add a sibling which requires one to first get a reference to the parent, obviously. I was wondering what is the "correct" way, by definition of what a Tree is, to do such a thing?</p>

答:
Well, you add a child to the parent.

But consider that the root can't add a sibling. This means that sibling-adding isn't something that a node in general knows how to do. You can check whether the parent is null, but (assuming you're doing OO) purists would say to put "add sibling" somewhere outside of your node class. Often you have a wrapping "Tree" class which holds a root node; the Tree class might be a good place for a static "add sibling" method.


问:
Multiple scrum teams moving to single backlog
We currently have 5 scrum teams that work off their own product backlog for the past year.
Each team works on their own dedicated system but underlying technology is the same .Net.

There has been a lot of discussion on moving to feature based teams working off a single backlog. The reason is one of our main systems has a significant amount of work coming and their is not enough capacity to deliver all the work in the year. The other reason which I believe is the significant one is it gives greater flexibility to adjust to changes in the portfolio rapidly.

A decision been made to change two teams to work on a single backlog but the devs don't have experience on the other systems. One thing we're doing is cross-skilling by moving an experience system developer over to the team.

My question is, have you experienced moving to single backlog for two or more different systems. What were your challenges? What did you need to do to get it to work?

答:
I am assuming that the reason you (or management) wants to create a merged backlog for two teams is that you want to be able to pick only backlog items for one of the system and have both teams work on them.

When this is the case, expect a lot of friction from the team that is forced to work on the system they are not familiar with. Expect that the team will take every straw (i.e. tiny backlog item related to their "home" system) to keep on working on the system they were working on before. Who is to blame them? It is no fun to work on something that you are not good at. And the fact that the other team is good as something you are not good at makes it worse - because it makes you look even more dumb.

So, the only way to make this succeed is to break up the two teams and form them into two mixed teams. Only then, there is a chance that you'll get all developers up to speed quickly on the (currently) "important" system.


答: A lot of trees I've worked with in the wild (window trees in display servers and so on) have just two pointers: first_child and next_peer.  add_child is implemented in terms of if(first_child) first_child->add_peer(child) else first_child = child;.  So in this implementation style there is a function explicitly for adding siblings.

Title: By the definition of a Tree(ADT), is it "wrong" for a node to add a sibling?

Body: The title pretty much says it all. I'm just having a little computer science exercise and am building a Tree. I want a node to be able to add a sibling which requires one to first get a reference to the parent, obviously. I was wondering what is the "correct" way, by definition of what a Tree is, to do such a thing?</p>


问:
Monitoring App: Client side or Server Side?
I have a monitoring web application which has a .Net Backend and a Silverlight frontend. The application crunchs big chunks of data, process them and presentates to user. Then user can interact with the data to see different graphs of log. He/She can unselect dimensions, group some values, choose metrics like transaction count, transaction amount(dollars) etc.

Currently, I combine log data into 3 minute chunks. Then making a lookup from it and sending to clientside. With this raw form of data it's size is optimized for network. On clientside I have a lot of business logic to process this data for presentation. Also when user changes options clientside processes the data according to user's choices.

We have chosen this path to serve this application only from one server. We don't have to scale with the user amount in the company because the whole thing happens on the clientside. This is good but we are sacrificing performance.

I'm really curious about what is going to happen if I choose to do the all computation for user's choices on raw data at the serverside.

-Is it going to be faster?
-Do I need to scale immediately?
-Is Fetching the data only once on the server then caching it something like redis than doing the computations according to user requests better solution?
-If clientside approach is good, do I need to switch to Javascript and Javascript client side MVC frameworks like AngularJS?

And I really don't know how to write the my whole business logic in Javascript at the moment.

Extra Info

Average desktop has 2gb ram and a dual core cpu which is core to duo.

Our servers are in VM cluster. They have scalable ram min 8gb. And 8 core xeon cpus.

100-150 concurrent users can use it.

Every user can do different manipulations on the data. That's why they all have their own data on the clientside.

Thanks

答:
How you are sacrificing performance? By sending data to clients? I think it is a lot easier to feed clients with data then spent time on task switching. You have 100 to 150 users, ehm I would go with saying "paralelize when you must not when you want". On server you would have to check probably for some thread stuff like deadlocks and other, just send data to clients and those having 2 gigs of ram and stuff would be happy.

Other way upgrading clients with hardware would be probably cheaper than using developers time to move logic from client to server, specially if you would get into "weird things" and as you said, you would have to change to JS which you are do not know what to do. Think about time cost also, but probably manages do not care about it, but if you would tell them to upgrade clients hardware they would go creazy.


答:
That is not very good to make it that way.
My prev company, went into single product single team mode because in big company, we had different people working on different stuff.

Switching between projects also costs effort, and if there is new person to start developing overhead is really big. One have to get access rights to developed system, different repository etc.

I prefer specialization, people know what they are doing, have all needed information, know pitfalls of project, and people do not have the feeling that you have to drop them from project to project to get them to work, to suck every penny out of them.

Even if they are idling in their project, they are a lot more productive in what they are familiar with, than jumping from project to project.

Title: Multiple scrum teams moving to single backlog

Body:
We currently have 5 scrum teams that work off their own product backlog for the past year.
Each team works on their own dedicated system but underlying technology is the same .Net.

There has been a lot of discussion on moving to feature based teams working off a single backlog. The reason is one of our main systems has a significant amount of work coming and their is not enough capacity to deliver all the work in the year. The other reason which I believe is the significant one is it gives greater flexibility to adjust to changes in the portfolio rapidly.

A decision been made to change two teams to work on a single backlog but the devs don't have experience on the other systems. One thing we're doing is cross-skilling by moving an experience system developer over to the team.

My question is, have you experienced moving to single backlog for two or more different systems. What were your challenges? What did you need to do to get it to work?


问:
The 10 minutes technical interview
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

答:
Is a string mutable or immutable?

What is the difference between a class and a static class?

What is a pointer?

Describe Complexity.

What is the difference between an Array and a Linked List.

What is the difference between Merge Sort and Quick Sort?

Given a spreadsheet with columns Name, Address, Zip code, and Phone number describe how you would convert the spreadsheet to a normalized database.

Describe the differences between asynchronous and synchronous methods and the ways they need to be handled.

How would you pass information from a server-side application to a web-application?

What is your preferred language? What are some reasons you would use that language over X? (ie. why would you want to use Java over C# and what are some of the fundamental differences?)

ContentLicense: CC BY-SA 2.5

Title: The 10 minutes technical interview


答:
It probably won't be faster to do the analysis on the server and would recommend keeping as is unless there are some other pressures to do otherwise. You would increase the load on your servers if it is doing a lot of computationally-intensive operations.

On the client side you could delay moving to JavaScript until there is a real need (for example tablets) but if it's now only used on Windows desktop applications there wouldn't be any compelling reason to do this quickly.

Title: Monitoring App: Client side or Server Side?

Body:
I have a monitoring web application which has a .Net Backend and a Silverlight frontend. The application crunchs big chunks of data, process them and presentates to user. Then user can interact with the data to see different graphs of log. He/She can unselect dimensions, group some values, choose metrics like transaction count, transaction amount(dollars) etc.

Currently, I combine log data into 3 minute chunks. Then making a lookup from it and sending to clientside. With this raw form of data it's size is optimized for network. On clientside I have a lot of business logic to process this data for presentation. Also when user changes options clientside processes the data according to user's choices.

We have chosen this path to serve this application only from one server. We don't have to scale with the user amount in the company because the whole thing happens on the clientside. This is good but we are sacrificing performance.

I'm really curious about what is going to happen if I choose to do the all computation for user's choices on raw data at the serverside.

-Is it going to be faster?
-Do I need to scale immediately?
-Is Fetching the data only once on the server then caching it something like redis than doing the computations according to user requests better solution?
-If clientside approach is good, do I need to switch to Javascript and Javascript client side MVC frameworks like AngularJS?

And I really don't know how to write the my whole business logic in Javascript at the moment.

Extra Info

Average desktop has 2gb ram and a dual core cpu which is core to duo.

Our servers are in VM cluster. They have scalable ram min 8gb. And 8 core xeon cpus.

100-150 concurrent users can use it.

Every user can do different manipulations on the data. That's why they all have their own data on the clientside.

Thanks


问:
Strategy for keeping secret info such as API keys out of source control?
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/

答:
Keep private information out of your source control. Create a non-loaded default for distribution, and have your VCS ignore the real one. Your installation process (whether manual, configure/build or wizard) should handle creating and populating the new file. Optionally modify permissions on the file to ensure only the required user (webserver?) can read it.

Benefits:

Doesn't assume development entity == production entity

Doesn't assume all collaborators/code reviewers are trusted

Prevent easy mistakes by keeping it out of version control

Easy to automate installs with custom configuration for QA/builds

If you are already doing this and are accidentally checking it in, add it to your project's .gitignore. This'll make it impossible to do  again.

There are plenty of free Git hosts around that provide private repositories. Although you should never version your credentials, you can be cheap and have private repos too. ^_^


答:
About Offloading processing to client side:
Can the client machines handle the business logic processing smoothly? Does other applications (outlook, VS, eclipse, etc) suffer because of the heavy silverlight application?

If the client machines have trouble running the silverlight application, then you need to take some processing to server side, maybe do some conversions from the raw data and send more streamlined data (e.g. JSON/XML) to the clients.

If the silverlight application works fine without impeding your users' work, then it's perfectly OK to offload the business logic to clients since you are saving server side resources.

To answer your questions:

Is it going to be faster?

It will be faster on client side but slower on server side. You might need to upgrade the VMs.

Do I need to scale immediately?

Your server will be processing more data than it used to, so you might have to scale if you see its getting slower.

Is Fetching the data only once on the server then caching it something
  like redis than doing the computations according to user requests
  better solution?

If different user requests fetch the exact same data into the server multiple times, and if fetching is a slow operation, then it is a very good idea to cache it. Based on the amount of data you might use storage systems like Redis.

If clientside approach is good, do I need to switch to Javascript and
  Javascript client side MVC frameworks like AngularJS?

If you have a standardized set of client machines, then Silverlight is good. You might have to think about javascript based clients if you have Linux, Mac, or Windows systems without Silverlight. Plus, Silverlight and other RIA frameworks are much faster than javascript when you are implementing heavy business logic on the client side.


问:
Information protection when registering on web sites
Up until now it seems that when you register on a random web site you do so with blind trust.

You assume that the site isn't harvesting information and passwords. You assume the site is reasonably secure. And you also assume that the information you've submitted isn't used in an undesireable way.

More recently, it's become possible to connect up to a site with a Google+ or Facebook account. But that brings along another problem. Anyone that has access to the social account can access anything that's linked to it.

So, has any thought gone into making something that's truly independant ? Something like an information locker a person could set up themselves. Do any relevant projects exist ?

答:
When we login using Facebook or Google or Twitter, the protocol used is OAuth. OAuth makes it easier to use existing profiles in new ones, but only a limited set of information is shared, in most cases only your email id.

However when the site you are logging into is registered as a Facebook "app" it can request a lot of information from Facebook including rights to post on your behalf. That is bad.

There are many OAuth providers, and if required you can setup your own. If you have your own server, you can use apache amber or other server side software to setup your own authorization service. When you go to a site, it will have an option for specifying your custom OAuth provider (most sites do, if they don't then bad luck). Provide your OAuth url and you will be able to login with your own domain's authorization.


答:
Funny: Save it for the water cooler, except in minimal doses - having a prune face is not a requirement for reviewing code.

Positive: Certainly. Review includes both positive and negative/constructive, by definition.

Positive Feedback helps everyone:

For the one receiving the thumbs up, you reinforce their confidence and inspire them to do more of the same through your positive feedback.

For the rest, as others have mentioned, they will learn what to do, as well as what  not to do. They will also be encouraged to excel, so they too can one day be in the spotlight.

I once worked for a boss who was liberal in his positive feedback - the team was very successful and productive as a result. He moved on, and others took over that lacked his ability to praise a job well done. Productivity and morale took a nosedive, and many of the better team members left the firm.

Title: Is it appropriate to have positive comments in code reviews, or is it exclusively for constructive criticism?

Body:
I have been doing a lot of code review lately, and I am unsure of the positive and negative effects and professionalism of putting positive and/or funny comments in code reviews.

We use Github as our code review platform on my team, so the comments are viewable by anyone.  I generally try to use this platform so the entire process from start to finish is visible and historical.


问:
What are functional languages most used for?
I wondered what functional languages are mainly used for? I've been reading about them and read about Haskell and others. Some seem to be just "academic" languages which makes little sense to me, so hoping to get a better idea of their uses in real world applications.</p>

答:
Functional programming languages are really suitable for Big Data because if you think about it, most of Big Data is about data processing, filtering, aggregating (a.k.a Data Flow).

Functional programming idioms such "Higher Order Functions", functions composition, partial functions, map/reduce, filtering, sequences abstraction (in Clojure) are a natural match to Big Data field.

Functional programming languages make it easy to write "Domain Specific Language".

Functional programming languages greatly simplify coding and architecting multithreaded and parallel systems (Erlang Actors, Elixir, Scala/Akka, Clojure/Pulsar).

Functional programming languages are suitable to code "Natural Language Processing", "Information Retrieval" and "Machine learning" systems. This is also due the "Higher Order Functions".

The ability to create and return functions dynamically at runtime is the main reason why Lisp is used to create AI and machine learning systems.

Dean Wampler gave an interesting talk at the Lambda Jam conference on why Copious Data is the Killer App for Functional Programming.

One field that I don't think functional programming fits in is building GUIs. This is where OOP shines. Just take a look at Cocoa and Cocoa Touch; both are well crafted frameworks.

Personally I like creating web applications with a functional programming languages. My favorite stack right now is Clojure/Pedestal/ClojureScript.


问:
How does a non-technical manager add value to team of self-motivated software developers?
I am seeing a lot of programmers turning away from management and administration roles. They want to build stuff. And as a result, a lot of these positions are filled by non-technical people. I fail to see how they add value. Is scheduling meetings, booking offsites and other administrative work enough to justify their role?</p>

答:
Is scheduling meetings, booking offsites and other administrative work
  enough for their role?

Yes. Perfectly sufficient. They are also good for calling building management when there is a problem with heat, AC, etc; making sure vending machines and water coolers are well stocked and maintained; bringing in special goodies for noshing; keeping the office clean and orderly...

Do your best to think of other such tasks in order to keep them busy and out of trouble...

Their most important role? Staying out of the way and not mixing with programmers, and making sure that other non-technical people do the same.

Consider a development team like an MLB ballclub (the analogy is quite a good one IMO): The managers are always former players - only they know how to handle 'hands on management' of a team of highly skilled, nerdy, idiosyncratic, professionals, who do things that most 'regular people' cannot.


问:
Quantifying the value of refactoring in commercial terms
Here is the classic scenario; Dev team build a prototype. Business mgmt like it and put it into production. Dev team now have to continue to deliver new features whilst at the same time pay the technical debt accrued when the code base was a prototype.

My question is this (forgive me, it's rather open ended); how can the value of the refactoring work be quantified in commercial terms?

As developers we can clearly understand and communicate the value in technical terms, such a the removal of code duplication, the simplification of an object model and so on.  But this means little to an executive focussed on the commercial elements.  What will mean something to this executive is the dev. team being able to deliver requirements at faster velocity.  Just making this statement without any metrics that clearly quantify return on investment (increased velocity in return for resource allocated to refactoring) carries little weight.

I'm interested to hear from anyone who has had experience, positive or negative, in relation to the above.

----------------- EDIT ----------------

Thanks for the responses so far, all of which I think are good.  What I want to develop is a metric that proves (or disproves!) all of these statements. A report that ties velocity to refactoring and shows a positive effect.

答:
I have been in such positions (I suppose we all have.)

Quite often, this a very effective answer:

You have paying me for a year to develop this project. If I get hit by a bus tomorrow, do you want to pay someone for two more years, to figure
  out how to unravel the mess I left behind? Are you not better off paying me for three months, so that the next guy will be up to speed in one month?

Important: Make sure you don't get the boot when they hear you spent a year writing messy code, so you could get them a prototype on time...


问:
Unit test strategy for layered (or derived) method calls
Forgive the title -- it needs work.  I am struggling to find better English to express my issue.  Edits encouraged.

Example to describe my issue:

Checker Method

I have an argument checking method called public static void StringArgs.checkIndexAndCount(String, int, int).  Given a string, an index, and a count, confirm the string is not null, and the index & counts are reasonable.  Unchecked (runtime) exceptions are used to report errors.  There is a battery of unit tests written to check all angles of this method.

Layered (or Derived) Method

The checker method is called by other methods, such as public static String removeByIndexAndCount(String, int, int).  The first line of this method checks the arguments by calling the above checker.

Unit Test Strategy

When I write unit tests for the second/layered/derived method, how do I account for the existing set of unit tests for the checker method?  It seems to violate duplication/copy-paste principles to simple re-add the same unit tests (modified slightly) from the checker method to the second method.

Please advise.

My code is Java, but I don't think that particularly relevant, as this same issue could occur in any language.

答:
There is no need to test all the scenario's for the Checker method when testing X. All you really need to do in testing X is to ensure that it actually does use the Checker method, so you can indeed forego all those test input scenario's to X.

The way to do that is the same way I would ensure that Asserts I have coded that are essential to validating the contract for a method, are still in place: code a single test that should trigger the assert and check that the EAssertionFailed (or whatever) exception is indeed raised.

For your scenario that would mean coding a single test for method X to ensure that it actually calls the 'Checker' method. For example by using test input for which Checker would would raise an exception.

Of course some clever programmer could thwart this check by checking for this input in X and returning the same exception. But you have to draw the line somewhere. You are not protecting against hackers but against someone forgetting to use Checker and/or inadvertent removal of the call to Checker.


问:
Does understanding functional programming help in understanding popular javascript libraries?
I am not experienced in javascript. I try to use some popular javascript libraries such as jQuery, Angular.js and Meteor.js.

I wonder if understanding the logic of functional programming (in javascript of course) will help in understanding and using these libraries better?

答:
Well JavaScript isn't truly a functional programming language. It borrows some functional idioms and the most important part is "Closures".

I would say study "Closures" carefully because it is such a powerful concept that it will help you to write clean and elegant code.

Also, I highly recommend that you read this chapter:  Functional Programming


答:
Code reviews are a tool for improving code quality, in part by uncovering defects.  More importantly, you want to instill good coding practices.

From this perspective, it is important to comment on things done well.  In a training context, improvements should also be commented on.  If your culture is one of continuous improvement, then you should always be commenting on improvements.

Mistakes, bugs, and bad coding will happen.  Point them out in a non-personal manner, and treat them as expected.

From a behavioral modification perspective, reward is much better at producing changes than punishment.  I would consider having good work noticed as a reward.


答:
There is a great article in Mozilla Developer Network (MDN) specifically written for inexperienced Javascripters (sadly many of us think we are experienced, eventhough we aren't): A re-introduction to Javascript

It discusses, in simple terms, some of the most important characteristics and features of Javascript which are often unnoticed (sometimes confusing). (One among them is the concept of Closures)

Title: Does understanding functional programming help in understanding popular javascript libraries?

Body:
I am not experienced in javascript. I try to use some popular javascript libraries such as jQuery, Angular.js and Meteor.js.

I wonder if understanding the logic of functional programming (in javascript of course) will help in understanding and using these libraries better?


问:
Javascript idioms this that vs this self
I've been writing JavaScript for a bit and have now seen code using the idiom

```<code>var that = this;
</code>```

and

```<code>var self = this;
</code>```

Used to gain access to this through closure scope. At this point var self = this seems somewhat more common.

My question is which of these two idioms is truly the convention?
Since they do exactly the same thing, are there advantages/disadvantages to either?

答:
Update 2018: You should use neither and prefer arrow functions that have lexical this scoping.

Original:

They are both idiomatic.

An experienced JavaScript programmer will know exactly what's going on when reading either.

It's just a variable naming thing - there is no empirical reason to choose one over the other - they function exactly the same and they're both common in big code bases of common open source libraries.

There is no reason to use one over the either. The important thing is to pick one and stick with it, and when you're joining a new code base - stick to whichever they were doing.

This related question in StackOverflow notes that self might have a really minor shortcoming where it refers to window in some browsers - so instead of getting a ReferenceError you'd get a silent error. However - this should not be the case anyway if you use a linter.

ContentLicense: CC BY-SA 4.0


问:
When to use event.initMouseEvent for simulating mouse clicks?
I wonder if there are benign use-cases for simulating mouse clicks using event.initMouseEvent. I found that it is used for creating pop-under ads in the following way:

```<code>        var e = document.createEvent('MouseEvents');
        e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
        a.dispatchEvent(e);
</code>```

This code simulates a click on the opening browser window, to force the newly opened window beneath it. Evil.

I'm thinking of simply preventing all simulated clicks in my own browser via a browser extension, but I wonder if I might break useful websites and behavior in the process. Therefore I wonder what situations justify simulating mouse clicks, and if there are big sites that use it in non-evil ways.

答:
Let us ignore the fact that the fact a simulated mouse click causes its default action is only in order to maintain backwards compatibility - so the code you mentioned in your example is indeed evil.

There are plenty of legitimate cases where you'd want to simulate mouse events:

Testing - This is the most important one by far in my opinion. You often want to test that your code reacts correctly. For example, you want to test that when you click a button it becomes inactive (so the user won't be able to click it again to resubmit an AJAX call for example). Simulating user events is an effective technique to test view logic. Mocking user interaction is overall very useful in testing GUI systems.

Working with external code - Sometimes you end up working with a plugin or library that has an inconcise API. Sometimes it does not expose the actual functions but does tell you that clicking element X will do Y. The sad truth is that such plugins are more common than we'd like to admit and simulating events is a way to speak to such plugins.

Scraping - Sometimes you might want to simulate user actions to obtain information for scraping when that information is unavailable otherwise. For example, if you want to extract all the information from a page but that page contains information that requires a click to obtain.

Automation with Userscripts - Sometimes you end up writing a script that 'hooks' on a page and makes working with the page easier for you. In these cases you have no desire to read the actual (often minified and sometimes obfuscated) implementation of the code you're working against, you just want to simulate a user action.

All these sum up to one thing - working against the user interface and not the backing code. When you want to take a step back and treat the user interface of a page for whatever reason (and these for are by far the most common imo) - simulating a mouse click can be very beneficial.


问:
Difference between a server and a client
On a high level, this is my understanding of the difference between a client and server:

a server listens on a host and a port, receives requests (e.g. through a socket connection), and then sends a response to the client who initiated the socket connection.

The client is what sends a request to that server socket, and waits for a response.

The definition is a bit broad and vague. Here is two situations in which both clients subscribe to the above definition, but behave differently:

1) In the first example, the program assumes a socket server is listening on port 2000. This client makes a tcp connection to socket server, waits for response, then prints the response to stdout of the currently running process, and closes connection. It itself does not write anything to the server:

```<code>require 'socket'
host, port = ARGV

s = TCPSocket.open(host, port)
while line = s.gets
  puts "the data is #{line.chop}"
end
s.close
</code>```

The socket server it talks to accepts tcp connections on port 2000. Once a connection is established, it sends data back to client, and then closes the socket thereby terminating connection with the client:

```<code>require 'socket'
server = TCPServer.open(2000)
loop {
  client = server.accept

  client.puts(Time.now.ctime)

  client.close
}
</code>```

Ok so the client program in the above example subscribes to the original definition delineated for client.

But in the next example, the client behaves differently. The clients establishes a tcp connection to a running instance of a redis socket server. The client creates a TCP socket connection to redis-server on port 6379 (the default redis port), plus establishes the new unified request protocol (redis protocol specification) - allowing the connection to communicate using redis-specific format messaging (e.g. multi-bulk replies). Just like the other client, this client sends a request to the server socket for a tcp connection, and waits for a response.

However, unlike the other example, this clients writes data to the server. Redis implement the Publish/Subscribe messaging paradigm. The client publishes to a channel which is stored in the key/value store on main memory that redis supports. So this client behaves significantly different from the other in that it just doesn't simply wait for some kind of response, it writes to the server and causes the server to do things, like push data to subscribed clients.

```<code>require 'rubygems'
require 'redis'
require 'json'

redis = Redis.new

data = {"user" => ARGV[1]}

loop do
  msg = STDIN.gets
  output = redis.publish ARGV[0], data.merge('msg' => msg.strip).to_json
  puts "What output we get #{output}"
end
</code>```

So I am wondering if someone could give me a more comprehensive definition of client and server.

答:
The client and server are basically two parts of a distributed computing model.

In this model, a user uses a client computer which sends requests to the server.
The server then processes the request and creates the appropriate response which it sends back to the client. In this model, it is often the client that initiates the interaction and not the server. The server simply waits for requests to be serviced.

In the two examples that you gave above,

First example, signifies the simple Request-Response operation.

Second Example, implies the Client sends the request, does some transactions/operations and the sends the Response, (Successful or Failure.)

So it does send the response, in the second example.

In Summary:

A Server services the requests from the client.

The client is usually the initiator.

A single server accommodates multiple clients.

The server is responsible for the data processing/operations while the client handles the presentation.

Let me know if it helped.


答:
A server is a computational unit dedicated to providing services to one or more clients or other servers.

A client requests services from one or more servers or other clients.

A server can act as a client requesting services from other servers.

Title: Difference between a server and a client

Body:
On a high level, this is my understanding of the difference between a client and server:

a server listens on a host and a port, receives requests (e.g. through a socket connection), and then sends a response to the client who initiated the socket connection.

The client is what sends a request to that server socket, and waits for a response.

The definition is a bit broad and vague. Here is two situations in which both clients subscribe to the above definition, but behave differently:

1) In the first example, the program assumes a socket server is listening on port 2000. This client makes a tcp connection to socket server, waits for response, then prints the response to stdout of the currently running process, and closes connection. It itself does not write anything to the server:

```<code>require 'socket'
host, port = ARGV

s = TCPSocket.open(host, port)
while line = s.gets
  puts "the data is #{line.chop}"
end
s.close
</code>```

The socket server it talks to accepts tcp connections on port 2000. Once a connection is established, it sends data back to client, and then closes the socket thereby terminating connection with the client:

```<code>require 'socket'
server = TCPServer.open(2000)
loop {
  client = server.accept

  client.puts(Time.now.ctime)

  client.close
}
</code>```

Ok so the client program in the above example subscribes to the original definition delineated for client.

But in the next example, the client behaves differently. The clients establishes a tcp connection to a running instance of a redis socket server. The client creates a TCP socket connection to redis-server on port 6379 (the default redis port), plus establishes the new unified request protocol (redis protocol specification) - allowing the connection to communicate using redis-specific format messaging (e.g. multi-bulk replies). Just like the other client, this client sends a request to the server socket for a tcp connection, and waits for a response.

However, unlike the other example, this clients writes data to the server. Redis implement the Publish/Subscribe messaging paradigm. The client publishes to a channel which is stored in the key/value store on main memory that redis supports. So this client behaves significantly different from the other in that it just doesn't simply wait for some kind of response, it writes to the server and causes the server to do things, like push data to subscribed clients.

```<code>require 'rubygems'
require 'redis'
require 'json'

redis = Redis.new

data = {"user" => ARGV[1]}

loop do
  msg = STDIN.gets
  output = redis.publish ARGV[0], data.merge('msg' => msg.strip).to_json
  puts "What output we get #{output}"
end
</code>```

So I am wondering if someone could give me a more comprehensive definition of client and server.


问:
Should we design programs to randomly kill themselves?
In a nutshell, should we design death into our programs, processes, and threads at a low level, for the good of the overall system?

Failures happen. Processes die. We plan for disaster and occasionally recover from it. But we rarely design and implement unpredictable program death. We hope that our services' uptimes are as long as we care to keep them running.

A macro-example of this concept is Netflix's Chaos Monkey, which randomly terminates AWS instances in some scenarios. They claim that this has helped them discover problems and build more redundant systems.

What I'm talking about is lower level. The idea is for traditionally long-running processes to randomly exit. This should force redundancy into the design and ultimately produce more resilient systems.

Does this concept already have a name? Is it already being used in the industry?

EDIT

Based on the comments and answers, I'm afraid I wasn't clear in my question. For clarity:

yes, I do mean randomly,

yes, I do mean in production, and

no, not just for testing.

To explain, I'd like to draw an analogy to multicellular organisms.

In nature, organisms consist of many cells. The cells fork themselves to create redundancy, and they eventually die. But there should always be enough cells of the right kinds for the organism to function. This highly redundant system also facilitates healing when injured. The cells die so the organism lives.

Incorporating random death into a program would force the greater system to adopt redundancy strategies to remain viable. Would these same strategies help the system remain stable in the face of other kinds of unpredictable failure?

And, if anyone has tried this, what is it called? I'd like to read more about it if it already exists.

答:
There is a literature related this idea, its called Crash-Only software (also Recovery Oriented Computing) and you can start with this usenix paper by Candea & Fox from 2003. Rather than random kills, the author's argue you can improve system reliability by only ever stopping your programs by killing them, so having a single kill switch as a shut down button and a single well exercised start-up path for recovery.

While I'm not sure how well the idea caught on, some of the specific techniques do remain useful. For example not trusting your software to be able to shut itself down when requested and so using specialized supervisory programs (e.g. supervisord etc), and also thinking carefully about what program state is essential and make sure its recorded at appropriate times in a data store designed to enable recovery (so e.g. a sql database).


问:
Is there an explicit word for non-abstract class?
I got mainly abstract classes in my project and there are a few other class which are using/inheriting them. When I'm writing the documentation I would like to specify that a part of it is just about the behavior of these non-abstract classes, but I found using this word silly.

I could just say it's a class, however an abstract class is a class as well. So I was wondering is there an explicit word/synonym for non-abstract class?

SEO update:

What is the general name of non-abstract classes?

答:
They are typically referred to as concrete classes.

...A concrete class is a class that can be instantiated, as opposed to abstract classes, which cannot.


问:
What is OpenCL?
I've been looking around, but I'm still not sure on the what OpenCL is. Other than multi processor stuff...

Is it another graphics API like OpenGL and DirectX? Or something that works alongside OpenGL?

I'm planning on learning OpenGL soon (with java if it makes a difference) so I want to know how/which direction to learn it with.

Also, I hear things about CUDA which confuses me further. Just looking for some simple clarifying statements. Thanks.

答: OpenCL is parallel programming language to program almost all kinds of modern processors CPUs, GPUs, DSPs to name a few. this article provides a good introduction of opencl</p>

Title: What is OpenCL?


问:
Are closures sufficient to characterize functional programming?
All functional programming languages that I know of (e.g. Haskell, Scala, Scheme, Clojure, SML, OCaml, ...) support a notion of closures.

Also, I often read that a language X can be considered functional because it supports closures.

On the other hand there are programming languages that do have closures but are not considered functional. The best example I know of is Smalltalk: Smalltalk has blocks (which in most implementations behave like closures, see e.g. here) but it is considered a pure object-oriented language.

So, while closures are a very common (or even essential) construct in functional programming, are they really sufficient to characterize functional programming? If the support of closures is sufficient for considering a language functional, why isn't Smalltalk considered functional too?

Or is the notion of a closure orthogonal to both functional and
object-oriented programming?

答: Closures are orthogonal to FP.  Really, all they are is a different way of looking at the same basic concepts as objects.  If what's really important to you is the behavior, you use a closure.  If what's really important is the state data, you use an object.  A lot of OO languages these days offer ways to do both, but that doesn't make them "functional languages."</p>


答:
The hallmarks of functional programming languages:

Higher Order Functions. (Passing functions as parameters, storing functions in data structures, returning functions, creating functions at runtime).

Encouraging "Referential transparency".

And I would dare to say "Laziness".

Immutability

A functional programming language makes a heavy use of Functional Data Structures.

Having Closures doesn't mean the language is "Functional". Examples: Java 8 (if Lambdas are going to be added), Groovy and Objective-C,

Edit:

Based on the comment, I removed Memoization from the previous list.

Functional programming languages employs the "Memoization" technique because it is easier with Functional code.

Title: Are closures sufficient to characterize functional programming?

Body:
All functional programming languages that I know of (e.g. Haskell, Scala, Scheme, Clojure, SML, OCaml, ...) support a notion of closures.

Also, I often read that a language X can be considered functional because it supports closures.

On the other hand there are programming languages that do have closures but are not considered functional. The best example I know of is Smalltalk: Smalltalk has blocks (which in most implementations behave like closures, see e.g. here) but it is considered a pure object-oriented language.

So, while closures are a very common (or even essential) construct in functional programming, are they really sufficient to characterize functional programming? If the support of closures is sufficient for considering a language functional, why isn't Smalltalk considered functional too?

Or is the notion of a closure orthogonal to both functional and
object-oriented programming?


问:
Does anyone make money with turnkey software versions of costly software?
For example, Say I make a business software product.  I sell it for $100.  The competitors charge thousands for their version.  Does that kind of model work?  Do company's ever buy software turnkey like that?  No support.  No nothing.  They just spend $100.  Sure there are continuing efforts to improve the product but no guarantees, etc.

I do not want it to be open source.  I do not want to offer support other than very minor things like support forums.  I don't want to make junk.  I can't quit my full time job to travel around the country supporting software.

edit:  They can even see the code, tweak it, etc.  They can't sell it though.  Close to some CC licenses I've seen, but you get the drift I hope.

答:
I'm guessing here, but I think what you are really asking is, can you make money selling software as-is without any support contract or obligation. It's not that you don't want to support your software, fix bugs and release incremental versions.  But what you don't want to be is legally responsible for fixing those bugs and releasing fixes in a very timely manner because your customers demand that.  If what I just said aligns with your question, then absolutely you can sell your software and make money.

To give you an example, just look at most games.  It's a billion dollar industry, but each customer has very little legal power.  You spend $50 on a software package, you install it and run it. It could be awesome or it could be total crap but once you bought it, you bought it, manufacturer will release fixes if/when they feel like it and the buyer can only wait and hope.

"I don't want to make junk" -- I wonder how many developers sit down to write some code and say to themselves, today I'm looking forward to writing junk and nothing but junk?  The point is that significant pieces of software WILL have bugs, that just a nature of things. And all of us wanted to produce nothing but gold.  If you are a small software shop (or just one person), I think it would be absolutely silly not to listen to your customers and provide support.  When you are that small, your customers are essentially your QA and if they are willing to pay you up front AND THEN test your software (because there's only so much testing you can do as one person), why would you not release fixes for them?? That's not to say you have to promise solid turn around times in 2 days or less, but still do your best to keep people that give you money happy or they'll stop giving you money.

It also depends on what kind of software you are producing and your target audience. Do the math. I'm a software engineer and we have 9 developers on the team.  Let's say our engineering costs for salaries, benefits, equipment are around $1M per year.  Would we spend $100 on a critical or even somewhat important piece of software when if something doesn't work, one of our engineers would have to spend 2 days digging through your code?  Those 2 days just cost my team $600, and that's only assuming that other developer's jobs were not hindered by the bug.  Otherwise, start multiplying all of their time lost by 9. On the other hand paying $1000 increases our teams operating expenses by 0.1%.

So if it's anything important or semi-important, my personal inclination would be to stay away from your product.  On the other hand, if you are producing something non-critical and I try your software with 30-day trial license and absolutely love it, of course I'll spend $100 and buy it.

So IMO these are the factors:

Small target audience --> support more important

How critical your product to operations --> support more important

How polished is version 1.0 (i.e. usable right out of the box) --> support less important.  In this point I'm talking even about little things.  If I launch your app, and it works but it's a bit quirky or glitchy, that gives me overall impressions that there are potentially other much larger issues that I haven't stumbled on yet.

And don't get hung up on #3. As I said above, all software has bugs and all software could use polish and improvements. But if you aim for 0 defect release, you'll just spend years coding your software without ever selling it.  Instead, my advice would be to do the opposite:

Find people who are interested in what you have to offer

Release version 0.9 (i.e. Beta) to 2 or 3 of those people with full understanding that it is buggy.

Use their feedback to...

add features they want but you don't have yet

remove features they don't care about and you don't want to support

fix bugs and bring up the quality

By artificially keeping your initial customer base  small, you won't get swamped with support calls/requests and you will be able to work and communicate with them to get your product to a shipping quality. By releasing beta, you could give some of your customers a working copy in 10%-30% of the time than what it would take you to finish every single feature and fix every single bug.


答: Closures are certainly a major part of functional programming. However, there are many languages nowadays that support closures, and at least some level of functional programming, without being "functional languages". Examples include Perl, Python, JavaScript, C#, Java 8, Ruby, and others. Conversely, closures are apparently not completely necessary to functional languages, in that the first functional languages predated the invention of the closure. Early versions of Lisp used dynamic scope for all variables, so the notion of "closure" could not be expressed: a variable was bound in the scope when a function was called, not when the function was declared. That said, I believe that all modern functional languages do offer closures; I certainly can't imagine programming in a functional language without them!


问:
How to initialize all your references?
I have recently taken a project with another developer, and he has a certain way of initializing his references.

```<code>class Player
{
    private:
        Console &console;
        Armor &armor1, &armor2;
        Debugger &debugger;
        sf::RenderWindow &window;
        sf::Event &event;

   public:
       Player(Console &console, Armor &armor1, ...) : console(console), armor1(armor1), ... {};
}
</code>```

And it's perfectly fine with me, but what if we add new stuff? Our constructor is massive, and so messy, I would like to know if there are better ways of initializing your references if you have a large project, because if we keep up with this, eventually our constructor will have more lines of code than what it actually does.

答:
C++ 11 allows initialization in the class declaration itself.

However, if you need to initialize from outside sources, that won't help.

You can also initialize on an 'as needed' basis - don't have to do it all at once in the constructor, but in the call that actually uses the reference - each reference at its appropriate time.

This depends on your design of course, but is often a good way to avoid those ugly massive constructors.

Title: How to initialize all your references?


问:
How to deal with someone who dislikes the idea of code reviews?
Obviously, if management buy into spending time with code reviews, then everyone has to do it.

But there are always those guys (or gals) who resist with every ounce of their being.

How do you effectively manage dealing with this scenario when dealing with it as the peer reviewer?

答:
Frankly, this question doesn't make any sense if you have a well managed shop:

1) If it's part of the job, you must do it, or you're insubordinate. Someone who adamantly refuses to do part of the job they are required to do should get canned. Programming is a craft and a profession - reviewers and managers are there to help get the job done, not deal with spoiled kids (of any age.).

2) If you have a well managed source control system, (which is a must in any professional software shop), then their code can be reviewed whether they like it or not. So review their code:

If it's good, notify them and give them a pat on the back - that will
encourage participation.

If it's no good, also let them know. This should have the effect of
motivating them to participate, in order to defend themselves. If it
doesn't, you can use punitive measures: Financial penalties,
demotions in status, etc. If in spite of your efforts this employee
fails to come around, IMO you have a bad employee and they should be
shown the door.


答:
I've been in the software business for about 40 years.  Every time I considered the idea of packaging a product I realized the value proposition was continuing support.  If customers couldn't get help they couldn't use it at all.  Therefore, everything I've ever done has been with the understanding that support comes first, development is what you do to provide support.  Over time I've met with other people that took that path, I've heard the same story - they would spend many hours a week on the phone fixing PC issues - often the customers were perfectly happy to pay for the help.

This would have meant creating an organization to provide a set of services - I tried that at one point and found I was babysitting employees, not writing code.

Rather than writing a cheapie to 'replace' expensive products, write 'plugins' that extend them.  Some of these, in particular one shot migrations, might get you the money you're expecting without long term obligations.

Title: Does anyone make money with turnkey software versions of costly software?

Body:
For example, Say I make a business software product.  I sell it for $100.  The competitors charge thousands for their version.  Does that kind of model work?  Do company's ever buy software turnkey like that?  No support.  No nothing.  They just spend $100.  Sure there are continuing efforts to improve the product but no guarantees, etc.

I do not want it to be open source.  I do not want to offer support other than very minor things like support forums.  I don't want to make junk.  I can't quit my full time job to travel around the country supporting software.

edit:  They can even see the code, tweak it, etc.  They can't sell it though.  Close to some CC licenses I've seen, but you get the drift I hope.


答:
Depends on what market you are targeting. If you're going for small businesses and marketing a vertical application targeted to their specific needs, you might have some success, provided you do take suggestions from customers and implement improvements.

Still, some support is mandatory, and that's often the show stopper. Also keep in mind that you have to market and sell your product, even if it only costs $100.

Regardless, big businesses will ignore you. No large, serious business is interested in a product without a strong support warranty, a staff with redundancy, etc. There is a reason why they pay the big bucks for software - if they could avoid it, they would. So if you're thinking that your $100 turnkey solution can compete with big time players in the corporate world, my suggestion is to scrap your idea.

However, as @GrandmasterB has pointed out, if you leverage the power of online distribution, support and marketing, then perhaps you can be successful with the right niche product, targeting botique industries and small businesses or software shops, if you are interested in developing software tools. Tools and addon's, plugin's etc - things that make developers lives easier - might be the best idea for such an endeavor. I would have no problem paying $100 for a quality tool that made my coding day easier to get through. See his comments on this answer.


问:
Multiple scrum teams moving to single backlog
We currently have 5 scrum teams that work off their own product backlog for the past year.
Each team works on their own dedicated system but underlying technology is the same .Net.

There has been a lot of discussion on moving to feature based teams working off a single backlog. The reason is one of our main systems has a significant amount of work coming and their is not enough capacity to deliver all the work in the year. The other reason which I believe is the significant one is it gives greater flexibility to adjust to changes in the portfolio rapidly.

A decision been made to change two teams to work on a single backlog but the devs don't have experience on the other systems. One thing we're doing is cross-skilling by moving an experience system developer over to the team.

My question is, have you experienced moving to single backlog for two or more different systems. What were your challenges? What did you need to do to get it to work?

答:
The correct Scrum answer is "Ask the team(s)".  This is the principle of self-organisation where they should be able to restructure themselves to get the job done quickly.  You see many people in the teams have more context knowledge than an outsider and they know what is best.  This also includes the Product Owner.

I take it that you came here and asked the question as there is something that does not feel right and you have hidden concerns. So I am going to give you a few pointers to discuss with the team to come up with the right decision.

Product Owner

There is only one product owner for a backlog and this should be a business person or person representing business.  It should not be IT management.  A big backlog has many items and with multiple teams it could be too much for a single PO to deal with.  You may want to keep backlogs separate for this reason.

If there are multiple PO's, then you definitely need multiple backlogs as teams should be dedicated in a sprint to a single PO and backlog.  The reason is a team does not need to manage conflicts between product owners priorities.

Product Development versus Maintenance

Maintenance teams work on many small enhancements, bugs over several different products and possibly with several product owners.  These BAU teams need the support of IT management to help schedule the and manage the conflicts between multiple product owners.

Project teams should focus on one product at a time to minimize context switching and delivering one great product at a time.  Context switching could result in delivery of many mediocre products with some degree of technical debt.

Context Switching

Working on multiple products or different features causes context switching which slows down teams productivity.  The PO should factor this in when working out what is next and what team should be working on what piece of work.  The amount of switching is not insignificant and not just a theoretical issue,  it is real and I have witnessed team dropping up to 80% in productivity due to this.

A good PO will try group features and type of work to help teams do less context switching, thus improving their performance.

Risk

Sadly, management try put the risk of time, money, budget and business pressures on the team;  and teams accept this by agreeing to this.  As a development professional, you should simply state the facts and impacts of the decisions and make the business own their own risk.

Examples

Agreeing to a ridiculous time.  Rather say what effort its going to take to do the job properly and make business manage the time problem

Estimations.  Business expect teams to accurately estimate in a world of complexity and uncertainty.  Teams should ask business what they are doing to mitigate if the estimates are exceeded due to unforeseen challenges, which are highly likely.  Teams should not factor in fat, but instead business should.

Technical Debt.  Teams should estimate on doing high quality code that is fully tested and estimate on that, i.e. Stop writing defects due to pressures.  If business want lower quality, then it is their risk to take and when things go wrong its their problem.

Professionalism

Be a professional by stating building the right things to the agreed quality.  Estimate to your best ability based on facts at hand.  When these facts change, communicate it and adjust the estimate.   As a development team, build great products and do not take on business risk.  Communicate and manage expectations.

Inspect and Adapt

Teams should always be seeking ways to improve and if they feel it is going to make things better, they should try it.  Then inspect to see whether there are improvements.  Finally they should adapt and improve on their new approach or scrap it if not working.  The intent behind seeking to improve should always be there.

Bottom Line

Ultimately, the management of the backlog is the choice of the PO.  How he/she wants to manage the queue of work is up to them.  The only think is they MUST keep the pipeline of work to ALL teams healthy and in a good state.  It is thus up to the PO to decide.

The contract

In sprint planning sessions, the team should expect a list of groomed product backlog items that are clear, unambiguous and ordered.  With a short discussion with the PO the team should know exactly what the PO wants;  the WHAT.  The team then focus on how they are going to build.

If the PO comes to the planning meeting well prepared, who cares how the backlog is managed.  If the PO comes unprepared to the sprint planning meeting, this should be addressed by the SM and made very visible as this is totally unacceptable and not a team problem to take on.


问:
When to use HTTP status code 404 in an API
I am working on a project and after arguing with people at work for about more than a hour. I decided to know what people on stack-exchange might say.

We're writing an API for a system, there is a query that should return a tree of Organization or a tree of Goals.

The tree of Organization is the organization in which the user is present, In other words, this tree should always exists. In the organization, a tree of goal should be always present. (that's where the argument started). In case where the tree doesn't exist, my co-worker decided that it would be right to answer response with status code 200. And then started asking me to fix my code because the application was falling apart when there is no tree.

I'll try to spare flames and fury.

I suggested to raise a 404 error when there is no tree. It would at least let me know that something is wrong. When using 200, I have to add special check to my response in the success callback to handle errors. I'm expecting to receive an object, but I may actually receive an empty response because nothing is found. It sounds totally fair to mark the response as a 404. And then war started and I got the message that I didn't understand HTTP status code schema. So I'm here and asking what's wrong with 404 in this case? I even got the argument "It found nothing, so it's right to return 200". I believe that it's wrong since the tree should be always present. If we found nothing and we are expecting something, it should be a 404.

More info,

I forgot to add the urls that are fetched.

Organizations

```<code>/OrgTree/Get
</code>```

Goals

```<code>/GoalTree/GetByDate?versionDate=...
/GoalTree/GetById?versionId=...
</code>```

My mistake, both parameters are required. If any versionDate that can be parsed to a date is provided, it will return the closes revision. If you enter something in the past, it will return the first revision. If by Id with a id that doesn't exists, I suspect it's going to return an empty response with 200.

Extra

Also, I believe the best answer to the problem is to create default objects when organizations are created, having no tree shouldn't be a valid case and should be seen as an undefined behavior. There is no way an account can be used without both trees. For that reasons, they should be always present.

also I got linked this (one similar but I can't find it)

http://viswaug.files.wordpress.com/2008/11/http-headers-status1.png

答:
If the URL represents a resource that never existed return 404 Not Found

If the URL represents a resource that is an empty list return an empty list and 200 OK.

Example:

```<code>{
  total: 0,
  items: []
}
</code>```

If the URL represents a resource that used to exist return 410 Gone.

Regarding Lego Stormtrooper's dialog:

```<code>Alien: Computer, please tell me all planets that humans inhabit. GET /planets?inhabitedBy=humans

Computer: 200 OK. { total: 1, items:[{name:'Earth'}] }

Alien: Computer, please tell me about Earth. GET /planets/earth

Computer: 200 OK. {name:'Earth', status: 'Mostly Harmless'}

Alien: Computer, please tell me about all planets humans inhabit, outside the asteroid belt. GET /planets?inhabitedBy=humans&distanceFromSun=lots

Computer: 200 OK. {total:0, items:[] }

Alien: Computer, please destroy Earth. DELETE /planets/earth

Computer: 204 No Content. (or 202 Accepted if it takes some time to destroy Earth)

Alien: Computer, please tell me about Earth. GET /planets/earth

Computer: 410 Gone

Alien: Computer, please tell me all planets that humans inhabit. GET /planets?inhabitedBy=humans

Computer: 200 OK 0 {total: 0, items:[] }

Alien: Victory for the mighty Irken Empire!
</code>```

Body:
If the URL represents a resource that never existed return 404 Not Found

If the URL represents a resource that is an empty list return an empty list and 200 OK.

Example:

{
  total: 0,
  items: []
}

If the URL represents a resource that used to exist return 410 Gone.

Regarding Lego Stormtrooper's dialog:

Alien: Computer, please tell me all planets that humans inhabit. GET /planets?inhabitedBy=humans

Computer: 200 OK. { total: 1, items:[{name:'Earth'}] }

Alien: Computer, please tell me about Earth. GET /planets/earth

Computer: 200 OK. {name:'Earth', status: 'Mostly Harmless'}

Alien: Computer, please tell me about all planets humans inhabit, outside the asteroid belt. GET /planets?inhabitedBy=humans&distanceFromSun=lots

Computer: 200 OK. {total:0, items:[] }

Alien: Computer, please destroy Earth. DELETE /planets/earth

Computer: 204 No Content. (or 202 Accepted if it takes some time to destroy Earth)

Alien: Computer, please tell me about Earth. GET /planets/earth

Computer: 410 Gone

Alien: Computer, please tell me all planets that humans inhabit. GET /planets?inhabitedBy=humans

Computer: 200 OK 0 {total: 0, items:[] }

Alien: Victory for the mighty Irken Empire!


问:
Object Oriented Design
Suppose you have the following:

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+------+     +----+-+
       ^                 ^
       |                 |
       |                 |
  +------+              +-------+
  | Deer |              | Grass |
  +------+              +-------+
</code>```

Deer inherits from Animal, and Grass inherits from Food.

So far so good. Animal objects can eat Food objects.

Now lets mix it up a bit. Lets add a Lion which inherits from Animal.

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+-----++     +----+-+
       ^     ^           ^
       |     |           |
       |     |           |
  +------+ +------+     +-------+
  | Deer | | Lion |     | Grass |
  +------+ +------+     +-------+
</code>```

Now we have have a problem because Lion can eat both Deer and Grass, but Deer is not  Food it is Animal.

With out using multiple inheritance, and using object oriented design, how do you solve this problem?

FYI: I used http://www.asciiflow.com to create the ASCII diagrams.

答:
Inheritance should be used for something that is always something else, and cannot change. Grass is not always food. For example, I do not eat grass.

Grass plays the role of a foodstuff for certain animals.

Title: Object Oriented Design


问:
Best books on Managing a Software Development Team?
The canonical books on software development is fairly well established. However, after reading through a dreadful book full of bad advice on managing programming teams this weekend I am looking for recommendations for really good books that focus on the management side of programming (recruiting, performance measurement/management, motivation, best practices, organizational structure,  etc.) and not as much on the construction of software itself.

Any suggestions?

答:
Peopleware: Productive Projects and Teams .

If you read one book make it this one.  It covers how to set about making your developers productive and backs up why these things are important with hard numbers.

The chances are that you won't get all of them implemented (too many companies have ingrained cultures which will prevent them) but it's worth knowing what the ideal is and why, and having the ammunition to get what you can.


问:
Why is mod (%) a fundamental mathematical operator in many programming languages?
Is there a reason, historical or otherwise, why the modulus operator is part of a small set of standard operators in what seems like many languages? (+, -, *, / and %, for Java and C, with ** in Ruby and Python).

It seems strange to include mod as a "fundamental" (not to knock it, I use it plenty, but I also use exponentiation, absolute value, floor/ceiling or others -- they seem just as useful and necessary). Was this an old decision made in some specification which Java, C, Ruby and Python all follow or a language they are all descended from? As far as I can tell most Lisp dialects only include +, -, / and *.

At first I wondered if mod was particularly easy to implement at the binary level (would that even make a difference, regarding decisions about what should be a "fundamental" operator and what shouldn't?) but it seems not to be. Is it just much more commonly used in programming than I think?

答:
I am sure it is common because many CPU architectures implement modulus as a second output of the integer divide instruction.

I don't recall it being present in 1970s CPUs (6800, 8080, Z80, 1604, etc.), but by the 1980s, the Intel 8086 and 8088, as well as the Motorola 6809 had it.

The PDP-11 instruction architecture specified DIV producing a quotient and a remainder from the beginning (1970), though the MUL and DIV instructions were not present on early designs, but could be transparently emulated by an "instruction not implemented trap" and implemented with a handler that did bit twiddling.  Probably the PDP-11 feature encouraged the very first edition of the C language providing the % feature.  (Ever notice how a percent sign has a slash in it?  That makes it a cleverish choice for a division related operator.)

The presence of modulus in C alone can probably explain its presence in all modern languages.  C has a very large family of descendants and was otherwise quite influential.

OwnerDisplayName: Eli Rose

OwnerDisplayName: wallyk


答:
Many programming languages have a "remainder" operator which may be used as a modulus operator when both operands are positive; said operator is often called the "modulus" operator, because that is its primary use.  Languages generally have such an operator because many hardware platforms' division hardware automatically supply a remainder when performing a division, and computing a remainder or modulus via any other means would be much more difficult.

I don't know the history of hardware support for signed division; many processors have for years provided hardware that can automatically perform signed division subject to the rule that if a/b yields (q,r), then -a/b or a/-b will yield (-q,-r), but I'm not sure of the use cases where division using that rule is particularly helpful.  In almost every case where I've used integer division or "modulus" operations on negative values, I've wanted round-toward-negative-infinity on the division and a true modulus operation (such that (a+b)/b would always equal (a/b)+1 and (a+b)%b would always equal a%b.).  Because the operators don't work that way, it's necessary to test the sign of the dividend and use different code when it's negative--essentially negating any benefit from having a signed divide instruction in the first place.  I'm curious for what purposes the signed-division support in hardware is actually useful.

Returning to the original question, the modulus operator is often useful in situations where certain things are supposed to happen on a periodic basis, either in space (e.g. graphical coordinates) or in time.  For example, if one wants to have an event happen every 15 seconds, the time until the next event will be 15-((time_now - time_of_an_occurrence) % 15), assuming time_of_an_occurrence is not greater than time_now.  If time_of_an_occurrence were greater than time_now, a modulus operator could continue to use the same formula provided the subtraction didn't overflow, but the remainder operator will require a different formula.

Title: Why is mod (%) a fundamental mathematical operator in many programming languages?

Body:
Is there a reason, historical or otherwise, why the modulus operator is part of a small set of standard operators in what seems like many languages? (+, -, *, / and %, for Java and C, with ** in Ruby and Python).

It seems strange to include mod as a "fundamental" (not to knock it, I use it plenty, but I also use exponentiation, absolute value, floor/ceiling or others -- they seem just as useful and necessary). Was this an old decision made in some specification which Java, C, Ruby and Python all follow or a language they are all descended from? As far as I can tell most Lisp dialects only include +, -, / and *.

At first I wondered if mod was particularly easy to implement at the binary level (would that even make a difference, regarding decisions about what should be a "fundamental" operator and what shouldn't?) but it seems not to be. Is it just much more commonly used in programming than I think?

OwnerDisplayName: supercat


答:
Modulus is closely related to group and ring theory, which are very fundamental mathematical theories.

Exponentiation is just the third operation in the sequence addition, multiplication, exponentiation, tetration (and that's an infinite sequence). It does become important mainly with complex numbers, which are rarer in computer arithmetic. One particular exponentiation is supported explicitly, though: 2n is commonly written as 1<<n, since computers are quite binary.

Floor and ceil are really rare in comparison: They only apply when converting from  ℝ to ℤ. (floating point to integer). Similarly, abs is associated with a mapping from ℤ to ℕ

OwnerDisplayName: MSalters


答:
Sorry, but at the risk of turning this into a game of "Call My Bluff" I think the real answer to this question is quite simple:

Mod allows precise computations in "non-decimal" quantities and units such as dates, time, yards, inches, ounces etc.
In decimal calculations, it also provides a method for the programmer to work to a numeric precision beyond that provided by the hardware of the machine. This has a huge number of applications from the very small (e.g quantum calculations) to the very large (e.g. discovering new prime numbers).

It is important to understand that we called these things computers for a reason. Sometimes we need them to give us the correct answer!

OwnerDisplayName: Sheldon


答:
For recruitment Smart and Gets Things Done by some bloke called Joel Spolsky has the virtue of being very very short with some good insights.  Some of what it talks about isn't going to be easy to get implemented in every company / country but there are often alternatives which will get you some of the benefits.

While we're touting Joel's stuff the first book of Joel on Software essays is also good though they're all available online.  Short, readable and thought provoking.

(Proceeds to die of hypocrisy after all the times he's moaned about people banging on about how wonderful Joel and / or Jeff are.)

Title: Best books on Managing a Software Development Team?

Body:
The canonical books on software development is fairly well established. However, after reading through a dreadful book full of bad advice on managing programming teams this weekend I am looking for recommendations for really good books that focus on the management side of programming (recruiting, performance measurement/management, motivation, best practices, organizational structure,  etc.) and not as much on the construction of software itself.

Any suggestions?


答: Truly randomly, no. But it's probably a good idea for long-running processes/threads to exit/restart at a given interval, or after having been idle for a given (but dependent on certain criteria) duration, or after executing a particular kind of task. Long-running processes build up state inevitably including stale things, can presumably hang on to memory preventing swap space to be released, all of which gets (or ought to get) cleaned up when they exit, improving general system stability.</p>

Title: Should we design programs to randomly kill themselves?

Body:
In a nutshell, should we design death into our programs, processes, and threads at a low level, for the good of the overall system?

Failures happen. Processes die. We plan for disaster and occasionally recover from it. But we rarely design and implement unpredictable program death. We hope that our services' uptimes are as long as we care to keep them running.

A macro-example of this concept is Netflix's Chaos Monkey, which randomly terminates AWS instances in some scenarios. They claim that this has helped them discover problems and build more redundant systems.

What I'm talking about is lower level. The idea is for traditionally long-running processes to randomly exit. This should force redundancy into the design and ultimately produce more resilient systems.

Does this concept already have a name? Is it already being used in the industry?

EDIT

Based on the comments and answers, I'm afraid I wasn't clear in my question. For clarity:

yes, I do mean randomly,

yes, I do mean in production, and

no, not just for testing.

To explain, I'd like to draw an analogy to multicellular organisms.

In nature, organisms consist of many cells. The cells fork themselves to create redundancy, and they eventually die. But there should always be enough cells of the right kinds for the organism to function. This highly redundant system also facilitates healing when injured. The cells die so the organism lives.

Incorporating random death into a program would force the greater system to adopt redundancy strategies to remain viable. Would these same strategies help the system remain stable in the face of other kinds of unpredictable failure?

And, if anyone has tried this, what is it called? I'd like to read more about it if it already exists.