问:
Advise how to write a simple test for this javascript snippet?
I'm trying to start unit testing (not using any testing frameworks) for my javascripts.

Here's one example of it.

```<code>var obj = {};

obj.disableBtn = function ($btn, style) {
  $btn.attr('disabled','disabled').addClass('disabled').removeClass(style);
};
</code>```

The use case is as such:

```<code>obj.disableBtn($('.submit'), 'btn-blue');
</code>```

What it does is simply add the disabled attribute, add the disabled class, and remove the btn-blue style.

Please advise how would a typical test case look like in this case.

I have a little knowledge on testing using assert(), but have no idea how to go about it when it involves verifying the result on HTML elements.

答:
I recommend using a JS unit testing framework, such as qUnit. There's no need to reinvent unit testing tools from scratch, and you will be able to focus on testing your specific functionality.

You could then create a unit test that creates a button which is not disabled and has the "active" style properties attached to it. Next, run your disableBtn function and assert that the button is disabled and no longer has the style attached to it. The unit test code would then look something like:

```<code>ok(true === yourButton.prop("disabled"));
ok(false === yourButton.hasClass('btn-blue'));
</code>```

(jQuery functions used here since we're mostly concerned about the unit testing code. You can of course check the attributes using vanilla JS).

Body:
I recommend using a JS unit testing framework, such as qUnit. There's no need to reinvent unit testing tools from scratch, and you will be able to focus on testing your specific functionality.

You could then create a unit test that creates a button which is not disabled and has the "active" style properties attached to it. Next, run your disableBtn function and assert that the button is disabled and no longer has the style attached to it. The unit test code would then look something like:

ok(true === yourButton.prop("disabled"));
ok(false === yourButton.hasClass('btn-blue'));

(jQuery functions used here since we're mostly concerned about the unit testing code. You can of course check the attributes using vanilla JS).


问:
API design: concrete vs. abstract approach - best practices?
When discussing APIs between systems (on the business level) there are often two different point of views in our team: some people prefer a more - lets say - generic abstract approach, other a straight forward "concrete" approach.

Example: the design of a simple "person search" API. the concrete version would be

```<code> searchPerson(String name, boolean soundEx,
              String firstName, boolean soundEx,
              String dateOfBirth)
</code>```

People in favour of the concrete version say:

the API is self-documenting

it is easy to understand

it is easy to validate (compiler or as a webservice: schema validation)

KISS

The other group of people in our team would say "That is just a list of search criteria"

```<code>searchPerson(List<SearchCriteria> criteria)
</code>```

with

```<code>SearchCritera {
  String parameter,
  String value,
  Map<String, String> options
}
</code>```

with possibly making "parameter" of some enumeration type.

Proponents say:

without changing the (declaration of) the API the implementation can change, e.g. adding more criteria or more options. Even without synchronizing such a change at deployment time.

documentation is necessary even with the concrete variant

schema validation is overrated, often you have to validate further, schema cannot handle all cases

we already have a similiar API with another system - reuse

The counter-argument is

lots of documentation about valid parameters and valid parameter combinations

more communication effort because it's more difficult to understand for other teams

Are there any best practices? Literature?

答:
It depends on how many fields you're talking about, and how they are used.  Concrete is preferable for highly structured queries with only a few fields, but if the querying tends to be very free form, then the concrete approach quickly becomes unwieldy with more than three or four fields.

On the other hand, it's very difficult to keep a generic API pure.  If you do a simple name search in a lot of places, eventually someone is going to tire of repeating the same five lines of code, and they're going to wrap it in a function.  Such an API invariably evolves into a hybrid of a generic query together with concrete wrappers for the most commonly used queries.  And I don't see anything wrong with that.  It gives you the best of both worlds.

ContentLicense: CC BY-SA 3.0


问:
In need of a more technical answer for an interview question about how the internet works from beginning to end
I've had interviews with 5 separate people over the past two weeks and three of those five have all asked me this question:  Explain what happens between hitting "Google.com" and the page coming up on the screen.  Basically, how the Internet works.  I figure after three times that I better be prepared if I ever get this question again.

I know some things, but I'm not fully convinced that my answer is good enough.  Basically, I mention that the DNS server translates "google.com" into an IP address.  I kinda gloss over TCP/IP, then talk about the web server literally serving up requested pages that get sent back to the browser which the browser then interprets and displays.

As I said before, I'm not convinced my answer is technical enough.  What are the steps that I'm leaving out?

For what it's worth, two of those three times have been with the same company and I'm being called back for a third interview with them, so I can't have bombed it too hard.

答:
Your browser first has the OS look in its "hosts" file for an entry that will translate the domain name to an IP address. This is a legacy feature inherited from ARPANET, when it was possible for a single text file to contain intelligible names for every computer accessible via the ARPANET, and for each computer connected to it to have a relatively recent copy. It used to have some remaining value in small networks of computers that didn't have NetBIOS or similar node-naming protocols, but nowadays it's as likely to be a target for hackers (who can use it to bypass DNS and point your computer to sites they control) as to have any legitimate use to a client computer or its user/owner.

Assuming your computer doesn't have a HOSTS entry for this domain, your browser sends a UDP request to the DNS server configured in the OS's Internet settings for the connection being used, passing the "host name" aka domain name of the request (everything between "http://" and the first colon or forward slash following what comes next; i.e. "www.google.com"). This DNS server typically belongs either to your company or to your local Internet Service Provider.

UDP stands for "Universal Datagram Protocol", and is a "transport-layer" protocol in the same class as TCP (above the "network-layer" IP protocol, below the "application-layer" protocols like HTTP, FTP, SMTP etc). While TCP provides for a lot of error-checking and fault-tolerance capabilities (adding extra data and so increasing the overhead), UDP takes a much more lightweight approach, increasing net data bandwidth; the tradeoff is that the protocol doesn't support features available in TCP like splitting up large data into multiple packets (so messages have to be small) or re-sending packets lost in transit. It's good for small, simple messages (like DNS) and streaming, telemetry-type data where it doesn't matter if one packet is lost.

This DNS server will know one of three things: how to translate that domain name directly into an IP address (meaning it's the "authoritative name server" or ANS for that domain); the IP address of the ANS or a parent of it; or its own parent nameserver which is more likely to know how to reach the ANS. If the server does not translate the request itself, it will forward the request either "down" toward a known ANS, or "up" to its parent NS, and this process repeats recursively.

The "root" of this tree structure is a single server which does nothing but forward any requests it receives to one of a number of "top-level domain" or TLD servers. There is, for instance, a ".com" nameserver, who knows how to find the IP address of any ".com" domain on the planet (by forwarding these requests down to ISP-level nameservers). These TLDs forward requests for domain name servers that aren't known by any DNS within a specific "branch" of the internet belonging to an ISP.

Once the authoritative name server is found and has translated the domain name into an IP address, this address is returned to the client and its browser. If an ANS cannot be found within the request's "time to live" (TTL; the maximum number of times the request should be forwarded between servers, to avoid infinite cycling between misconfigured servers), an error is returned to the client by the node at which the request "times out" (or the node that is the authoritative server for the domain but that cannot translate the particular domain prefix).

The browser, for an HTTP connection, then sends a "TCP SYN" request to the IP address and specified port (or the default HTTP port of 80) to establish a connection. This is a protocol-level request, layered on top of the "network-level" IP header, that contains information such as the client's preferred response port (the "source port"), preferences for TCP communication such as segment size, window scale, and use of optional protocol features.

The request is routed at the "link level" (governing how the actual electrical circuits are manipulated to transmit the data contained at the network, transport and application layers) through the structure of the Internet; typically the data will travel along a wire or fiber to your home's or business's "Central Office" (this is called the "last mile" and is typically the circuit representing the biggest bottleneck to bandwidth) which is more or less the "onramp" to the Information Superhighway. The CO then has access to high-bandwidth pipes (T-carriers, SONET, etc) that transmit your request, along with billions of others, across the globe to the CO of the destination, which forwards it to the destination server or network.

This "IP routing" works in a conceptually similar way as DNS resolution; "top-tier" ISPs are assigned entire "class A" IP networks (every address possible given a known first byte) by ICANN, and other ISPs know who owns that Class A network and how to get the data to that network's nearest "front door", using information in a "routing table". This top-tier ISP then leases blocks of addresses, some to local ISPs, others directly to corporate users, and these ISPs and corporations have routers that use the IP address (and their own routing tables) to determine whether to send packets down to other nearby circuits, sideways to other local ISP routers, or up to higher-tier trunks and routers.

The server receives this request (provided it isn't rejected at a lower abstraction layer like the socket or a firewall), and if it decides to accept the connection it will send a "SYN-ACK" request-response step, both acknowledging the request and specifying its own preferences (including any of the clients' preferences that it can accomodate, but changing any that it cannot or that were not specified).

If the client supports communication using the option set the server has provided, it will send an ACK response, and now the connection is "established".

The browser next sends an "HTTP GET" request. The request includes the full URI of the resource requested by the browser (even though we know we're talking to www.google.com, we send that string as part of the request so that the server can, if it wishes, further interpret the domain name to direct the request). This request may include "cookies"; data stored on the client that can be given to the server to assist in processing the request efficiently and conveniently (such as identifying the preferences of the user).

The server receives the GET request, and first decides if it wishes to honor it (the server may have been listening for requests to TCP port 80, but expecting messages from a different application protocol like FTP or VoIP; this is rare for port 80 but more common for other types of ports). We will assume it does accept it; the server then returns an HTTP response containing the resource requested (in this case, the HTML for the default page which is Google's ubiquitous search page). The response may also include "cookies", which the server asks the client to store (the client may or may not do so).

The HTML is digested by the browser and rendered to draw the page in the browser window. While this happens, more HTTP GET requests for Javascript, style sheets, images, and other data that are needed to display all the content of the page in the manner prescribed by the HTML are sent by the client and the resulting data is provided by the server.

In a bygone age, Google was based on static forms; you typed what you wanted to search for into the textbox and hit "Search" (or "I'm Feeling Lucky"). When you do this, an HTTP POST request is sent by the client to the server; the request contains the location, specified by the client, that the information should be sent to, and of course the information itself. This information is digested by the server, which uses it to find search results, and the server builds a page of these results which it sends to you. Or, it can transform the search terms into a "query string", and respond with a "redirect"; a request for the browser to send another request to a different URI specified in the message. The browser will do so, and then the server will build and transmit that page.

In modern times, Google's front page is much more dynamic. As you type, JavaScript that executes on the client side within the browser sends what you're typing in to Google along a "side channel" (it uses the same protocols for communication, but because it's not the browser itself sending requests for entire pages, the browser screen is not cleared completely and re-drawn). For the front page, this is used to provide query hints (auto-complete suggestions for things you might be searching for because other people have done so recently); on the results page, it does the same thing but can also be used to provide real-time search results and completely redraw the page, without requiring a full page reload by the browser. These types of tricks fall under the general heading of AJAX (Asynchronous JavaScript and XML, although the competing JSON standard is used just as often for data formatting) and they are nearly ubiquitous in modern "web applications" to provide dynamic content over the relatively static, stateless call-and-answer model of the Internet.

This movie, which is the one they showed my freshman "Intro to IT" class in college, has the basics illustrated in friendly, analogous format. It's not technical by any means, but it provides a good conceptual overview of the pieces of this puzzle.


问:
How to deal with system "static" data in java
I was just wondering if there is some better way how to handle system "static" configuration data. Let say you have a system which offers several operation which are in code translated to operation code but you need to keep other related information to that operation like description, priority etc. Nasty way I have seen is public static final constants. Better way I was using before was create a class eg:

```<code>public abstract Codebook{
private int id;
private String description;
... getters setters
}
</code>```

Then for given cathegory - in this case OperationalCode:

```<code>public class OperationalCode extends Codebook{}
</code>```

Instance of this class were created with the data from BD. Now I cannot use DB so I thought I will create factories which will populate classes with given set of parameters. BUT all is hardcoded to factory class which I don't like.

Is there a better solution how to tackle this case as I believe I am not the first one solving that. Some handy framework or ...

I wasn't probably clear enough. I am fully aware of Properties capability in java but that doesn't match the criteria. Let me explain more:
When I say configuration I mean business configuration. You never know how many possible items you will get. For example in banking system you can cancel contract and you are forced to provide a reason for termination - predefined list which includes text, code in your system and translation to codes of third party systems where your system need to perform cancelation operation as well. Those possibilities need to be externalized of your system as they will probably change offten. Property files doesn't seems as a right choice and the opposite site - using Buisiness Rule Systems (e.g. Drools ) seems to me as overkill. Using enums with specified properties wouldn't fit quit well because time to time you need to be able to recognize that it is configuration and not just normal enum. That the reason for class inheritance - instanceof operator solve this.

答:
Store the constant values within a properties file called application.properties (for example)...

```<code>property1.value=Hello
property2.value=World
property3.value=Another property
</code>```

The content should match the key=value pattern and also, parameters are supported.

```<code>property.with.parameter=My name is {0}.
</code>```

If the file is stored within the root folder of the project, you can read each of them like this:

```<code>Properties properties = new Properties();

try {
    properties.load(new FileInputStream("application.properties"));
    System.out.println(properties.getProperty("property1.value"));
    System.out.println(properties.getProperty("property2.value"));
    System.out.println(properties.getProperty("property3.value"));
 } catch (IOException ex) {
    ex.printStackTrace();
 }
</code>```

You can read more about Properties in the Official Oracle Tutorials.

OwnerDisplayName: jaksky

Body:
Store the constant values within a properties file called application.properties (for example)...

property1.value=Hello
property2.value=World
property3.value=Another property

The content should match the key=value pattern and also, parameters are supported.

property.with.parameter=My name is {0}.

If the file is stored within the root folder of the project, you can read each of them like this:

Properties properties = new Properties();

try {
    properties.load(new FileInputStream("application.properties"));
    System.out.println(properties.getProperty("property1.value"));
    System.out.println(properties.getProperty("property2.value"));
    System.out.println(properties.getProperty("property3.value"));
 } catch (IOException ex) {
    ex.printStackTrace();
 }

You can read more about Properties in the Official Oracle Tutorials.

OwnerDisplayName: kocko


问:
Why can static methods only use static data?
I don't understand why a static method can't use non-static data. Can anybody explain what the problems are and why we can't do it?</p>

答:
I think the easiest way to explain this is to look at some code and then consider what results we would expect the code to produce.  </p>

```<code>// Create three new cars.  Cars have a name attribute.
Car car1 = new Car("Mazda3");
Car car2 = new Car("FordFocus");
Car car3 = new Car("HondaFit");

// Now we would like to print the names of some cars:
// First off why don't we try this:

Car.printCarName();

// Expected behaviour:
// If we think about what we are trying to do here it doesn't
// really make sense.  What instance of car name should this
// print?  Should it print Mazda3?  FordFoucs?
// What is the expected behaviour?  If we are going to have a
// static call on car call printCarName it should probably do
// something like print all car names or a random car name or
// throw an error.

//Now lets try this instead:

Car.printCarName(car1);

// Expected Behaviour:
// Luckily the expected behaviour is very clear here.  This
// should print Mazda3.  This works as expected.

// Finally lets try this:

car1.printMyName();

// Expected Behaviour:
// Same as previous example, however this is the *right* way
// to do it.
</code>```

<p>For completeness here is the car class: </p>

```<code>public class Car{

    public String name;

    public Car(String name){
        this.name = name;
    }

    public static printCarName(){
        print "Not sure what to do here...  Don't know which car you are talking about.";
    }

    public static printCarName(Car c){
        print c.name;
    }

    public /*NOT static*/ printMyName(){
        print this.name;
    }

}
</code>```

Body:
I think the easiest way to explain this is to look at some code and then consider what results we would expect the code to produce.

// Create three new cars.  Cars have a name attribute.
Car car1 = new Car("Mazda3");
Car car2 = new Car("FordFocus");
Car car3 = new Car("HondaFit");

// Now we would like to print the names of some cars:
// First off why don't we try this:

Car.printCarName();

// Expected behaviour:
// If we think about what we are trying to do here it doesn't
// really make sense.  What instance of car name should this
// print?  Should it print Mazda3?  FordFoucs?
// What is the expected behaviour?  If we are going to have a
// static call on car call printCarName it should probably do
// something like print all car names or a random car name or
// throw an error.

//Now lets try this instead:

Car.printCarName(car1);

// Expected Behaviour:
// Luckily the expected behaviour is very clear here.  This
// should print Mazda3.  This works as expected.

// Finally lets try this:

car1.printMyName();

// Expected Behaviour:
// Same as previous example, however this is the *right* way
// to do it.

For completeness here is the car class:

public class Car{

    public String name;

    public Car(String name){
        this.name = name;
    }

    public static printCarName(){
        print "Not sure what to do here...  Don't know which car you are talking about.";
    }

    public static printCarName(Car c){
        print c.name;
    }

    public /*NOT static*/ printMyName(){
        print this.name;
    }

}


问:
What is the general tech news website every programmer should read?
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.

答:
I feel like http://reddit.com/r/programming has high quality, interesting and up-to-date content.

The idea of reading tech news sites is to keep yourself entertained with latest technologies and discoveries. New interesting programming paradigms, people solving interesting database issues or just simple inspiring blogs by successful entrepreneurs.

Reddit brings all of this.

ContentLicense: CC BY-SA 2.5


问:
Finding the right license for my open source
I'm about to create a new open-source project and I'm not sure about the licensing method I should choose.

Here is what I know:

The project will be built on the basis of an already existing open source. I will fork from the original project and will build a community around a new project that has a code base from the original project.

In case the new project becomes successful, I will want to, one day, fork to an extended version of it which I will earn from. I want the non-free version to be non open-source.

For now, I have 2 main projects that I can use as my base project. One has a GPL license and the second has MIT license. I'm wondering what would better suit my needs. Also I'm wondering which license should I use for my open-source in order to, maybe, someday fork for a paid version which will not be open-sourced?

答:
The GPL is incompatible with your goals because it is viral. Once the code is open sourced by the original project, any fork must also abide by the GPL. If you are the copyright owner (which you will not be) then you can dual license your code, however.

The MIT license appears to be more flexible and would better suit your goals.

Source: http://opensource.org/licenses


问:
Why the question "give five things you hate about C#" is so difficult to answer during an interview?
In podcast 73, Joel Spolsky and Jeff Atwood discuss, among other subjects, "five things everyone should hate about their favorite programming language":

If you’re happy with your current tool chain, then there’s no reason you need to switch. However, if you can’t list five things you hate about your favorite programming language, then I argue you don’t know it well enough yet to judge. It’s good to be aware of the alternatives, and have a healthy critical eye for whatever it is you’re using.

Being curious, I asked this question to any candidate I interviewed. None of them were able to quote at least one thing they hate about C#¹.

Why? What's so difficult in this question? It is because of the stressful context of the interview that this question is impossible to answer by the interviewees?

Is there something about this question which makes it bad for an interview?

Obviously, it doesn't mean that C# is perfect. I have myself a list of five things I hate about C#:

The lack of variable number of types in generics (similar to params for arguments).

Action<T>,

Action<T1, T2>,

Action<T1, T2, T3>,

       ⁞

Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>

Seriously?!

The lack of support for units of measure, like in F#.

The lack of read only properties. Writing a backing private readonly field every time I want a read only property is boring.

The lack of properties with default values. And yes, I know that I can initialize them in the parameterless constructor and call it from all other constructors. But I don't want to.

Multiple inheritance. Yes, it causes confusion and you don't need it in most cases. It's still useful in some (very rare) cases, and the confusion applies as well (and was solved in C#) to the class which inherits several interfaces which contain methods with the same name.

I'm pretty sure that this list is far from being complete, and there are much more points to highlight, and especially much better ones than mine.

¹ A few people criticized some assemblies in .NET Framework or the lack of some libraries in the framework or criticized the CLR. This doesn't count, since the question was about the language itself, and while I could potentially accept an answer about something negative in the core of .NET Framework (for example something like the fact that there is no common interface for TryParse, so if you want to parse a string to several types, you have to repeat yourself for every type), an answer about JSON or WCF is completely off-topic.

答:
Most candidates aren't that deeply involved with more than one language or paradigm in order to contrast. I haven't worked with another object-oriented language for over 5 years now, and the one I had been working in (PowerBuilder), I had a lot of peeves with. Most guys fresh out of college are (or think they are) hot stuff at one, maybe two languages, and have received "exposure" to three or four more (meaning they completed at least one homework assignment requiring it but less than a full semester course studying it). That's not enough knowledge or experience to really know what's wrong with the language. Get a job in the real world, and that focus narrows considerably; you learn a lot more about the language that gets you the paycheck than any other, and in the process, you come to accept what the language won't do, or does in a weird way, to the point where you couldn't remember doing it differently.

Most C#-savvy candidates who compare it to Java/C/C++ are pretty happy with it. C# was designed from the ground up to do a lot of things better than Java (events, callbacks, the graphics library, database work). Java in turn was designed to be easier to use, and so more focused on correct code, than C++. I've yet to meet a C# programmer who wants to go back to C++ in any environment where blistering performance and near-circuit-level control aren't critical necessities.

In other words, See-Sharpers have it pretty good, all things considered.

Here's my list:

Lambda statements not watchable/evaluatable. Calls to named methods can be plugged into VS's QuickWatch. So can expressions. But lambdas? Nope (at least not in VS2010). Makes debugging Linq chains a real chore.

Optional parameter values for reference types other than string can only be null. if I were creating an overload stack, I might want to use other defaults. I might be able to default one value based on a property or simple expression based on another parameter. But I can't. So the value of not having to create an overload stack (which is minor with a refactoring assistant like ReSharper to handle the boilerplate) is diminished when the options for the optional parameters are so drastically limited.

C# is becoming old enough to have serious legacy code problems. Code originally written for 1.1 would cause anyone used to 4.0 to cringe in horror. Even 2.0 code misses out on a lot. In the same time, third-party libraries have come in that make things like ADO.NET seem woefully primitive (and much of ADO.NET's "connected model" is now a big anti-pattern). Yet, for backwards-compatibility, .NET schleps along support for all this old, bad code, never daring to say something like "ArrayList was a crappy way to do it, we're sorry we ever put it in and we're taking it out; use List instead and if you absolutely need a list of varying types, declare it as List<Object>.

Seriously limited switch statement rules. Probably one of the best things I could say about PowerBuilder is that the Choose Case statement (equivalent to switch) allowed Boolean expressions based on the variable. It also allowed switch statements to fall through even if they had code. I understand the reasons why that second one is disallowed (it's more likely to be done unintentionally than on purpose) but it would still be nice from time to time to write a statement like:

```<code>switch(someInt)
{
    case < 0: //all negative values enter here
       //...
       break;
    case 0:
       //...
       break;
    case 1:
       //...
       //no break; continue through to the code for > 1
    case > 1 // all positive values enter here (including 1)
       //...
       break;
}
</code>```

No INumeric interface. If it's a number, you can do math with it. In many cases the actual method doesn't have to care about exactly which types are plugged in; precision is the caller's responsibility. Yet it's not possible to create a generic method or class that can only accept number types as the GTP.

Body:
Most candidates aren't that deeply involved with more than one language or paradigm in order to contrast. I haven't worked with another object-oriented language for over 5 years now, and the one I had been working in (PowerBuilder), I had a lot of peeves with. Most guys fresh out of college are (or think they are) hot stuff at one, maybe two languages, and have received "exposure" to three or four more (meaning they completed at least one homework assignment requiring it but less than a full semester course studying it). That's not enough knowledge or experience to really know what's wrong with the language. Get a job in the real world, and that focus narrows considerably; you learn a lot more about the language that gets you the paycheck than any other, and in the process, you come to accept what the language won't do, or does in a weird way, to the point where you couldn't remember doing it differently.

Most C#-savvy candidates who compare it to Java/C/C++ are pretty happy with it. C# was designed from the ground up to do a lot of things better than Java (events, callbacks, the graphics library, database work). Java in turn was designed to be easier to use, and so more focused on correct code, than C++. I've yet to meet a C# programmer who wants to go back to C++ in any environment where blistering performance and near-circuit-level control aren't critical necessities.

In other words, See-Sharpers have it pretty good, all things considered.

Here's my list:

Lambda statements not watchable/evaluatable. Calls to named methods can be plugged into VS's QuickWatch. So can expressions. But lambdas? Nope (at least not in VS2010). Makes debugging Linq chains a real chore.

Optional parameter values for reference types other than string can only be null. if I were creating an overload stack, I might want to use other defaults. I might be able to default one value based on a property or simple expression based on another parameter. But I can't. So the value of not having to create an overload stack (which is minor with a refactoring assistant like ReSharper to handle the boilerplate) is diminished when the options for the optional parameters are so drastically limited.

C# is becoming old enough to have serious legacy code problems. Code originally written for 1.1 would cause anyone used to 4.0 to cringe in horror. Even 2.0 code misses out on a lot. In the same time, third-party libraries have come in that make things like ADO.NET seem woefully primitive (and much of ADO.NET's "connected model" is now a big anti-pattern). Yet, for backwards-compatibility, .NET schleps along support for all this old, bad code, never daring to say something like "ArrayList was a crappy way to do it, we're sorry we ever put it in and we're taking it out; use List instead and if you absolutely need a list of varying types, declare it as List<Object>.

Seriously limited switch statement rules. Probably one of the best things I could say about PowerBuilder is that the Choose Case statement (equivalent to switch) allowed Boolean expressions based on the variable. It also allowed switch statements to fall through even if they had code. I understand the reasons why that second one is disallowed (it's more likely to be done unintentionally than on purpose) but it would still be nice from time to time to write a statement like:

switch(someInt)
{
    case < 0: //all negative values enter here
       //...
       break;
    case 0:
       //...
       break;
    case 1:
       //...
       //no break; continue through to the code for > 1
    case > 1 // all positive values enter here (including 1)
       //...
       break;
}

No INumeric interface. If it's a number, you can do math with it. In many cases the actual method doesn't have to care about exactly which types are plugged in; precision is the caller's responsibility. Yet it's not possible to create a generic method or class that can only accept number types as the GTP.


答:
none

general tech news sites (mashable.com, et al) rarely have anything of use to me

EDIT 1: http://reddit.com/r/programming  is certainly interesting, but not critical

EDIT 2: note the question is ...that every programmer should read. There is no such site.

Title: What is the general tech news website every programmer should read?

Body:
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.


答:
The easiest thing to do would be to use the same license as the project you are forking from.

However if the original project is BSD licensed you need to think about another license.

I would disagree with some other posters and say that your type of project is an exact fit, you retain ownership but allow others to copy and improve. Indeed if the base project you are forking from is GPLed you must use the GPL license, at least for those pieces of your code which are based on the GPLed source.

Title: Finding the right license for my open source

Body:
I'm about to create a new open-source project and I'm not sure about the licensing method I should choose.

Here is what I know:

The project will be built on the basis of an already existing open source. I will fork from the original project and will build a community around a new project that has a code base from the original project.

In case the new project becomes successful, I will want to, one day, fork to an extended version of it which I will earn from. I want the non-free version to be non open-source.

For now, I have 2 main projects that I can use as my base project. One has a GPL license and the second has MIT license. I'm wondering what would better suit my needs. Also I'm wondering which license should I use for my open-source in order to, maybe, someday fork for a paid version which will not be open-sourced?


答:
As long as you choose one of the major open source licenses then you should be OK. I suggest sticking with one of the OSI's "Popular Licenses" But obviously you need to respect the terms of the original open source code that you build upon.

A "bait and switch" where you build an open source community around a pretence of openness  then make the product proprietary will, of course, be viewed very negatively by the open source community. You would probably lose all of your community and goodwill at this point.

A better option, if you want to be a good open source citizen while still making a profit, is to stay open source but charge for services and support for corporate users. This is the model used very successfully for Red Hat Linux, for example (which is GPL licensed).


问:
Is nesting typedefs a good style?
Let's say I have a namespace my and this namespace contains a class foo.

What should I prefer nesting typedefs into my class or hold it in my namespace?

```<code>namespace my {

class foo {
  // some stuff

  // nested one
  typedef bar my_foo_bar;

};

// or namespaced one
typedef bar my_foo_bar;

}
</code>```

Looking at the std-libs most things are the namespace variant.

(maybe a bad example but...) istream is not nested in iostream (at this point I only mean the way of using -> std::fstream, std::istream, ...), so I can use it directly. but also the list of possible functions is quite huge in std::

I could do both. The first variant is more encapsulated but also if I have to much inheritance I have to type a lot (my::foo::inh::and::so::on) if I won't use using [namespace].

First I thought the nested variant is more nice because of the encapsulation of what I want to have in the same "group". I also could do a new namespace inside my, but then I have also to type every time the new namespace (also without using [namespace]).

答:
I think that your choice here depends a lot on context.

As a general set of guidelines, I'd say, in rough decreasing order of importance:

you write your code once, and read it one or more times. What do you plan to do with your type? What kind of code will you likely have to write, including it? Optimize for maximum legibility, most of the time.

generally, it's better to use the most restricted possible name-space for your typedef. So, if you're only using it inside the class, define it there. If you're looking to access it from other places, that have access to the namespace, leave it outside of the class

as a heuristic, in my own work, I find myself placing the typedefs in classes more often than not. So if I'm not entirely sure and under pressure to decide quickly, I start by placing the typedef in the class, and refactor it out if I turn out to be wrong. For you, you can look at surrounding code and copy their decision, for now, if you're in a hurry

Title: Is nesting typedefs a good style?


问:
project with 2 types of interfaces performing different jobs, should they use the same BLL and DAL?
I am working on a project that has two interface (web and desktop), they are not performing the same tasks but they use the same BLL and DAL, the web part using 100% of the BLL and DAL, while the desktop only needs to know about 20% of the BLL and DAL.

Do you think it is a good idea to let the desktop use the same BLL and DAL as the web, which consequently will lead to distributing thos BLL and DAL with the desktop application? Or you think I'd better create new BLL and DAL projects just to serve the desktop app? But in this case I will fall in the trap of maintaining two copies of the same code!

答:
You haven't provided any specifics as to why you're concerned about distributing the extra code with your desktop app, but in general, keeping code duplication to a minimum should be a high priority.

My best guess is that you're concerned about the size of your desktop app when it includes the code that it doesn't use, but unless it pushes the size beyond 20MB or so to be downloaded over the internet, I wouldn't be too worried about it.

If you do have good reasons to believe that the size with unused code will be prohibitive, the first thing I would do is look into ways that I could include in the desktop package only those modules of the BLL and DAL that it needs. In Java I would try to break monolithic packages into smaller ones, and modify the build script to jar up only those packages that it uses.

Another option would be to make web service calls to your webapp from the desktop app, which can make sense in situations where you expect to eventually support many different apps, e.g. desktop, iOS, Android, etc, but it's not trivial undertaking.


答:
Some languages have a degree of metaprogramming that allow you to construct arbitrary classes that inherit from a base class on the fly.  Something along the lines in Ruby (just an example) of (and I don't claim I'm writing valid ruby code though if one wanted to it would give an idea of which way to look):

```<code># get lines of file, or hardcode... whatever
lines.each do |line|
    process line
    cls = Class.new(Object) do
        self.instance_variable_set(name,value)
    end
end
</code>```

You've got a config file sitting somewhere (in a database?) and load it in, and make all the classes on the fly.  Glance at enums in ruby if you want another thought of how to do it with it there.

Java doesn't have as rich a meta programming set available to it.  You can make anonymous classes, but they aren't exactly arbitrary anonymous classes... and not what you're really after either.

Lets start off with a class. Lets call it terminationReason.  Its abstract, and it has all of the associated business logic in it if it needs it.  It has a constructor and you've got your Factory.  Yes, this is the approach you didn't like - the Factory would indeed become rather monolithic with all of its various values.

Instead, lets make terminationReason abstract.  Then you've got the classes that implement it.  You've got latePayment extends terminationReason.  If there is nothing special in latePayment, it consists of a constructor that has the values set and thats it.  I don't see any glaring problems with this code structure.  It isn't that flexible, but if you don't need flexibility it has nice bits of the logic for a particular reason can be adjusted and you can have type safety (you must pass a latePayment to some other method).  I want to stress that this really isn't significantly better than using an enum. You've hard coded configuration in lots of small discrete classes instead of an enum.  It makes doing things like "show a list of drop down options" much more difficult.

What might be better though, is a combination of structured data files (json, xml or the like) and the factory.  Have the factory read the associated data and construct the objects as necessary.  This adds a degree of flexibility in the code - you can change what objects and parameters that are created without recompiling the application (note the 'Those possibilities need to be externalized of your system as they will probably change often' in the question).

There is a strong case of the use of instanceof to separate code functionality is a code smell. See avoiding instanceof in Java or Switch Statement code smell and Polymorphism or Instanceof In Conditionals.  And while you are right that inheritance is a good thing, using instanceof and associated conditionals to determine functionality is a bad thing.

If you are considering drools or similar systems, you might want to take a long look at it and consider it again.  Few applications reduce in scope as time goes on. It is also fairly safe to say that few maintain the same scope.  If you find yourself writing custom code that should have been done in drools, or reimplementing logic that off the shelf would have done much more easily... I don't know if drools is the right thing for you.  I do know that I've seen many projects where just one rule turns into something that balloons to huge sizes later on and a business rule management system early on could have saved hundreds of hours of custom code and debugging.

Title: How to deal with system "static" data in java

Body:
I was just wondering if there is some better way how to handle system "static" configuration data. Let say you have a system which offers several operation which are in code translated to operation code but you need to keep other related information to that operation like description, priority etc. Nasty way I have seen is public static final constants. Better way I was using before was create a class eg:

```<code>public abstract Codebook{
private int id;
private String description;
... getters setters
}
</code>```

Then for given cathegory - in this case OperationalCode:

```<code>public class OperationalCode extends Codebook{}
</code>```

Instance of this class were created with the data from BD. Now I cannot use DB so I thought I will create factories which will populate classes with given set of parameters. BUT all is hardcoded to factory class which I don't like.

Is there a better solution how to tackle this case as I believe I am not the first one solving that. Some handy framework or ...

I wasn't probably clear enough. I am fully aware of Properties capability in java but that doesn't match the criteria. Let me explain more:
When I say configuration I mean business configuration. You never know how many possible items you will get. For example in banking system you can cancel contract and you are forced to provide a reason for termination - predefined list which includes text, code in your system and translation to codes of third party systems where your system need to perform cancelation operation as well. Those possibilities need to be externalized of your system as they will probably change offten. Property files doesn't seems as a right choice and the opposite site - using Buisiness Rule Systems (e.g. Drools ) seems to me as overkill. Using enums with specified properties wouldn't fit quit well because time to time you need to be able to recognize that it is configuration and not just normal enum. That the reason for class inheritance - instanceof operator solve this.

Body:
Some languages have a degree of metaprogramming that allow you to construct arbitrary classes that inherit from a base class on the fly.  Something along the lines in Ruby (just an example) of (and I don't claim I'm writing valid ruby code though if one wanted to it would give an idea of which way to look):

# get lines of file, or hardcode... whatever
lines.each do |line|
    process line
    cls = Class.new(Object) do
        self.instance_variable_set(name,value)
    end
end

You've got a config file sitting somewhere (in a database?) and load it in, and make all the classes on the fly.  Glance at enums in ruby if you want another thought of how to do it with it there.

Java doesn't have as rich a meta programming set available to it.  You can make anonymous classes, but they aren't exactly arbitrary anonymous classes... and not what you're really after either.

Lets start off with a class. Lets call it terminationReason.  Its abstract, and it has all of the associated business logic in it if it needs it.  It has a constructor and you've got your Factory.  Yes, this is the approach you didn't like - the Factory would indeed become rather monolithic with all of its various values.

Instead, lets make terminationReason abstract.  Then you've got the classes that implement it.  You've got latePayment extends terminationReason.  If there is nothing special in latePayment, it consists of a constructor that has the values set and thats it.  I don't see any glaring problems with this code structure.  It isn't that flexible, but if you don't need flexibility it has nice bits of the logic for a particular reason can be adjusted and you can have type safety (you must pass a latePayment to some other method).  I want to stress that this really isn't significantly better than using an enum. You've hard coded configuration in lots of small discrete classes instead of an enum.  It makes doing things like "show a list of drop down options" much more difficult.

What might be better though, is a combination of structured data files (json, xml or the like) and the factory.  Have the factory read the associated data and construct the objects as necessary.  This adds a degree of flexibility in the code - you can change what objects and parameters that are created without recompiling the application (note the 'Those possibilities need to be externalized of your system as they will probably change often' in the question).

There is a strong case of the use of instanceof to separate code functionality is a code smell. See avoiding instanceof in Java or Switch Statement code smell and Polymorphism or Instanceof In Conditionals.  And while you are right that inheritance is a good thing, using instanceof and associated conditionals to determine functionality is a bad thing.

If you are considering drools or similar systems, you might want to take a long look at it and consider it again.  Few applications reduce in scope as time goes on. It is also fairly safe to say that few maintain the same scope.  If you find yourself writing custom code that should have been done in drools, or reimplementing logic that off the shelf would have done much more easily... I don't know if drools is the right thing for you.  I do know that I've seen many projects where just one rule turns into something that balloons to huge sizes later on and a business rule management system early on could have saved hundreds of hours of custom code and debugging.


答:
Designing good API is an art. Good API is appreciated even after time passes. In my opinion, there should be no general bias on the abstract-concrete line. Some parameters can be as concrete as days of the week, some require to be designed for extensibility (and it is quite stupid to make them concrete, eg, part of function names), yet another may go even further and in order to have elegant API one needs to provide callbacks or even domain specific language will help to fight complexity.

There are rarely new things happening under the Moon. Take a look at the prior art, especially established standards and formats (e.g., many things can be modelled after feeds, event descriptions were elaborated in ical/vcal). Make your API easily additive, where frequent and omnipresent entities are concrete and envisioned extensions are dictionaries. There are also some well-established patterns for dealing with specific situations. For example, handling HTTP request (and similar) may be modelled in the API with Request and Response objects.

Before designing API, brainstorm on aspects, including those, which will not be included, but you must be aware of. Examples of such are language, direction of writing, encoding, locale, timezone information and the like. Pay attention to places where multiples can appear: use list, not single value for them. For example, if you are desing API for videochat system, your API will be much more useful, if you assume N participants, not just two (even though your specs at the moment are such).

Sometimes, being abstract helps to reduce complexity drastically: even if you design a calculator for adding only 3+4, 2+2, and 7+6, it may be much simpler to implement X+Y (with technically feasible bounds on X and Y, and include ADD(X, Y) to your API instead of ADD_3_4(), ADD_2_2(), ...

All in all, choosing one way or another is just a technical detail. Your documentation should describe frequent use cases in a concrete manner.

Whatever you do on the data structure side, provide a field for an API version.

To summarize, API should minimize complexity when dealing with your software. TO appreciate the API, the level of exposed complexity should be adequate. Deciding on the form of the API depend a lot on the stability of the problem domain. Thus, there should be some estimation on which direction the software and it's API will grow, because this information may affect the equation for complexity. Also, API desing is there for people to understand. If there are any good traditions in the software technology area you are in, try not to deviate much from them, as it will help understanding. Take into account for whom you write. More advanced users will appreciate generality and flexibility, while those with less experience may be more comfortable with concretics. However, care for the majority of API users there, ie those in between beginners and experts.

On the literature side I may recommend "Beautiful Code" Leading Programmers Explain How They Think By Andy Oram, Greg Wilson, as I think beauty is about perceiving hidden optimality (and suitability for some purpose).

Title: API design: concrete vs. abstract approach - best practices?

Body:
When discussing APIs between systems (on the business level) there are often two different point of views in our team: some people prefer a more - lets say - generic abstract approach, other a straight forward "concrete" approach.

Example: the design of a simple "person search" API. the concrete version would be

```<code> searchPerson(String name, boolean soundEx,
              String firstName, boolean soundEx,
              String dateOfBirth)
</code>```

People in favour of the concrete version say:

the API is self-documenting

it is easy to understand

it is easy to validate (compiler or as a webservice: schema validation)

KISS

The other group of people in our team would say "That is just a list of search criteria"

```<code>searchPerson(List<SearchCriteria> criteria)
</code>```

with

```<code>SearchCritera {
  String parameter,
  String value,
  Map<String, String> options
}
</code>```

with possibly making "parameter" of some enumeration type.

Proponents say:

without changing the (declaration of) the API the implementation can change, e.g. adding more criteria or more options. Even without synchronizing such a change at deployment time.

documentation is necessary even with the concrete variant

schema validation is overrated, often you have to validate further, schema cannot handle all cases

we already have a similiar API with another system - reuse

The counter-argument is

lots of documentation about valid parameters and valid parameter combinations

more communication effort because it's more difficult to understand for other teams

Are there any best practices? Literature?


答:
I wouldn't say that an abstract API is necessarily more difficult to validate. If the criteria parameters are simple enough and have little dependencies between each other, it doesn't make much difference whether you pass the parameters separately or in an array. You still need to validate them all. But that depends on the design of the criteria parameters and the objects themselves.

If the API is complex enough, having concrete methods is not an option. At some point you'll probably end up with either methods with to much parameters or too much simple methods that won't cover all of the required use cases. As far as my personal experience in designing an consuming APIs, it's better to have more generic methods on the API level and implementing specific required wrappers on the application level.


问:
Should I put utility methods inside a class?
I have been working on a library which contains a large set of functions. For the sake of simplicity, I am going to use just one set as an example.

I am not sure which is the better way, in terms of ease of use and performance, whether I should put those methods provided as individual methods, prepended with the function category, or whether it is better to create a Class containing all the method as static methods.

For Example:

Individual methods: (p.s. this could also be writen without request_ in the function name and using Namespaces instead)

```<code>function request_method() { ... }
function request_url() { ... }
function request_useragent() { ... }
....
</code>```

Classed method:

```<code>class Request {
    public static function method() { ... }
    public static function url() { ... }
    public static function useragent() { ... }
    ...
}
</code>```

答:
In your case these methods are all meant for working accessing request data so they are not I wouldn't say they are just utility method. They are actually very related to each other and putting them inside a Request method is completely logical.

But when talking about truly utility methods, for instance, methods for working with arrays, putting them inside a generic static may not be the true OOP way but offers a lot of practical advantages. From making code navigation easier in the IDE to being able to use autoload and extending these classes depending on your application architecture.


问:
Issue with scrum adaptation by team
I have been playing with Scrum methodology since year and half. I am using VersionOne as scrum tool. I have tried to follow most of the scrum principles. Sometimes, I feel like there is an issue with transparency of the stories. As of now, the whole team can get an access to all stories defined for the project. This creates issues with different levels of developers like junior and senior level developer.

People's complains are about the work distribution or type of work they are assigned to. There is an issue of comparison among the developers. I don't know if I am following scrum properly or not.

In scrum, should we give access of the all stories to everyone? or only assigned person can view his/her story?

答: The scrum methodology states that all developers should be treated as equal when in fact they are not. Some of them are more capable of handling complex tasks then others and this is not personal attitude but professional assessment. The key to a successful scrum team is to offer developers the freedom to pick their own stories, but still being able to delegate specific tasks to certain developers, if necessary. But this process has to be transparent and obvious to everyone to avoid jealousy and misunderstandings.</p>

Title: Issue with scrum adaptation by team


答:
The change argument should be dismissed with YAGNI. Basically unless you actually have at least 3 different use-cases that use the generic API differently, chances are pretty low you design it so that it won't have to change when next use-case comes up (and when you have the use-cases, you obviously need the generic interface, period). So don't attempt and be ready for the change.

The change does not need to be synchronized for deployment in either case. When you generalize the interface later, you can always provide the more specific interface for backward compatibility. But in practice any deployment will have so many changes that you'll synchronize it anyway so you don't have to test the intermediate states. I wouldn't see that as argument either.

As for documentation, either solution may be easy to use and obvious. But it stands as important argument. Implement the interface so that it will be easy to use in your actual cases. Sometimes specific may be better ans sometimes generic may be.


答:
I keep up on Groklaw from time to time, patent wars (like it or not) influence how many of us do our jobs.

Beyond that, my news reader is populated with several dozen individual blogs that I've discovered over the years. Like some others who have answered, I really don't care for mash ups, I find them more distracting than useful and informative.

I still subscribe to (and participate in) several newsgroups, such as comp.lang.c, comp.unix.programmer and others.

I know me, and I know how much work I won't get done in the name of 'staying informed', so I do try to limit my subscriptions.


问:
Listener, logger, plotter - what threading arcitecture to choose for this?
I am constructing a program that does several things.

Listens to a port. Every second a string is received

When new data is received, it has to be logged. No errors or skipped entries are allowed

When data is received, a plot on the screen has to be updated. This is an expensive computation. Missing some updates is not critical.

Once a month, an archiving function shall be called, to backup the logs. This might take unknown amount of time.

I am new to threading and would like to ask for advice on the threading infrastructure. On one hand, it seems that I need at least 1 additional thread besides the main thread, for the port listener.

On the other hand, I am afraid that if I spawn too many a thread:

Sync problems may occur

The app may become resource-hungry

Here is some proposed code for the listener.
* The complexity of the code might rocket up

答:
This is the sort of problem in which node.js thrives.  I realize you're asking for a python library, but I'm just telling you that if you have the liberty to change programming language, you should probably do so in this case.

Node.js uses web socket technology, meaning every client connected to your web site isn't going to have to poll for new information every second, thus making it scale with remarkable efficiency.

How you use that information is entirely up to you, but there are many javascript libraries that will plot information from arrays of data or by repeated calls to add new data, meaning you could initially provide an array, then upon receiving new information, simply add it to your plot, which is likely a very efficient way of updating the plot without having to redraw everything (depending on what you're using).

If you use node.js, you can choose to use a NoSQL database like MongoDB.  That can be local to your server, but it can also be external, which will take care of your archiving problem.

If scalability is truly your concern, then I would highly recommend you consider switching to node.js for this.  It is built primarily for these types of web applications in mind.  If you aren't familiar with node.js, then I highly recommend you learn it anyway, even if you decide not to go this route.


答:
look up producer consumer problem for general solutions to the sync issue,

I think using a circular buffer that pops the oldest entry when it is full instead of blocking is your best bet

in psuedo code the port listener thread will be: (using an interface like javas ArrayBlockingQueue

```<code>while(alive){
     record = read(port) //only blocking operation in the loop
     logger.logRecord(record)
     while(!plotqueue.offer(record)){ //try to push to plotter thread
         plotqueue.poll() // discard oldest if full
     }
}
</code>```

then the plotter thread will be:

```<code>while(alive){
     record = plotqueue.take()//block until one is available

     plot(queue)
}
</code>```

Title: Listener, logger, plotter - what threading arcitecture to choose for this?

Body:
I am constructing a program that does several things.

Listens to a port. Every second a string is received

When new data is received, it has to be logged. No errors or skipped entries are allowed

When data is received, a plot on the screen has to be updated. This is an expensive computation. Missing some updates is not critical.

Once a month, an archiving function shall be called, to backup the logs. This might take unknown amount of time.

I am new to threading and would like to ask for advice on the threading infrastructure. On one hand, it seems that I need at least 1 additional thread besides the main thread, for the port listener.

On the other hand, I am afraid that if I spawn too many a thread:

Sync problems may occur

The app may become resource-hungry

Here is some proposed code for the listener.
* The complexity of the code might rocket up

Body:
look up producer consumer problem for general solutions to the sync issue,

I think using a circular buffer that pops the oldest entry when it is full instead of blocking is your best bet

in psuedo code the port listener thread will be: (using an interface like javas ArrayBlockingQueue

while(alive){
     record = read(port) //only blocking operation in the loop
     logger.logRecord(record)
     while(!plotqueue.offer(record)){ //try to push to plotter thread
         plotqueue.poll() // discard oldest if full
     }
}

then the plotter thread will be:

while(alive){
     record = plotqueue.take()//block until one is available

     plot(queue)
}


问:
Fields vs method arguments
I just started writing some new class and it occurred to me that I was adding a lot of method arguments that are not strictly needed. This is following a habit to avoid having state in classes that is specific to some method call, rather than being general configuration or dependencies of the class.

Doing so means that a lot of methods that could have no arguments end up with one, two or three.

I'd like to hear your opinions on what you think of this tradeoff, and how you go about deciding which approach to take in what situation?

Since code is often easier to understand than English when describing code, I created a little gist that has both variants in it: https://gist.github.com/JeroenDeDauw/6525656

答:
Since the only externally visible method of your example is updateTable, I think it is fine to use fields instead of method parameters.

If this is part of a more generic class (e.g. TableTools), I would move the helper methods that need the state into a hidden inner class.

Pseudo-code example:

```<code>class TableTools {
    ...
    public void updateTable(currentTable, newTable) {
        TableUpdater u = new TableUpdater(schemaModifier, currentTable, newTable);
        u.removeRemovedFields();
        u.addAddedFields();
     }

     private class TableUpdater { ... }
}
</code>```

That way, you avoid fields that are used by only one public method. In addition, the code is thread-safe in the sense that every call to updateTable uses its own copy of TableUpdater and, thus, of TableUpdater's instance variables.

Title: Fields vs method arguments

Body:
Since the only externally visible method of your example is updateTable, I think it is fine to use fields instead of method parameters.

If this is part of a more generic class (e.g. TableTools), I would move the helper methods that need the state into a hidden inner class.

Pseudo-code example:

class TableTools {
    ...
    public void updateTable(currentTable, newTable) {
        TableUpdater u = new TableUpdater(schemaModifier, currentTable, newTable);
        u.removeRemovedFields();
        u.addAddedFields();
     }

     private class TableUpdater { ... }
}

That way, you avoid fields that are used by only one public method. In addition, the code is thread-safe in the sense that every call to updateTable uses its own copy of TableUpdater and, thus, of TableUpdater's instance variables.


答:
Using fields co-opts the ability to have multithreading available for the methods that use those fields.

Using fields like that is only slightly better than using globals from a reusability and maintainability standpoint, the key point here is that complex setups need careful and up-to-date documentation about which methods use and/or clobber which fields; something you don't need to do when using arguments.

Title: Fields vs method arguments

Body:
I just started writing some new class and it occurred to me that I was adding a lot of method arguments that are not strictly needed. This is following a habit to avoid having state in classes that is specific to some method call, rather than being general configuration or dependencies of the class.

Doing so means that a lot of methods that could have no arguments end up with one, two or three.

I'd like to hear your opinions on what you think of this tradeoff, and how you go about deciding which approach to take in what situation?

Since code is often easier to understand than English when describing code, I created a little gist that has both variants in it: https://gist.github.com/JeroenDeDauw/6525656


答:
I would favour the abstract interface approach. To put a query to those kinds of (search) service is a common problem and will likely occur again. Furthermore you propably will find more service candidates which are suitable to reuse a more general interface. To be able to provide a coherent common interface for those services I would not enumerate the currently identified query parameters in the interface definition.

As it was pointed out previously - I like the opportunity to change or extend the implementation without modifing the interface. Adding another search criteria have not to be reflected in the service definition.

Although it is no question to design well-defined, concise and expresse interfaces you will always have to provide some documentation in addition. Adding the definition scope for valid search criteria is not such a burden.


问:
In Python, what is the proper testing structure for packages containing packages?
Which is the preferred test package structure for packages containing subpackages:

Tests in Subpackages?

```<code>a/
  __init__.py
  b.py
  c/
    __init__.py
    cc.py
    test/
      __init__.py
      test_cc.py
  d.py
  test/
    __init__.py
    test_b.py
    test_d.py
</code>```

This structure suggests that each subpackage is a cohesive unit that can be tested (and possibly later released) by itself.

Subpackages in Tests?

```<code>a/
  __init__.py
  b.py
  c/
    __init__.py
    cc.py
  d.py
  test/
    __init__.py
    test_b.py
    test_c/
      __init__.py
      test_cc.py
    test_d.py
</code>```

This structure does a better job of keeping the tests in one place, but makes it a little harder to run the tests for a particular subpackage.

Something else?

答:
I am probably misunderstanding the question. Nevertheless, here is a go. Please, guide me to the precise question of interest by the means of comments.

Why not place the test within the modules themselves?

```<code>def main():
    pass

if __name__ == "__main__":
    main()
</code>```

It is idiomatic.

It provides two different uses for every module - to be included and used by other code, or to be called directly, in which case test are run.

Is quite handy during development. When working on a module, one usually wants to see first how the local changes are affecting the module, not that 12731 out of 13000 tests passed.

Tests can generally be customized so that there is a test that invokes local functionality, mocking all children, and a different test to import the sub-modules usually used and do some tests that are closer to the real world use of the module. This is very handy when a sub-module is broken, but you need to work on the higher-in-the-hierarchy module.

Body:
I am probably misunderstanding the question. Nevertheless, here is a go. Please, guide me to the precise question of interest by the means of comments.

Why not place the test within the modules themselves?

def main():
    pass

if __name__ == "__main__":
    main()

It is idiomatic.

It provides two different uses for every module - to be included and used by other code, or to be called directly, in which case test are run.

Is quite handy during development. When working on a module, one usually wants to see first how the local changes are affecting the module, not that 12731 out of 13000 tests passed.

Tests can generally be customized so that there is a test that invokes local functionality, mocking all children, and a different test to import the sub-modules usually used and do some tests that are closer to the real world use of the module. This is very handy when a sub-module is broken, but you need to work on the higher-in-the-hierarchy module.


答: I mostly read Hacker News and Programming Reddit. There is some overlap, while the former leans more towards startups and business.</p>


问:
Distributing a proprietary application together with GPL software
First, there are many similar questions here, but I found none with direct answers about this specific scenario. If you find a duplicate, please be kind enough to link to the specific answer(s). Also, to avoid question being too broad, consider this specific scenario only.

Assume a proprietary Linux application, which links against LGPL libraries dynamically, and does not link against GPL libraries. It also executes GPL'ed binaries from the file system through standard OS APIs though, to perform some actions.

Then assume a customized mainstream Linux distribution, with visible trademarked logos etc removed.

Then assume a self-contained product, which includes hardware, let's say Raspberry Pi with a bootable SD card with this customized OS. Then it has the proprietary software, which ultimately needs to start when device is switched on.

How to distribute this combination legally?

More specifically, I see (at least) three separate concerns:

In general, how to distribute just the customized Linux distro legally? For example, are there tools, or which distros have tools, to download all used default source packages, ready to be included with distribution or archived locally?

I think it's sometimes thought, that if you distribute a derivative of a mainstream Linux distro, you do not need to distribute the sources of default packages yourself, or that you can just point to the distro source repositories if someone asks for them, but I'm not sure if this is legally valid way to fulfill GPL obligations.

How to legally include the proprietary software with the distribution? For example, is it ok to have the proprietary software already installed in the above mentioned SD? Is it ok to have it uninstalled on the same media, and prompt user for it's installation on first boot? Is it required to have it on separate media or downloaded from the net, and installed from that? What are the limits of "certainly OK" and "certainly not OK", is there any consensus or even legal precedent?

Is executing GPL programs with hard-coded command strings from a proprietary application OK? My understanding is, this is OK and does not create a derived work. But if this is an issue, would working around it be as simple as creating an LGPL-licensed wrapper? Or just having the commands in modifiable configuration file (a good idea anyway, regardless of licensing issues)?

Note: Except for the techincal aspects of first bullet point, I understand that answers here are not any kind of legal counsel, but answers need to be backed up somehow, this site is not for opinion polls.

答:
If I read GPL correctly, it is only permitted for internet downloads and provided you just took the binary as it was. Otherwise you should have a copy of the source somewhere. All distributions have archives of sources, but it includes all versions. You need to pick the versions corresponding to versions you distribute. Also you probably won't be distributing all packages, the distributions are huge these days.

It is all OK. E.g. Android devices come with GPL Linux and proprietarty applications preinstalled and nobody has any problem with it. They just have to be separate programs.

It is OK. They are still separate programs. For things that are not OK, LGPL wrapper won't help you, because it is only permitted as far as code under any other license is.


答:
In layman's words:

methods should have as few arguments as possible ( Martin's Clean Code )

one of the features of objects is than they can (and should) have a state

non-static methods that don't operate on the object's state, i.e. receive everything as parameters, are not cohesive

non-cohesive methods might as well be made static and grouped in an utility class

Again, in my humble opinion non-cohesive methods belong to an utility class and not to a class with a domain name.

Title: Fields vs method arguments


答:
In layman's words:

The abstract approach has the advantage of allowing to built concrete methods around it.

The other way around is not true


问:
How is dependency injection not just moving the complexity into a separate class?
I've been looking into using the Typhoon framework for dependency injection this week. I get that separating the construction of objects is beneficial for replacing arbitrary components with mocks during unit testing, and so far I have seen benefits from this alone.

But I cannot help but think that where before I had a humongous view controller class that had tens of header imports, I now have a humongous factory class that has tens of header imports. Am I supposed to avoid having a massive factory class?

答:
In layman's words:

Dependency injection moves complexity to where it does less harm.

EDIT for @gnat: DI is not just moving complexity to a separate class, it's moving it to where it causes the less harm.


答:
If you extend the SearchCriteria idea a little bit, it can give you flexibility such as creating AND, OR etc. criteria. If you need such functionality, this would be the better approach.

Otherwise, design it for usability. Make the API easy for the people which use it. If you have some basic functions which are needed often (like search for a person by it's name), provide them directly. If advanced users need advanced searches, they can still use the SearchCriteria.


问:
The Art of Computer Programming - To read or not to read?
There are lots of books about programming out there, and it seems Code Complete is pretty much at the top of most people's list of "must-read programming books", but what about The Art of Computer Programming by Donald Knuth?  I'm a busy person, between work and a young family I don't have a ton of free time, so I have to be picky about how I use it.

I'm wondering - has anybody here read 'TAOCP'?  If so, is it worth making time to read or would some other book or more on-the-side programming like pet projects or contributing to open source be a better use of my time in terms of professional development?

DISCLAIMER - For those of you who sport "Knuth is my homeboy" t-shirts, don't get me wrong - I want to read it, but I'm just wondering if it should be right at the top of my priority list or if something else should come first.

答: Knuth's seminal work is the most popular reference that programmers intend to read, or finish reading. Someday.


问:
How to find classes that use certain DB tables
Problem:

I'm asked to prepare a document where all our DB tables are listed and I'm supposed to list all Controllers that uses these DB tables for read and another list for Controllers that do write operations.

Ex:

```<code>     +------------------------------------------+------------+
     |            DB table                      | tbl_Orders |
     +------------------------------------------+------------+
     |Controllers that perform read operations  |    ??      |
     +------------------------------------------+------------+
     |Controllers that perform write operations |    ??      |
     +------------------------------------------+------------+
</code>```

We are trying to write some documentation for a legacy system built using Zend framework. The code is scattered everywhere. There is code in the Controllers, in the models and even in the views.

The application uses PROPEL as an ORM.

What makes this really difficult is that the Controller may not be directly calling the table, but it may be instantiating a model class that calls that table.

Is there an educated way to approach this crazy task?

Note:

Searching for the table name won't provide a solution because if a model uses that table I wouldn't know which Controller is using that model.

答:
I think you'll need a tiered search approach.

First round is the obvious one that you call out in your question.  Specifically, search for the table names within the code itself.

The second round is where it gets more difficult.  You'll need to know the names of the functions that you found from the first round of searching.  Then search for all of the areas where those functions are being called.

Combine the results of the second set of answers with the first set and you should be able to identify all of your areas of concern.


问:
Hiding query strings logically?
I feel uncomfortable when using query string parameters as:

http://xyz.com/default.aspx?carId=1129&country=uk&uniqueId=98745DVF4563VVf1259

I would rather use something that should not make sense to anyone who is trying to make some sense from the URL:

?a=1129&b=uk&c=98745DVF4563VVf1259

(after all this query sting info is for my use only)

Firstly is this a good thing to do? (I mean to hide logic of you query string)

If it is, then is there a way, that internally developers can use carId, country and uniqueId in code, but externally the url uses a, b and c respectively?

So if someone goes to

?a=1129&b=uk&c=98745DVF4563VVf1259

when I do Request.QueryString["carId"]

I should get 1129.

Can this be done?

答:
firstly is this a good thing to do? (i mean to hide logic of you query string)?

I don't think so. A malicious user can still modify the query string parameters at will, you just make it slightly more difficult for him, at the expense of added complexity to your system.

Title: Hiding query strings logically?


答:
I think, that the choosing should be according to the real situation, as you see it. If an item belongs to an instance, it should be seen as its field. If the item is external to the instance, it should be passed as a method parameter.

We should be guided in this case not by the effectivity (the difference is insignificant anyway), or (God save!) easiness of typing, but by the understandability and naturalness of the code.

Title: Fields vs method arguments


问:
Why would I ever use delegates if I'm not doing events?
I am trying to learn how to do events in C#, and according to the MSDN Events tutorial,

Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so before continuing

so now I'm trying to understand Delegates first, and failing horribly. What are they for? What problem are you trying to solve where you delegate something?

I THINK they're for passing methods into other methods but what is the point of that? Why not just have a method that does whatever you're doing in the first place?

答:
There are a ton of framework class library types with operations that take delegates as a parameter.

If you use the Task parallel Library, LINQ or Entity Framework, you will be passing in delegates as arguments.

A lot of the delegate signatures you would want to use are already defined (Action, Func, Predicate) and the syntax made simpler with lambda expressions.


答:
Passing functions to other functions is a very good way of generalizing code, especially when you have lots of nearly-duplicate code with only the logic in the middle differing.

My favorite (simple) example of this is making a Benchmark function, that accepts a delegate containing the code you wish to benchmark. I'll be using lambda syntax and Func/Action objects, because they're much more concise (and common) than seeing explicitly created delegates nowadays.

```<code>public void Benchmark(int times, Action func)
{
    var watch = new Stopwatch();
    double totalTime = 0.0;

    for (int i = 0; i < times; i++)
    {
        watch.Start();
        func(); // Execute our injected function
        watch.Stop();

        totalTime += watch.EllapsedTimeMilliseconds;
        watch.Reset();
    }

    double averageTime = totalTime / times;
    Console.WriteLine("{0}ms", averageTime);
}
</code>```

You can now pass in any block of code to that benchmark function (along with the number of times you want to run it) and get back the average execution time!

```<code>// Benchmark the amount of time it takes to ToList a range of 100,000 items
Benchmark(5, () =>
{
    var xs = Enumerable.Range(0, 100000).ToList();
});

// You can also pass in any void Function() by its handler
Benchmark(5, SomeExpensiveFunction);
</code>```

If you couldn't inject the code you wanted to benchmark into the middle of that function, you'd probably end up copying and pasting the logic around anywhere that you wanted to use it.

Linq makes extensive use of function passing, allowing you to have a whole host of really flexible operations on sets of data. Let's take the Where function as an example. It filter's out elements of a list that return "true" when passed a comparison function.

```<code>var xs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// This function compares each element, and returns true for those that are above 5
//   Result = { 6, 7, 8, 9, 10 }
var above5 = xs.Where((x) => x > 5);

// This function only returns true if an element is even
//   Result = { 2, 4, 6, 8, 10 }
var evens = xs.Where((x) => x % 2 == 0);
</code>```

The Where function itself very generalized. It simply loops over a collection, and yields a new collection containing only the values that match some predicate function. It's up to you to inject the code that tells it precisely what it's looking for.

Title: Why would I ever use delegates if I'm not doing events?

Body:
I am trying to learn how to do events in C#, and according to the MSDN Events tutorial,

Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so before continuing

so now I'm trying to understand Delegates first, and failing horribly. What are they for? What problem are you trying to solve where you delegate something?

I THINK they're for passing methods into other methods but what is the point of that? Why not just have a method that does whatever you're doing in the first place?

Body:
Passing functions to other functions is a very good way of generalizing code, especially when you have lots of nearly-duplicate code with only the logic in the middle differing.

My favorite (simple) example of this is making a Benchmark function, that accepts a delegate containing the code you wish to benchmark. I'll be using lambda syntax and Func/Action objects, because they're much more concise (and common) than seeing explicitly created delegates nowadays.

public void Benchmark(int times, Action func)
{
    var watch = new Stopwatch();
    double totalTime = 0.0;

    for (int i = 0; i < times; i++)
    {
        watch.Start();
        func(); // Execute our injected function
        watch.Stop();

        totalTime += watch.EllapsedTimeMilliseconds;
        watch.Reset();
    }

    double averageTime = totalTime / times;
    Console.WriteLine("{0}ms", averageTime);
}

You can now pass in any block of code to that benchmark function (along with the number of times you want to run it) and get back the average execution time!

// Benchmark the amount of time it takes to ToList a range of 100,000 items
Benchmark(5, () =>
{
    var xs = Enumerable.Range(0, 100000).ToList();
});

// You can also pass in any void Function() by its handler
Benchmark(5, SomeExpensiveFunction);

If you couldn't inject the code you wanted to benchmark into the middle of that function, you'd probably end up copying and pasting the logic around anywhere that you wanted to use it.

Linq makes extensive use of function passing, allowing you to have a whole host of really flexible operations on sets of data. Let's take the Where function as an example. It filter's out elements of a list that return "true" when passed a comparison function.

var xs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// This function compares each element, and returns true for those that are above 5
//   Result = { 6, 7, 8, 9, 10 }
var above5 = xs.Where((x) => x > 5);

// This function only returns true if an element is even
//   Result = { 2, 4, 6, 8, 10 }
var evens = xs.Where((x) => x % 2 == 0);

The Where function itself very generalized. It simply loops over a collection, and yields a new collection containing only the values that match some predicate function. It's up to you to inject the code that tells it precisely what it's looking for.


答:
Delegates act as a way to parametrize some kind of action. The function that is being passed a delegate doesn't care how the action is done, just that it is performed.

For example, look at the IComparer interface. It allows you to sort a list without relying on how the type in the list is "naturally" sorted. However, when you look at the interface, it only defines one method. It seams rather wasteful to define a whole class that only implements a single function.

Delegates solve this problem1. You won't need to define a class, just the method. It allows you to remove boilerplate code and focus on what you want to do. Lambdas take this a step forward so that the function definition can be in-lined instead of defined somewhere else in the class.

1 If you look at Sort(), an overloaded version exists that uses a delegate.


答:
Probably the simplest way to understand delegates and events is to look at GUI programming.  Let's take a very common case: you have a form with a button on it, and when the user clicks the button, you want a certain piece of code to execute.

The guy who wrote the button class has no idea what you want to do with it, obviously.  So he can't build your code for "what this button should do" into his class.  And even if he could, he really shouldn't, because then it stops being a "GUI button" and turns into a "Medivh's this-specific-use-case button" which is much less useful in the general case.

So instead, the guy who wrote the button class put in an Event, which is sort of a hook into the functionality of the object.  An Event is basically a piece of the code that's being executed where someone else can stick code in there.  So when someone clicks the button, it fires the OnClick event, and if you've attached anything to that event--such as a method (a delegate) that causes a new form to open--then that delegate will be executed at this point.

When you start thinking of methods as not just a procedure or function you can call, but an object you can pass to other code, it opens up all sorts of new possibilities.  Some of the other people here have already mentioned LINQ and the Task Parallel Library, which contain algorithms that define the basic idea of something, and then let you pass in a delegate to fill in the details.


答:
Suppose you have a complicated mathematical calculation to do, that involves performing rounding. Suppose that sometimes you want the rounding to be round to even (aka bankers' rounding), but other times you want round away from zero (aka 'round up [in absolute value]').

Now, you could write two methods:

```<code>double DoTheCalculationWithRoundToEven(double input1, double input2)
{
    var intermediate1 = Math.Pow(input1, input2);
    // more calculations...
    var intermediate5 = Math.Round(intermediate4, MidpointRounding.ToEven);
    // more calculations...
    var intermediate10 = Math.Abs(intermediate9);

    return intermediate10;
}

double DoTheCalculationWithRoundAwayFromZero(double input1, double input2)
{
    var intermediate1 = Math.Pow(input1, input2);
    // more calculations...
    var intermediate5 = Math.Round(intermediate4, MidpointRounding.AwayFromZero);
    // more calculations...
    var intermediate10 = Math.Abs(intermediate9);

    return intermediate10;
}
</code>```

with the two methods being the same except for that one line in the middle.

Now, this works, BUT you've got duplicated code and the very real possibility that some future maintainer (for example, a future you) will change one version of the intermediate2 to intermediate3 and forget about the other.

A delegate type and parameter can solve this duplication.

First declare the delegate type:

```<code>    public delegate double Rounder(double value);
</code>```

This says that a Rounder is a method that accepts a double and returns a double.

Next, have one calculation method that accepts a Rounder and uses it to round:

```<code>double DoTheCalculation(double input1, double input2, Rounder rounder)
{
    var intermediate1 = Math.Pow(input1, input2);
    // more calculations...
    var intermediate5 = rounder(intermediate4);
    // more calculations...
    var intermediate10 = Math.Abs(intermediate9);

    return intermediate10;
}
</code>```

Finally, when you want the calculation done, pass an appropriate Rounder. You can spell it all out with methods:

```<code>double RounderAwayFromZero(double value)
{
    return Math.Round(value, MidpointRounding.AwayFromZero);
}
// same for ToEven
</code>```

then call one of:

```<code>var result = DoTheCalculation(input1, input2, RounderAwayFromZero);
</code>```

or

```<code>var result = DoTheCalculation(input1, input2, RounderToEven);
</code>```

but C# allows you to do this all inline with lambdas:

```<code>var result = DoTheCalculation(input1, input2,
     value => Math.Round(value, MidpointRounding.AwayFromZero));
</code>```

where the lambda expression defines a method with the correct signature to be a Rounder.

Body:
Suppose you have a complicated mathematical calculation to do, that involves performing rounding. Suppose that sometimes you want the rounding to be round to even (aka bankers' rounding), but other times you want round away from zero (aka 'round up [in absolute value]').

Now, you could write two methods:

double DoTheCalculationWithRoundToEven(double input1, double input2)
{
    var intermediate1 = Math.Pow(input1, input2);
    // more calculations...
    var intermediate5 = Math.Round(intermediate4, MidpointRounding.ToEven);
    // more calculations...
    var intermediate10 = Math.Abs(intermediate9);

    return intermediate10;
}

double DoTheCalculationWithRoundAwayFromZero(double input1, double input2)
{
    var intermediate1 = Math.Pow(input1, input2);
    // more calculations...
    var intermediate5 = Math.Round(intermediate4, MidpointRounding.AwayFromZero);
    // more calculations...
    var intermediate10 = Math.Abs(intermediate9);

    return intermediate10;
}

with the two methods being the same except for that one line in the middle.

Now, this works, BUT you've got duplicated code and the very real possibility that some future maintainer (for example, a future you) will change one version of the intermediate2 to intermediate3 and forget about the other.

A delegate type and parameter can solve this duplication.

First declare the delegate type:

    public delegate double Rounder(double value);

This says that a Rounder is a method that accepts a double and returns a double.

Next, have one calculation method that accepts a Rounder and uses it to round:

double DoTheCalculation(double input1, double input2, Rounder rounder)
{
    var intermediate1 = Math.Pow(input1, input2);
    // more calculations...
    var intermediate5 = rounder(intermediate4);
    // more calculations...
    var intermediate10 = Math.Abs(intermediate9);

    return intermediate10;
}

Finally, when you want the calculation done, pass an appropriate Rounder. You can spell it all out with methods:

double RounderAwayFromZero(double value)
{
    return Math.Round(value, MidpointRounding.AwayFromZero);
}
// same for ToEven

then call one of:

var result = DoTheCalculation(input1, input2, RounderAwayFromZero);

or

var result = DoTheCalculation(input1, input2, RounderToEven);

but C# allows you to do this all inline with lambdas:

var result = DoTheCalculation(input1, input2,
     value => Math.Round(value, MidpointRounding.AwayFromZero));

where the lambda expression defines a method with the correct signature to be a Rounder.