问:
How do you keep your unit tests working when refactoring?
In another question, it was revealed that one of the pains with TDD is keeping the testing suite in sync with the codebase during and after refactoring.

Now, I'm a big fan of refactoring. I'm not going to give it up to do TDD. But I've also experienced the problems of tests written in such a way that minor refactoring leads to lots of test failures.

How do you avoid breaking tests when refactoring?

Do you write the tests 'better'? If so, what should you look for?

Do you avoid certain types of refactoring?

Are there test-refactoring tools?

Edit: I wrote a new question that asked what I meant to ask (but kept this one as an interesting variant).

答:
Your tests are too tightly coupled to the implementation and not the requirement.

consider writing your tests with comments like this:

```<code>//given something
...test code...
//and something else
...test code...
//when something happens
...test code...
//then the state should be...
...test code...
</code>```

this way you can't refactor the meaning out of tests.

Body:
Your tests are too tightly coupled to the implementation and not the requirement.

consider writing your tests with comments like this:

//given something
...test code...
//and something else
...test code...
//when something happens
...test code...
//then the state should be...
...test code...

this way you can't refactor the meaning out of tests.


问:
Another way of expressing 'Dirty' coding
I'm writing a brief for a new starter at the company.

I've pointed out the aims of what I want to achieve and now I'm writing some suggested (but not concrete) solutions.

For each of the aims, I'd like to suggest a fast, dirty method, and a slower, but more robust solution. I don't mean 'dirty' as in uncommented and untabbed code, but simply as in faster, hackishy code.

I'm happy that the new starter takes whichever pathway they feel are necessary, and I feel my use of the word 'dirty' is going to put them off that particular solution. They're probably going to try to impress the management, and I don't want the 'dirty' solution to be a turn-off if that's what they're most comfortable with.

Can you help me decide on a slightly better terminology than dirty?

I aim to contrast between the hacky/fast solution (which is still valid) and a more robust, scalable solution. For a project as trivial as the one we're producing, then either method will be accepted.

答:
I believe you mean Technical Debt.

To explain, the "dirty" solution is solution that creates lots of this debt. The other solution is the one that doesn't. Explaining what technical debt is is much better than comparing "bad" and "good" solution.

Basically, finding a name for the "dirty" solution might not be a problem. Because even this "dirty" solution might have it's merits. Even worse, there might be more than two solutions, some "dirtier" than others. It is much better to compare those solutions based on how much effort they take and how much technical debt they incur. And if person understands technical debt, it becomes easier to differentiate between the probably multiple solutions.

ContentLicense: CC BY-SA 3.0


答:
I don't mean 'dirty' as in uncommented and untabbed code, but simply
  as in faster, hackishy code.

How about duct tape programming?

http://www.joelonsoftware.com/items/2009/09/23.html

Based on your description, I believe it conveys well the believed advantages of your approach.

On the other hand, if it's about prototyping (as @mouviciel suggested in a comment), then there's still the concept of a proof-of-concept.

Title: Another way of expressing 'Dirty' coding

Body:
I'm writing a brief for a new starter at the company.

I've pointed out the aims of what I want to achieve and now I'm writing some suggested (but not concrete) solutions.

For each of the aims, I'd like to suggest a fast, dirty method, and a slower, but more robust solution. I don't mean 'dirty' as in uncommented and untabbed code, but simply as in faster, hackishy code.

I'm happy that the new starter takes whichever pathway they feel are necessary, and I feel my use of the word 'dirty' is going to put them off that particular solution. They're probably going to try to impress the management, and I don't want the 'dirty' solution to be a turn-off if that's what they're most comfortable with.

Can you help me decide on a slightly better terminology than dirty?

I aim to contrast between the hacky/fast solution (which is still valid) and a more robust, scalable solution. For a project as trivial as the one we're producing, then either method will be accepted.


问:
Low level programming - what's in it for me?
For years I have considered digging into what I consider "low level" languages. For me this means C and assembly. However I had no time for this yet, nor has it EVER been neccessary.

Now because I don't see any neccessity arising, I feel like I should either just schedule some point in time when I will study the subject or drop the plan forever.

My Position

For the past 4 years I have focused on "web technologies", which may change, and I am an application developer, which is unlikely to change.

In application development, I think usability is the most important thing. You write applications to be "consumed" by users. The more usable those applications are, the more value you have produced.

In order to achieve good usability, I believe the following things are viable

Good design: Well-thought-out features accessible through a well-thought-out user interface.

Correctness: The best design isn't worth anything, if not implemented correctly.

Flexibility: An application A should constantly evolve, so that its users need not switch to a different application B, that has new features, that A could implement. Applications addressing the same problem should not differ in features but in philosophy.

Performance: Performance contributes to a good user experience. An application is ideally always responsive and performs its tasks reasonably fast (based on their frequency). The value of performance optimization beyond the point where it is noticeable by the user is questionable.

I think low level programming is not going to help me with that, except for performance. But writing a whole app in a low level language for the sake of performance is premature optimization to me.

My Question

What could low level programming teach me, what other languages wouldn't teach me? Am I missing something, or is it just a skill, that is of very little use for application development? Please understand, that I am not questioning the value of C and assembly. It's just that in my everyday life, I am quite happy that all the intricacies of that world are abstracted away and managed for me (mostly by layers written in C/C++ and assembly themselves). I just don't see any concepts, that could be new to me, only details I would have to stuff my head with. So what's in it for me?

My Conclusion

Thanks to everyone for their answers. I must say, nobody really surprised me, but at least now I am quite sure I will drop this area of interest until any need for it arises.

To my understanding, writing assembly these days for processors as they are in use in today's CPUs is not only unneccesarily complicated, but risks to result in poorer runtime performance than a C counterpart. Optimizing by hand is nearly impossible due to OOE, while you do not get all kinds of optimizations a compiler can do automatically. Also, the code is either portable, because it uses a small subset of available commands, or it is optimized, but then it probably works on one architecture only.

Writing C is not nearly as neccessary anymore, as it was in the past. If I were to write an application in C, I would just as much use tested and established libraries and frameworks, that would spare me implementing string copy routines, sorting algorithms and other kind of stuff serving as exercise at university. My own code would execute faster at the cost of type safety. I am neither keen on reeinventing the wheel in the course of normal app development, nor trying to debug by looking at core dumps :D

I am currently experimenting with languages and interpreters, so if there is anything I would like to publish, I suppose I'd port a working concept to C, although C++ might just as well do the trick.

Again, thanks to everyone for your answers and your insight.

答: I would say there is not much reason in your domain, however if you was to do high performance computing (eg Gaming, Science, etc) thing it would be justified.</p>

ContentLicense: CC BY-SA 2.5


问:
Question on Graph
I am trying to implement  a graph data structure in C#. I have the following interfaces:

```<code>public interface IVertex<TValue>
{
    TValue  Value { get;}
    VertexList<IVertex<TValue>> Neighbours { get;}
    int InDegree { get;}
    int OutDegree { get;}
}

public interface IWeightedEdge<TValue, TWeight>
{
    IVertex<TValue> source { get;}
    IVertex<TValue> destination { get;}
    TWeight weight { get; }
}
public interface IWeightedGraph<TVertexValue, TEdgeWeight>
{
    bool AddVertex(TVertexValue value);
    TVertexValue RemoveVertex(IVertex<TVertexValue> vertex);
    bool RemoveVertex(TVertexValue value);
    bool AddEdge(IVertex<TVertexValue> source, IVertex<TVertexValue> dest, TEdgeWeight weight);
    bool RemoveEdge(IVertex<TVertexValue> source, IVertex<TVertexValue> dest);
}
</code>```

From this, you can see that it is the responsibility of the Vertex class (the class implementing IVertex interface) to tell about its adjacent vertices (Neighbors function), its in degree, out degree etc. While I was designing this, I was told by a friend of mine that the Graph class (the one that will implement IGraph) should take the responsibility of operations like retrieving adjacent vertices ,finding the in/out degrees etc. His point is that the above operations are valid only when a vertex becomes part of a Graph. But my point is that a Vertex is standalone; it can exist even outside of a graph. So, the vertex should provide the operations on it.

Which one you think is correct? Please share your thoughts on this.

答:
I would say your friend has a point, albeit it can be elaborated in a bit more detail regarding its advantages:

Firstly, mathematically speaking, a vertex cannot exist without a graph, simply because a vertex itself is already forming a graph.

Secondly, and much more importantly, vertices can be shared by different graphs. Consider operations like creating sub-graphs, embedded graphs, vertex cover graphs, etc etc.. - the common notion here is that you create a graph, that contains some vertices from your original graph, but different edge sets. For example, if you create a subgraph that has only some nodes, you lose the edges that are adjacent to other nodes, which are not part of that subgraph's vertex set.

Now if you look at the implementation side of things you do not want to create a copy of these vertices due to the size of some of these graphs. But if you want to reuse the original vertex objects, you will have a hard time to provide different edge sets for different context graphs.

When the graph class itself is responsible for keeping track of which edges are part of the graph, you can reuse all edge and vertex objects in the above operations.

Title: Question on Graph


问:
What's the best way to retrieve a value and a status
Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?

For example, something like one of these declarations:

```<code>bool getMethod(double& ret);

double getMethod(bool& ok);

void getMethod(bool& ok, double& ret);

pair<bool, double> getMethod();

bool checkMethod(); // eg if (checkMethod())
double getMethod(); //        result = getMethod();
</code>```

or something else, like return a struct

The value may exist about 50% of the time.

The existing code already does a lot of the last method, i.e. using a checkMethod() but I was wondering if that's really an efficient way to do it - via two calls (half the time).

答:
Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?

Starting from C++17, you can use std::optional. (until then, you can use boost::optional).

The class behaves like a pointer, but allocates no dynamic memory and expresses explicitly the fact that the value can be missing:

The following code snippets perform the same function:

```<code>bool getMethod(double& ret); // from your code
// client code:
double result = 0.;
if(getMethod(result)) {
    // result has a valid value
}
</code>```

and:

```<code>#include <optional>
std::optional<double> getMethod();
if(auto result = getMethod()) {
    // *result is a valid value
}
</code>```

Body:
Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?

Starting from C++17, you can use std::optional. (until then, you can use boost::optional).

The class behaves like a pointer, but allocates no dynamic memory and expresses explicitly the fact that the value can be missing:

The following code snippets perform the same function:

bool getMethod(double& ret); // from your code
// client code:
double result = 0.;
if(getMethod(result)) {
    // result has a valid value
}

and:

#include <optional>
std::optional<double> getMethod();
if(auto result = getMethod()) {
    // *result is a valid value
}

ContentLicense: CC BY-SA 4.0


问:
Does “notification center” pattern encourage good or bad program design?
Sometimes I come across these message-hub-style APIs, for example the Cocoa NSNotificationCenter: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

Usually these APIs provide a global access point on which you subscribe to or broadcast messages/events. I'm thinking this is a problem because it encourages a flat and unstructured program architecture, where dependencies are not explicit in the API, but hidden in the source code. You are not forced to think about object ownership and hierarchies, but can rather make any object in your program result in any code anywhere being called. But maybe this is a good thing?

Does this pattern generally encourage good or bad program design, and why so? Does it make the code harder or easier to test?

Forgive me if this question is too vague or broad. I'm trying to wrap my head around the potential consequences of extensive use of an API like this, and the different ways you could use it.

Edit: I guess my biggest issue with this pattern is that the API "lies" about dependencies and object couplings, and can be illustrated with this example:

```<code>myObj = new Foo();
myOtherObj = new Bar();
print myOtherObj.someValue; // prints 0
myObj.doSomething();
print myOtherObj.someValue; // prints 1, unexpectedly, because I never indicated that these objects had anything to do with each other
</code>```

答:
Asynchronous messaging is a good architectural principal for large systems that must scale

The Java equivalent of this is JMS and generally considered to be a good thing.

This is because it promotes decoupling of your client code from the code that actually services the message. Client code merely has to know where to post their message. Service code merely has to know where to pick up messages. Client and service know nothing of each other and therefore can change independently of each other as required.

You can easily externalise the URI of the message hub to make it configurable and not embedded in the source code.


答:
I cannot recall ever seeing either of

```<code>double getMethod(bool& ok);
void getMethod(bool& ok, double& ret);
</code>```

and they just look ugly to me.

The first one

```<code>bool getMethod(double& ret);
</code>```

seems the most obvious and self-explanatory, but I've seen

```<code>std::pair<bool, double> getMethod();
</code>```

done too, but it doesn't add anything to the first version.

Title: What's the best way to retrieve a value and a status

Body:
Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?

For example, something like one of these declarations:

```<code>bool getMethod(double& ret);

double getMethod(bool& ok);

void getMethod(bool& ok, double& ret);

pair<bool, double> getMethod();

bool checkMethod(); // eg if (checkMethod())
double getMethod(); //        result = getMethod();
</code>```

or something else, like return a struct

The value may exist about 50% of the time.

The existing code already does a lot of the last method, i.e. using a checkMethod() but I was wondering if that's really an efficient way to do it - via two calls (half the time).

Body:
I cannot recall ever seeing either of

double getMethod(bool& ok);
void getMethod(bool& ok, double& ret);

and they just look ugly to me.

The first one

bool getMethod(double& ret);

seems the most obvious and self-explanatory, but I've seen

std::pair<bool, double> getMethod();

done too, but it doesn't add anything to the first version.


问:
Is printing to console/stdout a good debugging strategy?
Let's say we have a function like this:

```<code>public void myStart()
{
    for (int i = 0; i<10; i++) myFunction(i);
}

private int myFunction(int a)
{

    a = foo(a);
    a = bar(a);
    return a;
}

private int foo(int a)
{
    //do something here

    //something gnarly here

    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}
</code>```

Now for whatever reason, our code isn't working. Perhaps it's throwing an error, perhaps it's returning the wrong value, perhaps it's got stuck in an infinite loop.

The first thing any first year programmer, is print to console/std out, (having learned how to print Hello World before learning to use a debugger).

For example to debug this code they might do the following:

```<code>private int myFunction(int a)
{
    print("before foo: a=" + a);
    a = foo(a);
    print("before bar: a=" + a);
    a = bar(a);

    return a;
}

private int foo(int a)
{
    //do something here
    print ("foo step1: a=" + a);

    //something gnarly here
    print ("foo step2: a=" + a + " someOtherValue="+ someOtherValue + " array.length= " + someArray.length());
    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}
</code>```

Now they run the code, they get a big console print out, which they can go through to trace where things are going wrong.

An alternative of course, is to set breakpoints and step through the code at each point.

One major advantage of printing to console, is that the developer can see the flow of the values in one go, without having to click through steps etc.

But the disadvantage is, your code is then riddled with all these print statements that then need to be removed.

(Is it possible perhaps to tell the debugger to print only certain values out to a log?, the breakpoints can then easily be added or removed without actually modifying the code.)

I do still use console printing as a primary debugging method, I'm wondering how common/effective this is in comparison to something else out there.

答:
Loging/printing and debuggers are complementary techniques that have different strenghts and weaknesses - it's best to use both. But overall, I'd say that debuggers are the superior tool in most cases and should be used first, with logging/printing only used for the things it's actually better at.

Advantages of debuggers:

You can inspect the entire program state, not just the values you thought to print out in advance. This can massively speed up the debugging process by reducing the feedback cycle to less than a second. Especially important when it takes some time to reach the bug.

You can see where calls came from and even inspect values up the stack trace.

You can (to some degree that depends on the language/platfrom) debug code that you cannot easily modify because you only have the compiled binary or byte code.

Advantages of Logging/printing:

It doesn't require a special debug build or configuration. It always works.

Can be used to analyze errors that are hard to reproduce and occur rarely

Can be used to analyze timing-dependant errors where the pause caused by a debugger can easily make the bug disappear.

Gives you permanent information that you can analyze at your leisure. You can jump back and forth between output at different points in the program flow.


问:
Is it a good idea to collect anonymous usage statistics in a free program?
I'm the main author of a multiplatform free software/open source GUI program. Although the program gets thousands of direct downloads per month, I have no idea of the number of people regularly using it. It is also included in some Unix distributions and download sites making the counting harder. It would be interesting for me to know

How many people use it? Should I bother continuing development?

Which features of the program (dialogs, import filters, etc) do people most use? This would focus development.

I'm considering some form of anonymous feedback (with the user opting-in), where the program sends monthly reports of the time since installation (whole months), the number of times each dialog is used, number of files opened, the version number and platform. The user would be asked the first time this is sent and there would be an option to disable it. I think I would only do this after the first week of usage, to exclude one-off users.

Is doing this a good and ethical idea? I'm in the EU, so it's possible that data protection laws may apply.

答:
No.

Always let the user know what you're collecting, and why.
If at all possible (in this case it's possible) require the user to opt in.

If it is found out that you are collecting this information without user knowledge, you will come across as shady at the very least. The damage that this causes usually outweights the benefits of the data, and many users will opt in if you make the case that opting in is like voting to improve those features they use the most.


答:
IIRC data protection laws do not apply to anonymous data - it only applies to personal data held against the person.

I wouldn't do what you suggest simply because someone will notice and your reputation will get tarnished. They will assume you need it to sell to Google for marketing purposes.

So first thing you need to do is tell the users what you're doing, and let them opt-out. If they opt-in, send whatever usage data you like. The trick is to be totally transparent about what you're doing.

Title: Is it a good idea to collect anonymous usage statistics in a free program?

Body:
I'm the main author of a multiplatform free software/open source GUI program. Although the program gets thousands of direct downloads per month, I have no idea of the number of people regularly using it. It is also included in some Unix distributions and download sites making the counting harder. It would be interesting for me to know

How many people use it? Should I bother continuing development?

Which features of the program (dialogs, import filters, etc) do people most use? This would focus development.

I'm considering some form of anonymous feedback (with the user opting-in), where the program sends monthly reports of the time since installation (whole months), the number of times each dialog is used, number of files opened, the version number and platform. The user would be asked the first time this is sent and there would be an option to disable it. I think I would only do this after the first week of usage, to exclude one-off users.

Is doing this a good and ethical idea? I'm in the EU, so it's possible that data protection laws may apply.


答:
I think it's not only ethical, but also mandatory for developing quality applications.

You should ask the user before, of course, and letting them to switch off the data collection.


问:
is there any way to copy the "Work Item Type" diagram in TFS?
I used the Process Editor (from TFS Power Tools) to update the Workflow diagram of a particular Work Item Type (viz., the "Issue" type). There are a dozen other projects on our server that share the Issue type, and I would like to port my changes to all of them. But unfortunately, while the Process Editor allows you to export/import Work Item Types to/from the server, it only includes the.xml (definition) file, which doesn't include the workflow diagram. (The diagram is stored in the.wit and the.wit.diagram files, which do not get imported with the.xml).
Is there any way to copy the diagram to all the projects?

(Note: I eventually intend to make similar changes to several of the work item types, so an automated solution to propagate these changes across all the projects would be much appreciated!)

Running TFS 2010.

答:
The TFS Team Project Manager has a tool to sync work item definitions between team projects.

You can also use witadmin to export a Process Template from one Team Project and import into another without using the UI.


答:
Sending Usage Data

I have no negative opinion on sending anonymous data of a software's usage. As long as that this is a op-in only feature. With that said, I only enable such features for products from reputable sources. An unknown vendor would not get my usage data.

Instead of monitoring your users. Offer them alternative features that gives you the same data but in different forms.

Automatic Updates

Adding automatic updates allows you to monitor how often the software pulls for new downloads. This gives you an idea of how many activate installations there are of your software. Furthermore, users who op-in for updates checking are committed users. They want to stay on the edge of receiving new features.

Error Reporting

Add error reporting features to the software. When there is a problem users can submit a report of what happen. Include options for attaching usage logs, and other debug information to fix the error. This helps ensure a quality problem, and gives you an idea of how many users care that a problem is resolved.

Feature Requests

Add a way for users to easily request features from the software. This gives you better feedback at the time the user has the idea, and ensures better engagement with the user.


答:
This is a typical Oberserver Pattern implementation (or sometimes called a Listener pattern or sometimes called Subscriber/Publisher pattern).  In applications where this is behavior useful it's a good pattern to implement.  No pattern should be implemented if it adds no value to the solution.

From your question, it sounds as if you are concerned that everything knows about the NotificationCenter and that global things are BAD.  Sometimes, yes, global things are bad.  But let's look at the alternative.  Let's say you have 2 components, for this example it doesn't really matter what they do or what they are.  Component1 has some data that was acted upon or changed in some way.  Component2 would like to know about any changes to data of the type that Compoent1 manages.  Should Component2 know about the existence of Component1?  Or would it be better for Component2 subscribe/listen for a message that tells it that some component somewhere in the app changed some data that it is interested in?  Now take this example and multiply it by dozens or more components and you can see where the value of the pattern lies.

Is it a perfect solution for every situation, no.  Does it abstract communication in between components and provide a more loose coupling, yes.

Title: Does “notification center” pattern encourage good or bad program design?

Body:
Sometimes I come across these message-hub-style APIs, for example the Cocoa NSNotificationCenter: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

Usually these APIs provide a global access point on which you subscribe to or broadcast messages/events. I'm thinking this is a problem because it encourages a flat and unstructured program architecture, where dependencies are not explicit in the API, but hidden in the source code. You are not forced to think about object ownership and hierarchies, but can rather make any object in your program result in any code anywhere being called. But maybe this is a good thing?

Does this pattern generally encourage good or bad program design, and why so? Does it make the code harder or easier to test?

Forgive me if this question is too vague or broad. I'm trying to wrap my head around the potential consequences of extensive use of an API like this, and the different ways you could use it.

Edit: I guess my biggest issue with this pattern is that the API "lies" about dependencies and object couplings, and can be illustrated with this example:

```<code>myObj = new Foo();
myOtherObj = new Bar();
print myOtherObj.someValue; // prints 0
myObj.doSomething();
print myOtherObj.someValue; // prints 1, unexpectedly, because I never indicated that these objects had anything to do with each other
</code>```


问:
How should I test the functionality of a function that uses other functions in it?
Suppose there is a function get-data which returns a map of information about the id of the user passed in. Now this function uses 3 functions source-a, source-b and source-c to get three different kinds of maps. Now we combine all these maps into one map and return from get-data.

When I test get-data, should I test for existence of data for keys? Does it makes sense for this function to fail unit tests if one of source-a, source-b and source-c fail? If thats function job is to combine data, and it's doing it, it should be enough, right?

答:
In unit testing you must only test the functionality of one class, if your source-a, source-b and source-c methods call other classes, you should mock them (they should be unit tested in their own classes).

In integration testing, you test the behavior of several classes interacting between them, that means that your get-data function must test that the data that is retrieving is correct (source-a, source-b and source-c are correct, and the data is being joining properly).

Unit testing are easier and more focused, and should be created by developers.
Integration tests usually get obsolete relatively fast (if any internal component has been modified), so they are harder to mantain. Should be created by a QA profile.


问:
Async network programming using Reactive Extensions
After doing some (more-or-less) "low-level" async socket programming years ago (in an  Event-based Asynchronous Pattern (EAP) fashion) and recently moving "up" to a TcpListener (Asynchronous Programming Model (APM)) and then trying to move to async/await (Task-based Asynchronous Pattern (TAP)) I've pretty much had it with keep having to bother with all this 'low level plumbing'. So I was figuring; why not give RX a go (Reactive Extensions) since it might fit more snugly to my problem domain.

A lot of code I write has to to with many clients connecting over Tcp to my application which then start a two-way (async) communication. The client or server may at any point decide a message needs to be sent and do so, so this is not your classic request/response setup but more of a real-time, two-way, "line" open to both parties to send whatever they want, whenever they want. (If anyone has a decent name to describe this I'd be glad to hear it!).

The "protocol" differs per application (and isn't really relevant to my question). I do, however have an initial question:

Given that only one "server" is running, but it has to keep track of many (usually thousands) of connections (e.g. clients) each having (for lack of a better description) their own "state machine" to keep track of their internal states etc, which approach would you prefer? EAP/TAP/APM? Would RX even be considered an option? If not, why?

So, I need to work Async since a) it's not a request/response protocol so I cannot have a thread/client in a "waiting for message"-blocking call or "sending message"-blocking call (however, if the send is blocking for that client only I could live with it) and b) I need to handle many concurrent connections. I see no way of doing this (reliably) using blocking calls.

Most of my applications are VoiP related; be it SIP messages from SIP cients or PBX (related) messaging from applications like FreeSwitch / OpenSIPS etc. but you can, in it's simplest form, try to imagine a "chat"server trying to handle many "chat"clients. Most protocols are text based (ASCII).

So, after having implemented many different permutations of aforementioned techniques I would like to simplify my work by creating an object that I can simply instantiate, tell it on which IPEndpoint to listen and have it tell me whenever something of interest is going on (which I usually use events for, so some EAP is usually mixed with the other two techniques). The class should not bother trying to 'understand' the protocol; it should merely handle incoming/outgoing strings. And thus, having my eye on RX hoping that would (in the end) simplify the work, I created a new "fiddle" from scratch:

```<code>using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Reactive.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        var f = new FiddleServer(new IPEndPoint(IPAddress.Any, 8084));
        f.Start();
        Console.ReadKey();
        f.Stop();
        Console.ReadKey();
    }
}

public class FiddleServer
{
    private TcpListener _listener;
    private ConcurrentDictionary<ulong, FiddleClient> _clients;
    private ulong _currentid = 0;

    public IPEndPoint LocalEP { get; private set; }

    public FiddleServer(IPEndPoint localEP)
    {
        this.LocalEP = localEP;
        _clients = new ConcurrentDictionary<ulong, FiddleClient>();
    }

    public void Start()
    {
        _listener = new TcpListener(this.LocalEP);
        _listener.Start();
        Observable.While(() => true, Observable.FromAsync(_listener.AcceptTcpClientAsync)).Subscribe(
            //OnNext
            tcpclient =>
            {
                //Create new FSClient with unique ID
                var fsclient = new FiddleClient(_currentid++, tcpclient);
                //Keep track of clients
                _clients.TryAdd(fsclient.ClientId, fsclient);
                //Initialize connection
                fsclient.Send("connect\n\n");

                Console.WriteLine("Client {0} accepted", fsclient.ClientId);
            },
            //OnError
            ex =>
            {

            },
            //OnComplete
            () =>
            {
                Console.WriteLine("Client connection initialized");
                //Accept new connections
                _listener.AcceptTcpClientAsync();
            }
        );
        Console.WriteLine("Started");
    }

    public void Stop()
    {
        _listener.Stop();
        Console.WriteLine("Stopped");
    }

    public void Send(ulong clientid, string rawmessage)
    {
        FiddleClient fsclient;
        if (_clients.TryGetValue(clientid, out fsclient))
        {
            fsclient.Send(rawmessage);
        }
    }
}

public class FiddleClient
{
    private TcpClient _tcpclient;

    public ulong ClientId { get; private set; }

    public FiddleClient(ulong id, TcpClient tcpclient)
    {
        this.ClientId = id;
        _tcpclient = tcpclient;
    }

    public void Send(string rawmessage)
    {
        Console.WriteLine("Sending {0}", rawmessage);
        var data = Encoding.ASCII.GetBytes(rawmessage);
        _tcpclient.GetStream().WriteAsync(data, 0, data.Length);    //Write vs WriteAsync?
    }
}
</code>```

I am aware that, in this "fiddle", there is a little implementation specific detail; in this case I'm working with FreeSwitch ESL so the "connect\n\n" in the fiddle should, when refactoring to a more generic approach, be removed.

I am also aware that I need to refactor the anonymous methods to private instance methods on the Server class; I'm just not sure what convention (e.g. "OnSomething" for example) to use for their method-names?

This is my basis/starting-point/foundation (which needs some "tweaking"). I have some questions about this:

See above question "1"

Am I on the right track? Or are my "design" decisions unjust?

Concurrency-wise: would this cope with thousands of clients (parsing/handling the actual messages aside)

On exceptions: I'm not sure how to get exceptions raised within clients "up" to the server ("RX-wise"); what would be a good way?

I can now get any connected client from my server class (using it's ClientId), assuming I expose the clients in one way or another, and call methods on them directly. I can also call methods via the Server class (for example, the Send(clientId, rawmessage) method (whereas the latter approach would be a "convenience" method for quickly getting a message to the other side).

I am not quite sure where (and how) to go from here:

a) I need to handle incoming messages; how would I set this up? I can get the stream ofcourse, but where would I handle retrieving the received bytes? I think I need some kind of "ObservableStream"-something I can subscribe to? Would I put this in the FiddleClient or FiddleServer?

b) Assuming I want to avoid using event until these FiddleClient/FiddleServer classes are implemented more specifically to tailor their application specific protocol handling etc. using more specific FooClient/FooServer classes: how would I go from getting the data in the underlying 'Fiddle'-classes to their more specific counterparts?

Articles/links I already read / skimmed / used for reference:

Consume a Socket using Reactive Extension

Creating and Subscribing to Simple Observable Sequences

How to add or associate context to each ObservableTcpListener Connection/Session

Asynchronous Programming with the Reactive Framework and the Task Parallel Library — Part 1, 2 and 3.

Using Reactive Extensions (Rx) for socket programming practical?

A .NET Rx Driven Web Server and .NET Rx Driven Web Server, Take 2

Some Rx tutorials

答:
...I would like to simplify my work by creating an object that I can simply instantiate, tell it on which IPEndpoint to listen and have it tell me whenever something of interest is going on...

After reading that statement I immediately thought "actors". Actors are very similar to objects except they only have a single input where you pass it the message (instead of directly calling the object's methods) and they operate asynchronously. In a very simplified example... you would create the actor and send it a message with the IPEndpoint and the address of the actor to send the result to. It goes off and does it work in the background. You only hear back from it when "something of interest" happens. You can instantiate as many actors as you need to handle the load.

I am not familiar with any actors libraries in .Net although I know there are some. I am familiar with the TPL Dataflow library (there will be a section covering it in my book http://DataflowBook.com) and it should be easy to implement a simple actor model with that library.

OwnerDisplayName: RobIII


答:
Suppose there is a function get-data which returns a map of information about the id of the user passed in.

Great. You should test that then. For a given ID, do you get the right data back?

now this function uses 3 functions source-a, source-b and source-c to get three different kinds of maps.

Which is an implementation detail you should ignore in the test. All you're testing is that your unit of work (this method) does what it's supposed to (take an ID and return XYZ data for that ID). How the method does that isn't particularly relevant - after all, a key benefit of that unit test is that you can refactor the implementation of the method and the test will verify you did that correctly.

That said, you're likely going to need to mock the data sources, so at some point the test will likely need to know how the code works to do that. You'll need to balance three competing goals here: making the test isolated (by mocking the data), making the test focused on requirements, and pragmatism.

In the end, it's the code that matters. Tests exist to support the actual code, spending a lot of time and trouble mucking about with polishing tests isn't nearly as useful as making tests.

Title: How should I test the functionality of a function that uses other functions in it?

Body:
Suppose there is a function get-data which returns a map of information about the id of the user passed in. Now this function uses 3 functions source-a, source-b and source-c to get three different kinds of maps. Now we combine all these maps into one map and return from get-data.

When I test get-data, should I test for existence of data for keys? Does it makes sense for this function to fail unit tests if one of source-a, source-b and source-c fail? If thats function job is to combine data, and it's doing it, it should be enough, right?


答:
If you have demonstrated the hackish code is indeed faster, just document that it was chosen for performance reasons.  I would document this as a comment in the code.  To do this you need to develop and test both solutions

If a quick and dirty solution was created for immediate cost reasons, present it as such.  Do note that it introduces technical debt that may have to be repaid later.  It has been my experience that in some cases the quick and dirty solution often cost more to test and get production ready than a properly coded solution.   This is a case where early interest payments on the technical debt exceed the cost of the technical debt.

In other cases, the quick and dirty solutions end up including more code that a properly coded solution.  They can be harder to understand and patch when necessary (part of the technical debt).

Be clear of the costs (including time to delivery, and reliability) of both solutions.

If there are problems with the quick and dirty solution, send them back to the starter with an appropriate timetable for solution.  This may help them understand the cost of each approach.  Good mentoring and code reviews may be appropriate as well.


答:
I wouldn't go as far as saying it encourages bad programming. But it can easily be misused.

Well what is the actual idea?

The source of the notification only makes its notification. It doesn't make an assumption about the existence of potential observers or anything. An observer registers for notifications it is designed to handle. The observer doesn't make any assumptions about how many potential sources there are for the notifications it may handle.

This is a way to achieve dependency injection, without ever having sources know observers or observers know sources. However for the whole system to work, you need to wire up the right observers for the right notifications, and this system is even vulnerable to typos, because it cannot be compile time checked.

The biggest danger of course is, that someone will use this to make tons of objects globally available for 1-1 calls.


问:
Advice for solo programmer whose team will expand in the near future
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.

答:
There are going to be heated technical discussions: new programmers have a bias, they have experienced a few ways to do things and when confronted with a new way that they don't understand, they'll first think it makes no sense and needs changing. Programmers who have worked on their own for years are likely to be defensive about their work, and also their work will be somewhat idiosyncratic, because of the number of problems they've solved without discussing things with other people.

Be aware of those biases, welcome the fresh input, don't be too defensive and don't make rash decisions to change everything either.

There are many good sides to working in a team, especially getting your code reviewed by a colleague. Insist on that for all team members including yourself from the start.


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

答:
Never, I think you will never finish testing in a system.. there are sooo many variables you can't manage.

But, as we know, you can not test "for ever", so i think the limit depends basically on:

When the risk associated with the software's use has been reduced to an acceptable level. (as @Graham Lee says)

Who is the system user? it can be you or the president of united states. In the first case you don't care a lot if a bug appears because you solve it and its done. In the second case you don't want ANY bug to appear.

What's your relationship with your client? Maybe the client its your dad, so it is not so terrible, or maybe it is a big company.

How serious is for the system users a bug? Will it cause the third world war or just an ugly message?

Title: How To Know When To Stop Testing?


问:
Logic inside class properties setters & getters
Trying to build a case against this as we have a developer that likes to use class properties in place of methods. I think it's a bad idea. In some cases he is accessing the data layer inside the setter and getter.

here is a snippet of code, what are your thoughts on this?

```<code>private Dictionary<string, List<string>> _activeFilters;
    public Dictionary<string, List<string>> ActiveFilters
    {
        get
        {
            if (_activeFilters == null)
            {
                _activeFilters = new Dictionary<string, List<string>>();
                var qs = HttpContext.Current.Request.QueryString;
                foreach (var widget in SrpDto.Widgets)
                {
                    _activeFilters[widget.SearchParameter] = qs[widget.SearchParameter] != null ? qs[widget.SearchParameter].Split(',').Skip(1).ToList() : new List<string>();
                }
            }

            return _activeFilters;
        }
    }

    private Constants.SearchBarLayout? _searchBarLayout;
    public Constants.SearchBarLayout SearchBarLayout
    {
        get
        {
            if (_searchBarLayout == null)
            {
                var searchBarLayoutType = typeof(Constants.SearchBarLayout);

                // Use the first enum value as the default if no module setting is present
                _searchBarLayout = (Constants.SearchBarLayout)Enum.Parse(searchBarLayoutType,
                    this.ModuleContext.Settings[Constants.SRPSearchBarLayoutKey] as string ?? Enum.GetName(searchBarLayoutType, 0));
            }

            return _searchBarLayout.Value;
        }
    }

    public string SearchBarTemplate
    {
        get
        {
            switch (this.SearchBarLayout)
            {
                case Constants.SearchBarLayout.SimpleSearchBar:
                    return Constants.SRPSimpleSearchTemplateName;
                    break;
                case Constants.SearchBarLayout.FacetedSearchBar:
                    return Constants.SRPFacetSearchTemplateName;
                    break;
                default:
                    return string.Empty;
            }
        }
    }
</code>```

答:
I'm going to say that in some cases, this is exactly what you want.  Having logic in the property get/set is not unheard of, and in fact, the Microsoft guidelines for properties show calling a method to make a control active when a value changes.

I can think of many scenarios where you'd want to retrieve the values from the database when calling get, and in the cases above, the properties are read-only because they do not have a set method defined, so you wouldn't inadvertently update something in your code and break the principle of least surprise.

On the flip side, if every action that calls to the database or has some logic in it to determine a value must be a method, what would you call the method?  GetActiveFilters()?  That sounds like it should be a property.

By all means you can set a different coding standard for your own team if this is not what you prefer, but given that Microsoft itself adopts and demonstrates ways to bundle logic into property getters and setters, I'd say go easy on the guy, and tell him that your preference is you don't do it this way.

OwnerDisplayName: JBeckton

OwnerDisplayName: Maurice Reeves


答:
If there was no logic inside getters and setters, then what would properties be? SearchBarLayout is a simple conditional, and I think it's fine. The others could be more debatable, but this is a common pattern:

```<code>private T _value;
public T Value {
    get {
        if (_value == null) {
            _value = [initialization logic for the field]
        }
        return _value;
     }
}
</code>```

This means that if someone instantiates this class but never accesses Value, time was saved by skipping the initialization logic. And if it is accessed more than once then it's still only processed once (except in cases where the initialization could return null). It also keeps the code more sequentially organized than it would be if the fields / properties were listed and XML-documented in one section and initialized in other methods.

You have to decide whether those benefits actually apply. Maybe they are doing separate calls to the data layer that could be more efficient as one call so you should initialize both fields at once? I don't know the details, but personally I wouldn't have a problem writing code like you posted.

Title: Logic inside class properties setters & getters

Body:
Trying to build a case against this as we have a developer that likes to use class properties in place of methods. I think it's a bad idea. In some cases he is accessing the data layer inside the setter and getter.

here is a snippet of code, what are your thoughts on this?

```<code>private Dictionary<string, List<string>> _activeFilters;
    public Dictionary<string, List<string>> ActiveFilters
    {
        get
        {
            if (_activeFilters == null)
            {
                _activeFilters = new Dictionary<string, List<string>>();
                var qs = HttpContext.Current.Request.QueryString;
                foreach (var widget in SrpDto.Widgets)
                {
                    _activeFilters[widget.SearchParameter] = qs[widget.SearchParameter] != null ? qs[widget.SearchParameter].Split(',').Skip(1).ToList() : new List<string>();
                }
            }

            return _activeFilters;
        }
    }

    private Constants.SearchBarLayout? _searchBarLayout;
    public Constants.SearchBarLayout SearchBarLayout
    {
        get
        {
            if (_searchBarLayout == null)
            {
                var searchBarLayoutType = typeof(Constants.SearchBarLayout);

                // Use the first enum value as the default if no module setting is present
                _searchBarLayout = (Constants.SearchBarLayout)Enum.Parse(searchBarLayoutType,
                    this.ModuleContext.Settings[Constants.SRPSearchBarLayoutKey] as string ?? Enum.GetName(searchBarLayoutType, 0));
            }

            return _searchBarLayout.Value;
        }
    }

    public string SearchBarTemplate
    {
        get
        {
            switch (this.SearchBarLayout)
            {
                case Constants.SearchBarLayout.SimpleSearchBar:
                    return Constants.SRPSimpleSearchTemplateName;
                    break;
                case Constants.SearchBarLayout.FacetedSearchBar:
                    return Constants.SRPFacetSearchTemplateName;
                    break;
                default:
                    return string.Empty;
            }
        }
    }
</code>```

Body:
If there was no logic inside getters and setters, then what would properties be? SearchBarLayout is a simple conditional, and I think it's fine. The others could be more debatable, but this is a common pattern:

private T _value;
public T Value {
    get {
        if (_value == null) {
            _value = [initialization logic for the field]
        }
        return _value;
     }
}

This means that if someone instantiates this class but never accesses Value, time was saved by skipping the initialization logic. And if it is accessed more than once then it's still only processed once (except in cases where the initialization could return null). It also keeps the code more sequentially organized than it would be if the fields / properties were listed and XML-documented in one section and initialized in other methods.

You have to decide whether those benefits actually apply. Maybe they are doing separate calls to the data layer that could be more efficient as one call so you should initialize both fields at once? I don't know the details, but personally I wouldn't have a problem writing code like you posted.

OwnerDisplayName: nmclean


答:
I'd want to have a wider view on the class model if I were actually doing a full code review, but these all look like very obvious cases where one should definitely use a property rather than a method.

Let's consider ActiveFilters first. If I see a read-only property on an object called ActiveFilters, then I expect that "Gets the active filters for the object" to be what I'd see if I looked in the documentation; principle of least surprise therefore says that if that's what this property does, then all is good, otherwise it may not be.

And it is.

It happens to be a memoised property; that is to say, it calculates the value to return on first call and caches the result for subsequent calls. This is an optimisation for the case where a property is likely to be called more than once (otherwise it saves nothing). It's most useful in cases where the property might sometimes not be accessed (because in such cases the code never runs) though even when the property's getter is called every time, it's still nice to keep the logic for obtaining the value near to the place where it is accessed; aiding ones ability to understand the code.

Of course, outside calling code doesn't know whether it is memoised, a read from a field with no further logic, or if it calculates the result on each call.

Nor does calling code know if that memoisation is permanent, or if there is a method or setter elsewhere in the class that might either re-fill _activeFilters, or set it to null to force recalculation.

This is one of the main reasons for using properties rather than just exposing fields—if they'd exposed a field (and ensured it was correctly filled on construction) it would be a breaking change to later change to something like this.

It looks reasonably robust (I'd want to examine the details of SrpDto.Widgets etc. and know about why there is one item being skipped before I'd say anything more firmly than "reasonably").

All in all a textbook case of a memoised property getter.

If I were to critique it at all, it would be that perhaps rather than return a Dictionary containing Lists that could then be changed, it might be better to return a readonly IDictionary or ReadOnlyCollection or copies of the lists. Another alternative design would be to make it an indexed getter that returns read-only versions of the list based on a string key. However:

This might be a reasonable saving for the developer writing it, developers using it, and the processing computer, especially if it's an internal class.

It might be absolutely the perfect thing to do; I can't know it's not without seeing more.

The implementation would still be much like the above anyway, but with some extra work added to handle the creation of a readonly dictionary or handling of indexing.

(I'd also want to see the name Widgets justified; if it relates to a functional UI element, then it's perhaps okay, but I sometimes see it used with no further justification than "oh, I just wanted to use a silly piece of 1930s slang to make this less readable").

SearchBarLayout is another textbook memoised property getter. I'm not so sure about the naming convention that gives us Constants.SearchBarLayout (that had really better be an internal class or enum) but as far as being a property getter goes; of course it should, what else would it be?

SearchBarTemplate is even more obviously something that should be a property; it maps a set of values of one type to a set of values of another. Perhaps that logic should be elsewhere, but perhaps not (again, I can't tell from just here; the main thing is whether that logic is being duplicated all over the place). Still, that's not relevant to the question here; in terms of getter vs. method, this one's an obvious getter.

There's a bit of a bad smell in the use of a switch performing an arbitrary-looking mapping, as that is often something that can be done better another way. However;

Sometimes it is just the best way to do it.

If it can be improved, it can be improved as a non-breaking change, in this spot.

In all, while there is a degree of judgement in the question of whether something should be a property or a method, there are some general principles:

If we think of classes and struct as nouns, objects as instances of those nouns, and methods as verbs (and static classes as abstract nouns), then properties should be things we can reasonably think of as adjectives or prepositions (describing a relationship between the object we called on and the object we got or set).

Getters should generally not throw due to the caller doing an incorrect choice (throwing due to e.g. a database connection going down is another matter). If they do they should do so in a way that is obvious from knowledge of the class/struct and can test for (e.g. the way default(int?).Value throws InvalidOperationException) or because the property is indexed and the error relates to the key.

Getter should not change state as seen from the outside, only report on what the state is. (Memoisation changes internal state, but as seen from the outside it's no different than calculating the result each time, or having already calculated it).

A setter must throw on invalid values being set. This is their primary reason for existing (rather than just exposing fields), though another strong reason is that they can update more than one piece of state at a time.

Ideally getters and setters should be pretty fast (like all those shown above) especially if amortised over several calls (again, like the first two of those above). There's no semantic reason for this, but having what looks like it should be a property actually be a method can be a subtle warning that something is expensive (e.g. DateTime.UtcNow is calls whatever methods the underlying OS has for obtaining the current time such as 'GetSystemTimefollowed bySystemTimeToFileTime` on Windows, so there's no reason that wouldn't be an obvious thing to make a property, but a method for contacting several atomic clocks around the world and then deducing network delays to give a good estimate of the current time, might be better off being a method).

Another way of looking at the question, is to consider properties to be "smart fields", again like all the examples you give.

I don't see how anyone would object to these getters. I would be suspicious that anyone who did might be tending to use methods when they should really use properties.

OwnerDisplayName: Jon Hanna


问:
Why doesn't Haskell have a 'format' function for string interpolation?
I'm trying to use Shake and I stumbled upon the following problem: there's no easy and convenient way to interpolate a string. I know about Text.Printf — it's not what I'm looking for. The interpolation syntax I'm talking about is like this:

(Make)

```<code>HEADERS_DIR := /some/path/to/dir

CFLAGS := "-g -I$(HEADERS_DIR) -O2"
</code>```

(Python)

```<code>headers_dir = "/some/path/to/dir"

cflags = "-g -I{headers_dir} -O2".format(**locals())
</code>```

And now compare this to possible Haskell's solution. Firstly:

```<code>$ cabal install interpolatedstring-perl6
$ ghci -XExtendedDefaultRules -XQuasiQuotes
</code>```

And then:

```<code>> import Text.InterpolatedString.Perl6 (qq)
> let headers_dir = "/path/to/some/dir"
> [qq| -g -I$headers_dir -O2 |] :: String
</code>```

While I think Make goes maybe a step too far in its eagerness to interpolate even when not asked, I wonder why Haskell doesn't have a format function like Python does. It could parse the supplied string and pull the value with same name as referenced in pattern:

```<code>let headers_dir = "/path/to/some/dir"
format "-g -I$headers_dir -O2"
</code>```

Is there a specific reason why it's not implemented, or everyone is just happy with Text.Printf's verbosity and/or lengthy setup of interpolation libraries?

Update: A lot of people misinterpret the question as asking about general string formatting, with possibility of precision specification in case of integers, etc. The examples provided demonstrate one specific case of interpolation, which is just "substitute the result of show a at the place of name". It does allow for simpler syntax, and it does not use a variadic function per se.

答:
I suspect it's done as quasiquoting because this will interpolate the string at compile time, and due to the pure nature of functions in Haskell this is possible while other languages lack such ability because of their impure nature.

Think about it, other languages have to do it during runtime each time which is going to be much slower than the compile time once and done quasi-quoted interpolation.

If you want to do it at runtime explicitly then you should be able to do some simple abstractions that take advantage of Haskell's strings being lists, or you could create a different data structure that's similar pretty easily - but I would go for the more efficient quasi-quoted approach if I were doing this in any code I actually cared about.

That said, I found on Hackage the Data.Text.Format package which appears to do C# style substitution pretty straight forward, here's an answer showing an example on SO:
String formatting in Haskell - though as noted by Bryan O'Sullivan and others on that question that answer usess an out-dated package and there's a newer one Bryan has created (my guess the Data.Text.Format package is his new one that should be used) so the usage may be slightly different from in that SO example, though appears fairly similar.


答:
If you're talking about unit testing and you're doing TDD (writing the tests first) then this is a non-issue: you just stop testing when the features are done.

In incremental TDD, you write a test that fails, then implement the smallest amount of code that can make it pass, then refactor. Keep adding tests in this manner until the method is feature complete.

Here's a great example.

Title: How To Know When To Stop Testing?

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


答:
updated after question update

I feel that the python version:

```<code>"-g -I{headers_dir} -O2".format(**locals())
</code>```

is an abuse of the language. So I wouldn't say that python really offers local variable interpolation in strings. In fact, few languages have it.

Answering why language X doesn't have feature Y often comes down to saying that the designers did not feel that it was worth it. In the case of local variable interpolation in strings, it is very much a niche thing used in languages focused on command line scripts. Which Haskell is not. The fact that you can do it in python only comes from the (too?) powerful reflection facilities of the language.

Now why is Text.InterpolatedString.Perl6 so complex to use? It relies on quasiquotations, which is not part of the haskell language. It is a ghc language extension, so you have to declare its usage somewhere. If you exclude the library installation & the language extension declaration, its usage is not really more complex than in your other examples, and is more safe.

Title: Why doesn't Haskell have a 'format' function for string interpolation?

Body:
I'm trying to use Shake and I stumbled upon the following problem: there's no easy and convenient way to interpolate a string. I know about Text.Printf — it's not what I'm looking for. The interpolation syntax I'm talking about is like this:

(Make)

```<code>HEADERS_DIR := /some/path/to/dir

CFLAGS := "-g -I$(HEADERS_DIR) -O2"
</code>```

(Python)

```<code>headers_dir = "/some/path/to/dir"

cflags = "-g -I{headers_dir} -O2".format(**locals())
</code>```

And now compare this to possible Haskell's solution. Firstly:

```<code>$ cabal install interpolatedstring-perl6
$ ghci -XExtendedDefaultRules -XQuasiQuotes
</code>```

And then:

```<code>> import Text.InterpolatedString.Perl6 (qq)
> let headers_dir = "/path/to/some/dir"
> [qq| -g -I$headers_dir -O2 |] :: String
</code>```

While I think Make goes maybe a step too far in its eagerness to interpolate even when not asked, I wonder why Haskell doesn't have a format function like Python does. It could parse the supplied string and pull the value with same name as referenced in pattern:

```<code>let headers_dir = "/path/to/some/dir"
format "-g -I$headers_dir -O2"
</code>```

Is there a specific reason why it's not implemented, or everyone is just happy with Text.Printf's verbosity and/or lengthy setup of interpolation libraries?

Update: A lot of people misinterpret the question as asking about general string formatting, with possibility of precision specification in case of integers, etc. The examples provided demonstrate one specific case of interpolation, which is just "substitute the result of show a at the place of name". It does allow for simpler syntax, and it does not use a variadic function per se.

Body:
updated after question update

I feel that the python version:

"-g -I{headers_dir} -O2".format(**locals())

is an abuse of the language. So I wouldn't say that python really offers local variable interpolation in strings. In fact, few languages have it.

Answering why language X doesn't have feature Y often comes down to saying that the designers did not feel that it was worth it. In the case of local variable interpolation in strings, it is very much a niche thing used in languages focused on command line scripts. Which Haskell is not. The fact that you can do it in python only comes from the (too?) powerful reflection facilities of the language.

Now why is Text.InterpolatedString.Perl6 so complex to use? It relies on quasiquotations, which is not part of the haskell language. It is a ghc language extension, so you have to declare its usage somewhere. If you exclude the library installation & the language extension declaration, its usage is not really more complex than in your other examples, and is more safe.


问:
DMCA as a license for closed-source javascript code
I have a proprietary project, with parts of it written in javascript.  We would like a software license to include in the header file for this code which ensures the work remains:

proprietary

cannot be reverse engineered (as it will be obfuscated / minimized)

cannot be reused elsewhere

cannot be linked to

does the DMCA do all of this?  Does anyone use the DMCA in this way?

I looked at this other question, Best existing license for closed-source code, about other possible language, but want to know specifically about the benefits and failings of the DMCA as a license.

答:
The DMCA is a law, not a license.  It applies to everyone who works with software (within the law's jurisdiction) not just the people you are distributing your software to.

Your best bet is to articulate your terms in your own license.  You can use other licenses as a guide for doing this, if you wish.  If the specific character of the license, and the manner in which it is used, is important to you, consider paying a lawyer that specializes in licensing law a few hundred dollars to help you draft it.

Be aware that there is no such thing as "prevention of reverse-engineering," especially with respect to Javascript.  If you really want to keep that code private, run it on the server, not the client.


问:
Inform caller or just let them deal with exception?
I'm not sure how to proceed in the following situation.

say we have a function as so:

```<code>def runsATask(codes):
    myDicts = [helperFunc(code) for code in codes]
    for item in myDicts:
        # some logic.
</code>```

Here's the problem, codes is some iterable and should be either a list or a tuple, ie it should be used as so: runsATask(['code1', 'code2', ... 'codeN']), but sometimes N is 1 and so people could call it mistakenly, like so, runsATask('code1') This code will still run, but later on in the for loop it will crap out because myDicts doesn't have the correct objects in it because the list comprehension that made it iterated over a string rather than a list/tuple.

So should I leave it as it is or would the following be a solution:

```<code>def runsATask(codes):
    if not isinstance(codes, (list, tuple)):
        raise Exception("Codes should be a list or a tuple")
    myDicts = [helperFunc(code) for code in codes]
    for item in myDicts:
        # some logic.
</code>```

I'm not sure which way to go because I hear Python circles say to let callers deal with the issue, but debugging a situation like this can be annoying because the caller would deal with the issue in the for loop and had he been informed way earlier about the wrong parameter being passed, then it would save a lot of wasted time.

答:
This code

```<code>if not isinstance(codes, (list, tuple)):
    raise Exception("Codes should be a list or a tuple")
</code>```

Is called a Guard Clause, and it's a perfectly valid technique.

The reason you throw an exception here is that (presumably), if codes is not an instance of (list, tuple), then the method has no way to recover (unless you want to return some default value or error code from the method instead).

Body:
This code

if not isinstance(codes, (list, tuple)):
    raise Exception("Codes should be a list or a tuple")

Is called a Guard Clause, and it's a perfectly valid technique.

The reason you throw an exception here is that (presumably), if codes is not an instance of (list, tuple), then the method has no way to recover (unless you want to return some default value or error code from the method instead).


答: A guard clause is very reasonable, but have you considered whether there a negative to creating a list and inserting codes into it if it is not a list or tuple? If the function can compensate without user interaction that would prevent a fatal exception it should do so as long as it doesn't create a side effect.</p>

Title: Inform caller or just let them deal with exception?

Body:
I'm not sure how to proceed in the following situation.

say we have a function as so:

```<code>def runsATask(codes):
    myDicts = [helperFunc(code) for code in codes]
    for item in myDicts:
        # some logic.
</code>```

Here's the problem, codes is some iterable and should be either a list or a tuple, ie it should be used as so: runsATask(['code1', 'code2', ... 'codeN']), but sometimes N is 1 and so people could call it mistakenly, like so, runsATask('code1') This code will still run, but later on in the for loop it will crap out because myDicts doesn't have the correct objects in it because the list comprehension that made it iterated over a string rather than a list/tuple.

So should I leave it as it is or would the following be a solution:

```<code>def runsATask(codes):
    if not isinstance(codes, (list, tuple)):
        raise Exception("Codes should be a list or a tuple")
    myDicts = [helperFunc(code) for code in codes]
    for item in myDicts:
        # some logic.
</code>```

I'm not sure which way to go because I hear Python circles say to let callers deal with the issue, but debugging a situation like this can be annoying because the caller would deal with the issue in the for loop and had he been informed way earlier about the wrong parameter being passed, then it would save a lot of wasted time.


答:
Instead of the four letters, "DMCA", it might be better to use just three: "FBI". Specifically the FBI's anti-piracy warning seal and authorized language that explicitly informs the end-user of copyright law, and the authority of the FBI in such matters of law if under the appropriate jurisdictions.

One must keep one thing in mind, though: the FBI does not provide software licenses, and the DMCA isn't a license either, nor can either the FBI warning nor the DMCA be used as one.

However, you might then want/need to be clear about how this is handled in other countries, where - despite some extreme examples and often public opinion - US law does not apply or is simply not honored, or even conflicts with local law.

You might also wish to have an explicit document that cites relevant law and "reminds" anyone who reads it (and cares) about applicable law and the penalties for violating it.

However, attempting to craft a "license" should be done be a properly credentialed and experienced lawyer, for the same reason surgery is generally best left to surgeons - one small slip and it's all for naught. As a simple example, when the DMCA - or its interpretation and relevant case law changes - does your license become null and void, or at least unenforceable? Sever-ability, etc - all issues that require good counsel from someone who really knows their stuff.

Simply reminding people that it may be against the law - and you are granting no license otherwise - to reverse-engineer or distribute your code doesn't really require a lawyer, though one should be careful about the chilling effects of coming off as hostile to potential customers. A proper software license, custom written for your specifications, most certainly does.

Title: DMCA as a license for closed-source javascript code

Body:
I have a proprietary project, with parts of it written in javascript.  We would like a software license to include in the header file for this code which ensures the work remains:

proprietary

cannot be reverse engineered (as it will be obfuscated / minimized)

cannot be reused elsewhere

cannot be linked to

does the DMCA do all of this?  Does anyone use the DMCA in this way?

I looked at this other question, Best existing license for closed-source code, about other possible language, but want to know specifically about the benefits and failings of the DMCA as a license.


问:
Effective way to estimate dead code removal?
I've been working in an application with about 100k LOCs and basically We have been reworking features to comply with a new architecture based on a new technology stack. This work is almost finished but we had to keep the old code because we had to guarantee a stable environment in case of critical bugs in the new .

This has lead to a situation where we have a lot of dead code that mixes with a lot of working code thus making difficult to estimate how much time it would take to remove this dead code.

This codebase in particular is very troublesome as it does not have unit/integration testing other than the one generated in the process of reworking the features we migrated to the new architecture and also I think that a great deal of the new code is interwoven with the dead code (by static calls, using the previously thrown exceptions).

What would be a good start point to estimate how long would it take to safely remove the code?

答:
What if you using a global find and replace entered this into the constructor of every class:

```<code>PrintToMyLogFile(this.className);
</code>```

Run your higher level tests including manual tests.  Then delete all of the files that arn't in your log file.

This obviously is going to break some things but you can fix those as you go along.  This will ensure that you will be able to remove all classes that are not used.

In reality this probably isn't a great way to go about it and probably has multiple issues that I haven't considered yet.

Body:
What if you using a global find and replace entered this into the constructor of every class:

PrintToMyLogFile(this.className);

Run your higher level tests including manual tests.  Then delete all of the files that arn't in your log file.

This obviously is going to break some things but you can fix those as you go along.  This will ensure that you will be able to remove all classes that are not used.

In reality this probably isn't a great way to go about it and probably has multiple issues that I haven't considered yet.


问:
How should I validate code when there is no one to do code review?
I'm used to working in a large development environment where code is peer reviewed and tested by the client, who is usually an IT person themselves. I am now working at a very small company where I'm not just the only developer, but the only IT person at all.

I'm inclined to have my coworkers and/or boss take a look at my work every time I finish a agile story, so they can either accept it or reject it, as is the pattern I'm used to. However, too often my coworkers either don't understand my work well enough to judge it or they misunderstand it and accept bad code or reject good code based on surface looks alone, like the color of links.

So I'm wondering how I should decide when to accept/reject tests now? Should I try to assess my own code like an outside person? Should I just skip it and accept everything? Should I try to educate my coworkers a bit and get them to do proper tests?

答:
To assess your code you can use automated tools like PMD, Findbugs, Sonar, etc. Which one of these have a set of rules that evaluate your code against best pratices and design patterns. They also let you create new rules to match your patterns and architecture design. You can run them integrated on your IDE, on a CI Server (like Jenkins) or on a simple batch script.

They are not perfect but can give a help while you don´t have another developer to review your code. They are free and can be scheduled to run every night so you get a fresh report every morning. :)


答:
The best typesafe approach I can offer you is the formatting library

```<code>{-# LANGUAGE OverloadedStrings #-}

import Formatting (format, (%))
import Formatting.ShortFormatters (t)

headers_dir = "/path/to/some/dir"

example = format ("-g -I" % t % " -O2") headers_dir

GHCi> example
"-g -I/path/to/some/dir -O2"
</code>```

Body:
The best typesafe approach I can offer you is the formatting library

{-# LANGUAGE OverloadedStrings #-}

import Formatting (format, (%))
import Formatting.ShortFormatters (t)

headers_dir = "/path/to/some/dir"

example = format ("-g -I" % t % " -O2") headers_dir

GHCi> example
"-g -I/path/to/some/dir -O2"


问:
Nomenclature for wildcard vs regex expressions
When I see the term pattern in a description of syntax I infer a regular expression is being specified. Is there a separate term that specifies a wildcard expression?

```<code>^foo.*(bar|baz){3} <--  'regular expression' or 'pattern'
foo*bar.txt        <--- 'wildcard expression' or ...?
</code>```

Or is a wildcard expression just another type of pattern requiring context information to discern the distinction?

答:
The official name is a "glob" pattern. According to Wikipedia, the term originally was the name of a program (/etc/glob) which in the comments called itself "global command". It stems from an early versions of unix.

Wikipedia has a more information, including a link to the original source. The top of the original source contains this comment:

```<code>/* global command --

   glob params

   "*" in params matches r.e ".*"
   "?" in params matches r.e. "."
   "[...]" in params matches character class
   "[...a-z...]" in params matches a through z.

   perform command with argument list
  constructed as follows:
     if param does not contain "*", "[", or "?", use it as is
     if it does, find all files in current directory
     which match the param, sort them, and use them

   prepend the command name with "/bin" or "/usr/bin"
   as required.
*/
</code>```

For more information see http://en.wikipedia.org/wiki/Glob_(programming)

Body:
The official name is a "glob" pattern. According to Wikipedia, the term originally was the name of a program (/etc/glob) which in the comments called itself "global command". It stems from an early versions of unix.

Wikipedia has a more information, including a link to the original source. The top of the original source contains this comment:

/* global command --

   glob params

   "*" in params matches r.e ".*"
   "?" in params matches r.e. "."
   "[...]" in params matches character class
   "[...a-z...]" in params matches a through z.

   perform command with argument list
  constructed as follows:
     if param does not contain "*", "[", or "?", use it as is
     if it does, find all files in current directory
     which match the param, sort them, and use them

   prepend the command name with "/bin" or "/usr/bin"
   as required.
*/

For more information see http://en.wikipedia.org/wiki/Glob_(programming)


问:
What did machine code for 4-bit architecture look like?
I don't know how a 4-bit instruction could be enough to do something so I read about the Intel 4004 and it says that it used 8-bit instructions and then I can understand how opcode and numbers has enough digits.

Is it true that there never were any 4-bit instructions and that 4-bit systems use 8-bit instructions?

And that opcode and two numbers in an instruction can be done in 8 bits but not in 4 bits?

答:
Your question has some invalid premises in it.

The first one is that, if you are using 8 bit instructions, then it must not be a 4 bit architecture.  That's not true.  You can say categorically that instructions are 2 nibbles wide, but that doesn't make the architecture any less 4 bit.  That an architecture is 4 bit just means that the information travels around the system in 4 bit chunks.

The second one is that instruction opcodes always have to be one "system-width word" long.  That's clearly not true either, as the 4004 example indicates.  Computers historically have always been able to choose the number of "words" they need for any given situation, including the ability to represent more opcodes than can be represented by the system word length.


问:
Why are threads called threads?
I understand that a process a unit of resource ownership and executable instructions. Threads allow a process to share its resources with multiple executions, and it's easier for an OS to schedule threads because of all the overhead associated with whole processes.

But why the name thread? Does it have some reference to string or the interleaving of execution? Even so, this isn't an intuitive term in my opinion.

答:
tl;dr: They're called threads because "thread" is an apt metaphor.

When you start a thread, you rely on the operating system to allocate processing time so that your thread can execute.  While your thread is executing, the processor (or core) is placing all of its attention on your thread.  When the operating system switches the core to a different thread, your thread stops executing while the other thread is being serviced.

So execution jumps around all over the place.  But the integrity of the set of machine instructions remains intact, in spite of these jumps, because we build fences and concurrency mechanisms to protect its state, and the state of the objects it interacts with.

So the thread refers, not to the execution of instructions in any particular thread, but to the instructions that will eventually be executed within the thread that we have created.  Each thread, in other words, can be thought of as an individual machine or agent (we call them lightweight processes), without having to think about all of the context switches that the operating system is performing to give the appearance that they're all executing simultaneously.

In other words, despite all of the jumping around that the OS does behind the scenes, that which we call a thread (the sequence of operations that we are executing in a lightweight process) still can be thought of as the same sequence of operations, had we not spawned the thread, assuming we have taken the necessary concurrency protections.

If this description seems too weighty and abstract, then think of a thread in a forum, like Reddit.  You can branch off new discussions; each discussion is its own thread.  You can jump back and forth between threads.  But each thread still maintains its structural integrity as an individual conversation.

Title: Why are threads called threads?


问:
C# Design Issue
I am building a small application and I am trying to understand the best way to approach the design. I am looking for some guidance/advice how best to approach the following issue.

What I have is that I receive a set of data, real time. I then analyze the data for patterns. The patterns are classes that derive from an abstract class which implements an interface. The number of patterns will change over time as patterns are added/removed. In addition, depending on the access level of the user, the data is analyzed with different pattern options.

For example, if I have five patterns, A, B, C, D and E, level 100 access may only analyze the data with pattern A whereas access level 300 will analyze with patterns B, D and E, and access level 500 will analyze with all the patterns. The access levels are linked to the user, and a user can have different access levels on different data streams.

My thought is to create a hash table or dictionary for the patterns and a db for the users and their various access levels. Is this the best way to go or is there a better approach that will work in real time?

答:
You're on the right track, what you've described is a classic Strategy pattern.

There seems to be some confusion around the answer and I'll elaborate. The question is a little ambiguous as to what is being asked and such broad questions are usually flagged, but I wanted to answer the general gist.

The composition of behaviors over a single interface allows for multiple implementations to be instantiated and swapped out at run-time, which is the basic definition of a strategy pattern. The behaviors can be instantiated upon startup or construction and then stored in a simple dictionary for selection by key on an as-needed basis, or perhaps constructed on the fly as needed via dependency injection.

Several commentators seem to be taking issue with the notion of 'real time' as it is traditionally used as speed of results, and my perspective relevant to the question is simply that data is processed per call.

Lastly, a persistent data store of users and roles is exactly what is needed to create an authorization scheme for demarcating which behaviors can be used by which users.

Hopefully this clears up the answer.

Title: C# Design Issue


答: The first things to test would be the "happy path", edge cases, and invalid inputs. If there will be more than one concurrent user, you'll need to test for concurrency issues like locking and race conditions. If the app uses external resources, you'll need to test how the app behaves when those resources are unavailable. After that, you can use the code to look for things that might cause it to break and test for those. When all of those tests pass, the cost/benefit ratio of further testing starts to go up, so it's reasonable to stop at that point.</p>

Title: How To Know When To Stop Testing?


问:
Another way of expressing 'Dirty' coding
I'm writing a brief for a new starter at the company.

I've pointed out the aims of what I want to achieve and now I'm writing some suggested (but not concrete) solutions.

For each of the aims, I'd like to suggest a fast, dirty method, and a slower, but more robust solution. I don't mean 'dirty' as in uncommented and untabbed code, but simply as in faster, hackishy code.

I'm happy that the new starter takes whichever pathway they feel are necessary, and I feel my use of the word 'dirty' is going to put them off that particular solution. They're probably going to try to impress the management, and I don't want the 'dirty' solution to be a turn-off if that's what they're most comfortable with.

Can you help me decide on a slightly better terminology than dirty?

I aim to contrast between the hacky/fast solution (which is still valid) and a more robust, scalable solution. For a project as trivial as the one we're producing, then either method will be accepted.

答:
The problem with saying dirty or hackish is that they are likely to think of your code like a dirty crawlspace. If it's cheaper and no one is going to see it anyway then why should they care? You need to make it clear that the hackish solution is more like an unstable foundation. If you need to add on to the "building" then you will either have to fix the foundation (at greater cost than building it solid in the first place) or rebuild it altogether.

If you want to be sure that non-technical, business-minded individuals understand what they are choosing, communicate in terms of time/cost.

Rather than describing programming methods, I would use a term to describe the type of product you are producing. I would give options of quality code or throw-away code and describe the latter as being non-scalable, and non-maintainable. This makes it clear that adding on to the code will be more costly than rewriting it. The only reason for choosing such a solution is if you're confident that the piece you are building will never change and are willing to pay the difference if you're wrong.

Also consider that unless the decision makers are also programmers, they will not understand to what degree your hackish shortcuts will hamper change going forward. Only you know that. So it might be better if you get from them the estimated importance, longevity, and likelihood of change for a piece and make the technical decisions yourself.


答: Common terms are spikes, proof of concepts and prototypes.</p>

Body:
I'm writing a brief for a new starter at the company.

I've pointed out the aims of what I want to achieve and now I'm writing some suggested (but not concrete) solutions.

For each of the aims, I'd like to suggest a fast, dirty method, and a slower, but more robust solution. I don't mean 'dirty' as in uncommented and untabbed code, but simply as in faster, hackishy code.

I'm happy that the new starter takes whichever pathway they feel are necessary, and I feel my use of the word 'dirty' is going to put them off that particular solution. They're probably going to try to impress the management, and I don't want the 'dirty' solution to be a turn-off if that's what they're most comfortable with.

Can you help me decide on a slightly better terminology than dirty?

I aim to contrast between the hacky/fast solution (which is still valid) and a more robust, scalable solution. For a project as trivial as the one we're producing, then either method will be accepted.


答: I coded a similar type of application where I have various access levels and patterns to analize a input data, in that case what my team do was make all the patterns as childs of a abstract class and store that classes name in the database, users and their access level were stored as well. When a user logs to the system all the patters for his level were loaded via reflection. In our case the data was the Twitter Stream and we analize all the tweets to match with predefine patters such "HasALink" or "MentionPeopleInList", the solution perform well for us.</p>

Title: C# Design Issue

Body:
I am building a small application and I am trying to understand the best way to approach the design. I am looking for some guidance/advice how best to approach the following issue.

What I have is that I receive a set of data, real time. I then analyze the data for patterns. The patterns are classes that derive from an abstract class which implements an interface. The number of patterns will change over time as patterns are added/removed. In addition, depending on the access level of the user, the data is analyzed with different pattern options.

For example, if I have five patterns, A, B, C, D and E, level 100 access may only analyze the data with pattern A whereas access level 300 will analyze with patterns B, D and E, and access level 500 will analyze with all the patterns. The access levels are linked to the user, and a user can have different access levels on different data streams.

My thought is to create a hash table or dictionary for the patterns and a db for the users and their various access levels. Is this the best way to go or is there a better approach that will work in real time?

OwnerDisplayName: mart


答:
It all boils down to a matter of confidence. Do you feel confident that the system is tested enough?

Obviously, "confidence level" is highly subjective since you can never feel completely certain, but certain enough -- and that is what we are looking for. For that, you need to create a list of indicators, commonly known as definition of done and should be something your whole team agrees upon.

Here are a few test related "Done-indicators":

Is your build and installation completely automated and all tests (unit, gui, integration) executed automatically?

Do you write your tests while (or preferably before) writing the code, rather than after?

Do you feel safe enough to make large code refactoring without introducing bugs?

Is your code coverage level high enough?

Do you have a dedicated tester in your team? Is he/she involved daily throughout the whole development and not just at the end?

Has your tester manually (exploratory) tried to break it without success?

If you can check these points, then you probably can say you have tested enough.

Title: How To Know When To Stop Testing?


答:
Have you looked in a dictionary? The word thread has a meaning past sewing.

3:  something continuous or drawn out: as

a:  a line of reasoning or train of thought that connects the parts in
  a sequence (as of ideas or events)

http://www.merriam-webster.com/dictionary/thread

Title: Why are threads called threads?

Body:
I understand that a process a unit of resource ownership and executable instructions. Threads allow a process to share its resources with multiple executions, and it's easier for an OS to schedule threads because of all the overhead associated with whole processes.

But why the name thread? Does it have some reference to string or the interleaving of execution? Even so, this isn't an intuitive term in my opinion.


答:
Ever seen how multiples threads, twisted, form a thicker, stronger cord ?

That's the metaphor, every thread is independent but all threads together collaborate to a final computational output. Besides, as in the textile thread, a thread can break without compromising the structure of the whole cord.

Title: Why are threads called threads?


问:
Can I use the code for responsive video on this github link under a license?
This is the link: https://gist.github.com/jgarber/2302238

I am new to github and web development.So please bear with my questions.
I would like to use the responsive video code on the link mentioned above,
for a commercial website I am building.

I see that the code is posted under the 'public' section but there is a
copyright attached as well.

And, the file name is MIT-LICENSE.txt. Does this have any connection with the MIT-License?

Two questions:

a) Can I use this code by giving an attribution?

b) And, if I can, under which license can I use the code and what sort of attribution is required?

答:
The file does say MIT license, but that file does not contain an MIT License. According to the contents of that file, it's just copyrighted.

But then they have posted it on Github ... Personally, I'd suggest getting in touch with the author and asking them directly.


答:
A lot of the tips provided are excellent, I would just add a few from my experience in a similar position.

Get involved in the hiring decisions and don't be afraid to veto candidates that are not . You'll need to work closely with the team and they'll represent your to your clients and to management.

Establish a culture of honesty with your team members and expect honesty from them especially when the situations are difficult.

Learn to delegate and then focus on solutions and not process.

Title: Advice for solo programmer whose team will expand in the near future

Body:
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.