答:
Yes, it is a verbose method for transferring data. Probably not as much as you might think.

Let's explore a little history that might help to explain why XML was a good choice and may still be the choice. When XML came into being, there weren't many good choices for transferring data between disparate databases from the same software company, let alone different companies. The two easiest methods at the time were to build CSV (csv has its own issues when transferring between systems) and targeted SQL (if the other db supported it).

XML brought about a technique where you could also define parent child relationships within the data storage/transfer medium without having to have another specialized table just to show the relationships. For some databases, this made adding new records very easy (look up multivalued databases, or for something modern, MongoDB). For others, it was just a simple matter of building cursors to loop through the child data.

As Robert Harvey mentioned in his answer, there were also networking issues to deal with (getting the data past the firewall, none of the intermediaries changing your data because they were on a UTF7 system instead of ASCII or UTF8), compressing the data as it moved across the wire. These were all part of the thought process behind building XML as a text based transport.

Lastly, string parsing is built into almost every language and database system in existence. So creating libraries to perform a predefined method of parsing XML became something that all of the language and database providers built into their software.

I can understand why you would prefer to use something that doesn't add as much overhead as XML (JSON for example). Realistically though, there are places where XML still beats several of the newer technologies.

One of the biggest places you can save when using XML as a transport technology is to use attributes in place of elements.

```<code><user id="1" firstname="Adam" lastname="Zuckerman" />
</code>```

While the equivalent JSON is:

```<code>{ user: { id: 1, firstname: "Adam", lastname: "Zuckerman"} }
</code>```

MichaelT brought up a good point in the comments: XML can be validated using several methods. This ensures that not only is the XML well formed (closing tags, legal characters, etc.), but that all of the tags are correct and allowed in the structure.

Another thought comes to mind about why to use XML over some other transport technology is a mostly forgotten ability to transform the XML directly into another output (e.g., XML to HTML using XSLT).

My apologies if any of the syntax above is incorrect. This was just off the top of my head.

Title: Moving data between databases with XML

Body:
I just read this quote online:

XML is a very useful technology for moving data between different databases or between databases and other programs. However, it is not itself a database.

Which is quoted from the book 'Effective XML: 50 Specific Ways to Improve Your XML'.

I don't understand what you would bother moving data between databases in an XML format. Databases usually contain a lot of data, so wouldn't it be verbose to transform it into an XML format?

Is there no way, to just serialize the database data into something less verbose, somehow, instead of bothering with conversions?

Body:
Yes, it is a verbose method for transferring data. Probably not as much as you might think.

Let's explore a little history that might help to explain why XML was a good choice and may still be the choice. When XML came into being, there weren't many good choices for transferring data between disparate databases from the same software company, let alone different companies. The two easiest methods at the time were to build CSV (csv has its own issues when transferring between systems) and targeted SQL (if the other db supported it).

XML brought about a technique where you could also define parent child relationships within the data storage/transfer medium without having to have another specialized table just to show the relationships. For some databases, this made adding new records very easy (look up multivalued databases, or for something modern, MongoDB). For others, it was just a simple matter of building cursors to loop through the child data.

As Robert Harvey mentioned in his answer, there were also networking issues to deal with (getting the data past the firewall, none of the intermediaries changing your data because they were on a UTF7 system instead of ASCII or UTF8), compressing the data as it moved across the wire. These were all part of the thought process behind building XML as a text based transport.

Lastly, string parsing is built into almost every language and database system in existence. So creating libraries to perform a predefined method of parsing XML became something that all of the language and database providers built into their software.

I can understand why you would prefer to use something that doesn't add as much overhead as XML (JSON for example). Realistically though, there are places where XML still beats several of the newer technologies.

One of the biggest places you can save when using XML as a transport technology is to use attributes in place of elements.

<user id="1" firstname="Adam" lastname="Zuckerman" />

While the equivalent JSON is:

{ user: { id: 1, firstname: "Adam", lastname: "Zuckerman"} }

MichaelT brought up a good point in the comments: XML can be validated using several methods. This ensures that not only is the XML well formed (closing tags, legal characters, etc.), but that all of the tags are correct and allowed in the structure.

Another thought comes to mind about why to use XML over some other transport technology is a mostly forgotten ability to transform the XML directly into another output (e.g., XML to HTML using XSLT).

My apologies if any of the syntax above is incorrect. This was just off the top of my head.


问:
From a TDD perspective, am I a bad person if I test against a live endpoint instead of a mock?
I follow TDD religiously.  My projects typically have 85% or better test coverage, with meaningful test cases.

I do a lot of work with HBase, and the main client interface, HTable, is a real pain to mock.  It takes me 3 or 4 times longer to write my unit tests than it does to write tests that use a live endpoint.

I know that, philosophically, tests that use mocks should take priority over tests that use a live endpoint.  But mocking HTable is a serious pain, and I'm not really sure it offers much of an advantage over testing against a live HBase instance.

Everyone on my team runs a single-node HBase instance on their workstation, and we have single-node HBase instances running on our Jenkins boxes, so it's not an issue of availability.  The live endpoint tests obviously take longer to run than the tests that use mocks, but we don't really care about that.

Right now, I write live endpoint tests AND mock-based tests for all my classes.  I'd love to ditch the mocks, but I don't want quality to decline as a result.

What do you all think?

答: How much longer does an endpoint-based test take to run than a mock-based test?  If it's significantly longer, then yes, it's worth the investment of your test-writing time to make the unit tests quicker - because you'll have to run them many, many times.  If it's not significantly longer, even though the endpoint-based tests are not "pure" unit tests, as long as they're doing a good job of testing the unit, there's no reason to be religious about it.</p>

ContentLicense: CC BY-SA 3.0


问:
Claim to get my source code used GPL code
I'm running public web site based on Drupal. Drupal is GPL 2 or 3 licence. Of course I wrote custom code which interacts with Drupal code (modules). Can anybody write me an e-mail and ask for the source code of that my custom code? In other words, have I to publish that my code somewhere?</p>

答:
If your code is sitting on a web server and you are only serving web pages (or web services containing application data), then you are not "distributing" under the terms of the GPL 2 or GPL 3.

The Affero GPL is the one that requires you to release your source code if you are distributing web pages using software under that license.


问:
Complete immutability and Object Oriented Programming
In most OOP languages, objects are generally mutable with a limited set of exceptions (like e.g. tuples and strings in python). In most functional languages, data is immutable.

Both mutable and immutable objects bring a whole list of advantages and disadvantages of their own.

There are languages that try to marry both concepts like e.g. scala where you have (explicitly declared) mutable and immutable data (please correct me if I am wrong, my knowledge of scala is more than limited).

My question is: Does complete (sic!) immutability -i.e. no object can mutate once it has been created- make any sense in an OOP context?

Are there designs or implementations of such a model?

Basically, are (complete) immutability and OOP opposites or orthogonal?

Motivation: In OOP you normally operate on data, changing (mutating) the underlying information, keeping references between those objects. E.g. an object of class Person with a member father referencing another Person object. If you change the name of the father, this is immediately visible to the child object with no need for update. Being immutable you would need to construct new objects for both father and child. But you would have a lot less kerfuffle with shared objects, multi-threading, GIL, etc.

答:
It's often useful to categorize objects as encapsulating values or entities, with the distinction being that if something is a value, code which holds a reference to it should never see its state change in any fashion which the code itself did not initiate.  By contrast, code which holds a reference to an entity may expect it to change in ways beyond the reference-holder's control.

While it's possible to use encapsulate value using objects of mutable or immutable types, an object can only behave as a value if at least one of the following conditions applies:

No reference to the object will ever be exposed to anything that might change the state encapsulated therein.

The holder of at least one of the references to the object knows all the uses to which any extant reference might get put.

Since all instances of immutable types automatically satisfy the first requirement, using them as values is easy.  Ensuring that either requirement is met when using mutable types is, by contrast, much more difficult.  Whereas references to immutable types can be freely passed around as a means of encapsulating the state encapsulated therein, passing around state stored in mutable types requires either constructing immutable wrapper objects, or else copying the state encapsulated by privately-held objects into other objects which are either supplied by or constructed for the recipient of the data.

Immutable types work very well for passing values, and are often at least somewhat usable for manipulating them.  They are not so good, however, at handling entities.  The closest thing one can have to an entity in a system with purely-immutable types is a function which, given the state of the system, will report that attributes of some part thereof, or produce a new system-state instance which is like a supplied one except for some particular part thereof which will be different in some selectable fashion.  Further, if the purpose of an entity is to interface some code to something that exists in the real world, it may be impossible for the entity to avoid exposing mutable state.

For example, if one receives some data over a TCP connection, one could produce a new "state of the world" object which includes that data in its buffer without affecting any references to the old "state of the world", but old copies of the world state which doesn't include the last batch of data will be defective and shouldn't be used since they will no longer match the state of the real-world TCP socket.


问:
How many programming languages is a programmer expected to be an expert at?
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.

答:
The main benefit of knowing multiple languages isn't in writing them directly. All other things being equal, I'd rather work with a C# programmer who also knows C, Python and Lisp (for example) than one who's only ever hacked in C#. It's not that knowing more languages is better, it's that being able to think about problems at multiple levels and from multiple perspectives is really helpful.

A programming language that doesn't change the way you think about programming is not worth knowing. -Alan Perlis

It's not about checking off one more language, or putting it on your resume; you just need to understand its underlying concepts well enough to program in it to get the full benefit. You won't get that from having a basic understanding of the syntax.

The more direct answer is "it depends".

At larger companies you're expected/allowed to specialize, but as I said above, I believe there's still benefit to understanding things beyond your one favorite tool.

At smaller places, you really can't get away with that. If nothing else, you typically need to maintain your app as well as build it, and you probably souldn't use the same languages for running through logs/data munging as you do to actually build your app. I guess you could technically get away with knowing a single language, but the benefit of having a well-performing, strongly-typed (or at least assertion-capable), probably compiled language do the heavy lifting, and a scripting language for maintenance/setup/scripting tasks seems pretty big. I wouldn't want to do without it, certainly.

ContentLicense: CC BY-SA 2.5


问:
xml serialization and deserialization complex situation
I'm considering passing xml back and forth for error messages but each error has different scenarios.

one situation at hand is passing diffed text comparison while others are as simple as passing a text message.

What kind of serialization/deserialization strategy could I use for such a scenario?

The main issue with a scenario like this is that the object is different from case to case and there needs to be a mechanism for identifying what type it is.

Serializing xml is pretty straight forward:

https://stackoverflow.com/questions/11283040/deserialize-xml-string-to-complex-type

https://stackoverflow.com/questions/1212742/xml-serialize-generic-list-of-serializable-objects

Three sloppy ideas pop into my mind from the start:

Make some super class that contains every possibility of contained
types.

Make some mechanism for reading the xml first to identify
what's in it.

Use option 2 and convert the inner body xml to an
object.

A more elegant approach would be to implement some kind of Action pattern, where, once the object was identified you could create the proper action to take with it.

Some ideas consist of the Action/Executor pattern or IoC:

http://msdn.microsoft.com/en-us/library/cc984279.aspx

http://msdn.microsoft.com/en-us/library/aa973811.aspx

Here is an example pattern idea that runs parrallel to what I'm thinking:

https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type

Not for data persistence but for error handling by the client:
The client decides how to handle the error once received based on the Action from a base library that takes place after deserialization.

my considered xml format would be something like this:

diff error:

```<code><errorMessage>
<header>The header is not correct</header>
<body>

<diffErrorArray>
<diffItem message="NoChange">
<customMessage>Correct</customMessage>
<source>HeaderColumn1</source>
<destination>HeaderColumn1</destination>
</diffItem>

<diffItem message="Replace">
<customMessage>Changed</customMessage>
<source>HeaderColumn1</source>
<destination>Header_Column_1</destination>
</diffItem>

<diffItem message="AddDestination">
<customMessage>Unknown</customMessage>
<source></source>
<destination>Header_Column_1</destination>
</diffItem>

<diffItem message="DeleteSource">
<customMessage>Missing</customMessage>
<source>HeaderColumn2</source>
<destination></destination>
</diffItem>

</diffErrorArray>

</body>
</errorMessage>
</code>```

string error:

```<code><errorMessage>
<header>Bad news</header>
<body>
<stringErrorMessage>Something really bad happened.</stringErrorMessage>
<body>
</errorMessage>
</code>```

答:
Xml deserialization - at least in case of C# (you're not referring to it directly, but your links indicate it as your language of choice) - has type recognition built in. Why not make use of that?

See https://stackoverflow.com/questions/775647/how-do-i-deserialize-xml-without-knowing-the-type-beforehand for more details.

1: Make some super class that contains every possibility of contained
  types.

As demonstrated in the question I linked to above, all it takes is creating some common base class for your errorMessage objects. Then you need to use XmlInclude.

So the super class would only have to "contain every possibility" in the sense of knowing about all its subtypes (but not their implementation details). It's still all nice and neat in terms of OOP.

Note that if you feel that .NET serialization is too limiting, there's always more sophisticated alternatives such as SharpSerializer - better suited for polymorphic scenarios.

Again, this is not a language-agnostic suggestion, but if you used another programming language, the advice still applies: you can look for a good open-source library.

2: Make some mechanism for reading the xml first to identify what's in it.

You could also use reflection and retrieve the type in run-time (as Kirtan suggested) by the name of the root element, or some attribute of the root element.

Another option would be to create, or generate, XSD schemas for your errorMessage items, then use these schemas to validate the incoming messages - thus establishing their "type identity".

One advantage of this admittedly a bit more troublesome solution is that if the incoming xml was somehow broken, xsd validation could tell you exactly where and why (eg. some unexpected, unrecognized element), you don't have to handle this "manually".

Then there's dynamic typing and yet another interesting approach:

https://stackoverflow.com/a/13705918/168719

A more elegant approach would be to implement some kind of Action
  pattern, where, once the object was identified you could create the
  proper action to take with it.

That's what takes place after you deserialize the message, doesn't it?

With regard to this, I don't think one could come up with suggestions superior to what you have already found in this thread: https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type

I hope this gives you some inspiration. If not, the principle I go by is: when it's awfully hard to solve a problem, most likely the problem itself is badly posed from the very beginning. So if you are stuck, maybe it's time to step back and redesign. I don't know broader context, so I have no way of knowing how possible it is in your case.


问:
What negative consequences can arise from this language design rule?
Clarification: the rule is meant to prevent accessing variables that are not declared yet.

Clarification 2: the rule mandates that the compiler follows calls to functions which are defined in the same scope as the call and happen before the actual definition (forward referencing)  - making the compiler much alike an interpreter.

I'm thinking about a fictional programming language that behaves similar to JavaScript when declaring functions: that is, when using the function keyword to create named functions, they get "hoisted" to the top of the scope and can be used anywhere where their name is visible.

For example, the following is legal:

```<code>f();
function f() { console.log("f called") };
</code>```

However, there is a potential problem: what if the function f uses a variable x, that is defined after the call, like here:

```<code>f();
var x = 1;
function f() { console.log(x); }
</code>```

In case of JavaScript, this is also legal, because variables are hoisted as well - the program gets essentially transformed into something like this:

```<code>var x;
function f() { console.log(x); }

f();
x = 1;
</code>```

And therefore just prints undefined.

In my fictional language, variables wouldn't get hoisted, which means that the example before would produce an error. The rule concerns how this error is generated:

Functions are visible for the entire block in which they are defined,
  but it is illegal to call a function that accesses a variable declared
  after the call.

This means that each time the compiler for this language would encounter a function call, it would have to check if the function is defined in the current scope, and if it is, check if it accesses variables in the current scope that are declared after the call.

The reason for this rule is that it makes no sense to access variables before they are declared. Hoisting the variables to the top of their scopes like JavaScript does is a hack that only leaves room for error! This is why I believe it must not be done, but such situations should be detected and treated as errors (because they are, you're referencing something that doesn't chronologically exist yet).

I'm looking for reasons why this is a bad rule, i.e. results in complications or inconsistencies.

The reason I suspect that the rule is a bad one is that it does not exist in the Scala language. Scala solved this problem with a much more general rule:

The scope of a name introduced by a declaration or definition is the
  whole statement sequence containing the binding. However, there is a
  restriction on forward references in blocks: In a statement sequence
  s[1]...s[n] making up a block, if a simple name in s[i] refers to
  an entity defined by s[j] where j >= i, then for all s[k]
  between and including s[i] and s[j],

s[k] cannot be a variable definition.

If s[k] is a value definition, it must be lazy.

UPDATE:

For the time being I have adopted Scala's approach.

This approach is a more general version of my rule: it will catch all illegal accesses, but also some that are not - this is a tradeoff that I'm willing to make since I think that my rule may be too complicated or even impossible to implement.

Here's the rephrased/explained rule from Scala:

Variables cannot be forward-referenced, but lazy values, functions defined with def (which are just syntax sugar for lambdas assigned to (lazy) values, might even remove them as Doval suggested), classes, and modules can.

The restriction is that between the reference and the declaration (inclusive), there must be no variable definitions, because they might be altered by the entity being referenced before they are introduced to the program.

答:
In a language which supports nested scope, what should be the effect of:

```<code>int foo()
{
  int x,y;
  x=1; y=0;
  while(y < 5)
  {
    x=4;
    y++;
    int x;
    x+=23;
  }
  return x;
}
</code>```

If, within the inner scope, the usage of x had followed the declaration at that scope level, the meaning of the code would have been clear.

If one abides by the principle that a perfect programming language should refuse to compile anything that wouldn't behave as the programmer intended, and if one considers it reasonably likely the programmer intended the x=4 to modify the outer-scope x, but also reasonably likely that the programmer intended it to modify the inner one, that would imply that any compiled behavior would be likely to behave in a fashion contrary to programmer intention.

I would suggest that in languages where the ordering of function definitions in the source file has no relationship to the sequence in which they will be called, it would make sense to regard the file as holding an unordered mapping of function signatures to function definitions, along with a bunch of other stuff.  As such, if ordering is irrelevant, the concept of "hoisting" is too.  For things where ordering is relevant, I would suggest that declaring an identifier within a scope should cause outer declarations of that identifier to become unusable at the start of the scope, but the new declaration should not be usable until after it occurs.  Additionally, I would define a syntax for undeclaring an outer-scope identifier within a scope, and warn if code fails to use it [a warning rather than an error, so as to make the definition of a new outer-scope identifier not be a breaking change].

For some purposes, it would be useful to have an explicit way of declaring "temporary" variables with the following semantics:

Temporary variable names may be reused within a scope, but may not appear in the same scope as an "ordinary" variable of the same name.

Use of a temporary variable name within a scope will render any temporary variable of the same name unusable in any outer scope.

Temporary variables must have their value assigned only at the point of declaration.

The basic idea here is to recognize the common situation where a "variable" will, within a certain area of the code, always hold a value that was written in one particular place.  Given a construct like:

```<code>int result;
...
result = someMethod();
if (result < 0) doSomething();
...
result = someOtherMethod();
if (result < 0) doSomething();
...
result = YetAnotherMethod();
if (result < 0) doSomething();
</code>```

if may not always be clear whether, at any particular spot in the code, the value of result will always have been set by the closest assignment statement preceding that spot in the code.  If instead the code had been something like:

```<code>temp var result = someMethod();
if (result < 0) doSomething();
...
temp var result = someOtherMethod();
if (result < 0) doSomething();
...
temp var result = YetAnotherMethod();
if (result < 0) doSomething();
</code>```

then finding any usage of result and finding a temp var declaration somewhere above it would imply that the temp var declaration had written the value to be used.

Body:
In a language which supports nested scope, what should be the effect of:

int foo()
{
  int x,y;
  x=1; y=0;
  while(y < 5)
  {
    x=4;
    y++;
    int x;
    x+=23;
  }
  return x;
}

If, within the inner scope, the usage of x had followed the declaration at that scope level, the meaning of the code would have been clear.

If one abides by the principle that a perfect programming language should refuse to compile anything that wouldn't behave as the programmer intended, and if one considers it reasonably likely the programmer intended the x=4 to modify the outer-scope x, but also reasonably likely that the programmer intended it to modify the inner one, that would imply that any compiled behavior would be likely to behave in a fashion contrary to programmer intention.

I would suggest that in languages where the ordering of function definitions in the source file has no relationship to the sequence in which they will be called, it would make sense to regard the file as holding an unordered mapping of function signatures to function definitions, along with a bunch of other stuff.  As such, if ordering is irrelevant, the concept of "hoisting" is too.  For things where ordering is relevant, I would suggest that declaring an identifier within a scope should cause outer declarations of that identifier to become unusable at the start of the scope, but the new declaration should not be usable until after it occurs.  Additionally, I would define a syntax for undeclaring an outer-scope identifier within a scope, and warn if code fails to use it [a warning rather than an error, so as to make the definition of a new outer-scope identifier not be a breaking change].

For some purposes, it would be useful to have an explicit way of declaring "temporary" variables with the following semantics:

Temporary variable names may be reused within a scope, but may not appear in the same scope as an "ordinary" variable of the same name.

Use of a temporary variable name within a scope will render any temporary variable of the same name unusable in any outer scope.

Temporary variables must have their value assigned only at the point of declaration.

The basic idea here is to recognize the common situation where a "variable" will, within a certain area of the code, always hold a value that was written in one particular place.  Given a construct like:

int result;
...
result = someMethod();
if (result < 0) doSomething();
...
result = someOtherMethod();
if (result < 0) doSomething();
...
result = YetAnotherMethod();
if (result < 0) doSomething();

if may not always be clear whether, at any particular spot in the code, the value of result will always have been set by the closest assignment statement preceding that spot in the code.  If instead the code had been something like:

temp var result = someMethod();
if (result < 0) doSomething();
...
temp var result = someOtherMethod();
if (result < 0) doSomething();
...
temp var result = YetAnotherMethod();
if (result < 0) doSomething();

then finding any usage of result and finding a temp var declaration somewhere above it would imply that the temp var declaration had written the value to be used.


问:
Processing csv files (alternative to business logic in DB)
We are working on a fulfillment system for an online book store. Everyday we receive tens of CSV files (about 90 files) with data about purchased orders.

Example:

```<code>OrderId    |    BookTitle    |    Quantity    |    Price    |    BuyerName    |    ...
1          |The hunger games |        1       |     10      |    John Doe     |    ...
1          | The Exorcist    |        2       |     25      |    John Doe     |    ...
2          |   Superman      |        1       |     5.5     |    Jane Nose    |    ...
</code>```

What we currently do:

The data need to be translated to our domain to Order entity, OrderItem entity,...etc. We load the file into dummy tables then use very complex queries to populate the Orders table and OrderItems table.

Problem:

 All the business logic is in the database (in the queries) so unit
   testing them is a nightmare. In addition we were requested to change the database we are using (not exactly, but something terrifyingly similar)

What we tried:

We are moving to a DDD approach where the domain model is the core of the application that holds all the logic and validation.

We tried to parse the file line by line and create the respective entities and validate them accordingly then save them to the database.

This resulted in thousands of calls to the database and sometimes the server runs out of memory coz of the thousands of records (around 90 thousand record/file) in a single file.

I know this domain is dead old and someone must have found a better way to handle such task. How do you process such huge files in your domain without suffering from performance?

UPDATE

We are using a MySql database with PHP and Apache.

The CSV file is loaded into a dummy table using something similar to this:

load data local infile 'orders.csv' into table dummyOrders fields terminated by ','
  enclosed by '"'
  lines terminated by '\n'
    (orderId, bookkTitle,Quantity, Price, BuyerName,...)
```

答:
You were doing it right - load the file into a dummy table (preferably on a staging DB), then manipulate the data with stored procedures (which are easy to test - they're little more than a single function, and you can put test data in the tables and run your sprocs using that data in a transaction that can be rolled back so they can be very isolatable regardless of what data exists in there).

Once you have your data in a good state, you migrate it to the production DB. That one will not need to have all the loading SQL in it, so can be simpler to manage.

So basically, split your operations into 2, staging and production. I've used this approach with millions of records and very good performance (though with SqlServer, not MySQL).


问:
How should we handle extra cosmetic features in Scrum sprints?
I was reading the Scrum documents and it says that the tasks in Sprint should be "potentially shippable".

I am confused by what this means. Suppose in Sprint 1 the goal was, "user registration form".

How much detail do I need to add for something to be ready to ship? For example:

I can show the simple form with fields without any fancy styling and mark them as done

I can just do client side validation as mark as done but server side is also the option or both

I can also add some jQuery fancy tool tips, hover overs, captcha, colors, labels for the form

Then there is whole lot of styling about how to show error messages on screen

I can do endlessly on one topic. So how do we divide that and when I can think of that as shipping ready.

Or do I need to write each smallest possible thing like showing errors, popup or light box text as subtasks and put them as sprint. This would lead to 1000s of tasks for whole project.

I mean then again if some work for Internet Explorer and some for Firefox then again do I need to divide those as tasks as well. Time has to be spent on them and when manager asks me what you did in that time, I won't have any tasks to tell but in reality they all are part of User registration

答:
"Potentially shippable" means shipp-able not necessarily something that you ship. For example:

A web registration form that looks terrible and has no validation on the fields, may be ok for some situations, like a school project, but in a multimillion dollar business, would damage the brand to show to end users. The code might be shippable without being something you would want to ship or that marketing or legal would let you ship.

It is something that the programmers (and other people that are in the process at this point e.g. designers) would be happy to release as it is right now, even if, for some reason, it would never actually be released like that (e.g. it needs to be translated into other languages before it can be shipped to anyone - Canada has strict rules about the Government buying software that gives equal consideration to French as well as English).

This is a quality check point, you look everyone in the eye and ask if they would be happy to ship it as it is right now, with no extra work, no checking to see if they did that one last thing. I have hear this called the aeroplane engineer check point. You look a engineer in the eye and ask them if they are willing to accompany you on the test flight.

The idea is to be as Agile as possible. The quicker you can get something out to real users; whether that is beta copies of the code to select individuals or A/B testing on your website, the better. If you show users code that is too rough, rough as defined by their expectations for your product, then they will give you useless feedback. They will talk about things that you are not looking for information on like: they don't like that the button is yellow or the text box doesn't line up with the labels. If it IS good enough then you can get useful feedback. The quicker you get this feedback the better! You can validate product/market fit, and assumptions you have made about the feature you have tried to build.

Shipping the feature is the least important part of this. Moving the development team along and finishing User Stories is the important thing. Getting to the point where you can claim something is done is a great motivator.


答:
philosophically, tests that use mocks should take priority over tests
  that use a live endpoint

I think at the very least, that's a point of current ongoing controversy amongst TDD proponents.

My personal view goes beyond that to say that a mock-based test is mostly a way of representing a form of interface contract; ideally it breaks (i.e fails) if and only if you change the interface. And as such, in a reasonably strongly typed languages like Java, and when using an explicitly-defined interface, it is almost entirely superfluous: the compiler will already have told you if you have changed the interface.

The main exception is when you are using a very generic interface, perhaps based on annotations or reflection, that the compiler isn't able to usefully police automatically. Even then you should check to see if there is a way of doing validation programatically (e.q. a SQL syntax checking library) rather than by hand using mocks.

It is that latter case you are doing when you test with a 'live' local database; the htable implementation kicks in and applies much more comprehensive validation of the interfacve contract than you would ever think to write out by hand.

Unfortunately, a much more common use of mock-based testing is is the test that:

passes for whatever the code was at the time the test was written

provides no guarantees about any properties of the code other than that it exists and kind of runs

fails any time you change that code

Such tests should of course be deleted on sight.

Title: From a TDD perspective, am I a bad person if I test against a live endpoint instead of a mock?

Body:
I follow TDD religiously.  My projects typically have 85% or better test coverage, with meaningful test cases.

I do a lot of work with HBase, and the main client interface, HTable, is a real pain to mock.  It takes me 3 or 4 times longer to write my unit tests than it does to write tests that use a live endpoint.

I know that, philosophically, tests that use mocks should take priority over tests that use a live endpoint.  But mocking HTable is a serious pain, and I'm not really sure it offers much of an advantage over testing against a live HBase instance.

Everyone on my team runs a single-node HBase instance on their workstation, and we have single-node HBase instances running on our Jenkins boxes, so it's not an issue of availability.  The live endpoint tests obviously take longer to run than the tests that use mocks, but we don't really care about that.

Right now, I write live endpoint tests AND mock-based tests for all my classes.  I'd love to ditch the mocks, but I don't want quality to decline as a result.

What do you all think?


答:
GPL restricts distribution of source code. Your Drupal code is server side, it lives on your server and no client can see it. It's not really been distributed. So, you don't have to release your code if you don't want to.

As stated in the other answer, the Affero GPL is the GPL variant that requires you to release (which would be the same as distribute) the code you're using to publish your web pages (see this question).

Do note, however, that this applies to server side code. You should be careful with Javascript, since that code actually makes it to the client's machines.

Title: Claim to get my source code used GPL code

Body: I'm running public web site based on Drupal. Drupal is GPL 2 or 3 licence. Of course I wrote custom code which interacts with Drupal code (modules). Can anybody write me an e-mail and ask for the source code of that my custom code? In other words, have I to publish that my code somewhere?</p>


问:
How important is it to clean up someone else's code when faced with a tight deadline?
(I'm talking about HTML / CSS code (not programming languages) but I think we also face the same issue as with programmers.)

I am the senior front-end designer in a team and I often have to re-work my juniors' output in tight deadlines.

I am faced with 2 problems:

Their coding style is a bit of a mess.

The aesthetics are not good.

Their coding style, I find, is a mixed bag with no proper convention / standard. I am torn between cleaning up the code or just dealing with their code (even copying how they do things).

I do find it frustrating to follow their coding style as I feel I might learn bad habits. But then, that is the fastest way of meeting the deadline.

For those with much more experience, which is more effective? Should I save the clean-up for later? Or clean-up along the way as I make the changes?

(I don't want to sound arrogant though but such is the reality. It will take them more years to write better code. I know, I wrote messy code when I was starting.)

答:
As so many have said before, whatever you throw in the air will always come back down. I believe in strong uniformity across a code base. Of course some things really do not matter that much. Naming conventions on local variables within a procedure for example. However for anything structural, it should be fixed right away, before the final merge into the main trunk. It may only be slightly shoddy when you look at the individual procedure or class, but if everyone commits "slightly ugly" code, it really fast becomes really ugly as a whole.

Ugly code that works often works fine 90% of the time but falls apart at the edges. Making sure it doesn't is usually simple enough by following only a few simple rules. First, it should be mandatory for every programmer to define and document exact constraints for every procedure or functional block they produce.

Second, for every procedure there should be a test against those constraints. This should be a simple unit test the programmer can (and has to) run locally against his procedure before committing. Obviously this is easier to manage with a proper testing suite, but even without a test should be written, and possibly committed in a partial class that can be excluded from the build.

Thirdly, a set standardized development environments with pre-configured tools is invaluable. A TS server is superb for this. Everyone has the same exact tools (and versions), the same configurations, and the same updates. Install a refactoring tool like CodeRush or Resharper, preconfigured to your standards, and instruct you programmers that you will reject any commits that still have warnings. Now you can use your team's code review time to actually improve on your rule set from their feedback, and your team happily correct themselves without you having to constantly clean up afterwards. It is also much easier for a programmer to take code criticism from a properly configured tool than from a colleague or boss, where the standards may seem arbitrarily defined or are not properly understood. If the IDE tells you that your code is shoddy, no one will argue with it and it will be corrected. You will find that code quality will rise dramatically, and the team as a whole will spend MUCH less time refactoring and cleaning up after a few weeks. Programmers will also get used to the rules and stop writing crap code.

Lastly, the simple fix here is simply to give the programmers an incentive to improve. Programmers are by definition competitive. Everyone wants to have the nicest or fastest code. A good way to motivate everyone, improve on productivity, and root out the incompetent is to calculate a weekly weighted score board for everyone, taking off points for rejected commits and broken deadlines for example. Show the top N at the weekly team meeting, maybe even pay lunch to whoever is first in the month's averages.

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
Which features of shell scripting are relevant for PHP/Python development?
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?

答:
Do any of the following bother you?

You can't/shouldn't put Linux on your resume.

You don't qualify to work for a purely Linux shop.

Your current job demands and level of interest in pursing Linux via self-study are non-existent, so your situation concerning Linux won't change.

Non-Windows developers will mock you (Maybe not to your face.).

There are tons of job opportunities and career paths you can still pursue. I'm not saying any of these 'should' bother you. Just be honest with yourself and keep an eye on the industry in general and Linux in particular to see if your paths may cross. No doubt you could figure it out when the time comes. Who knows, a Linux project may come your way tomorrow.


答:
The 'fictional consequences' vs. the 'fictional benefits' means you are looking for the downsides of such a rule if you were designing a language.

The biggest downside i see is that anytime you don't make your language do something "useful" (generating an error falls under this class), you weaken the power of the language.  You are missing an opportunity to do anything useful with it.

You could make both of the defined in the same scope as you say javascript does: the benefit being that something has to come first -- the vars, or the functions -- if your want your functions to be able
to make use of the variables in the lexical scope of its definition, then it makes perfect sense to treat those variables as though they'd been declared before "f"'s first call.

That's useful for having local functions

```<code>func bigfunc() {...
  prologue... setup .. parameter checking...
</code>```

Now:

```<code>  for loop over the sanitized params (p1, p2, p3...) {

    func a_case () {...will need access to prologue and setup vars}

    func b_case () {... ditto....}

    ....
    func z_case() {}
</code>```

Look for input & lowercase it... then take first letter
and prepend it to '_case', and call that function for further  processing.

```<code>  endloop
} #end func
</code>```

So the functions in this case are helper functions that "want" or "need" access to the setup information created by bigfunc, but have no reason to be seen outside of bigfunc's scope.

So that's one possible feature you miss out on -- the ability to have nested functions where the inner ones are only callable by code in 'bigfunc').

Another option would have each invocation of bigfunc gets it's own
private copy of the value of the var when it is defined.

I.e. suppose bigfunc is a "function factory", that returns anonymous
bindings to that use a "specific" value of the var 'x', when the function is invoked.

So we have...

```<code>func bigproducerfunc(parameters: object_instance) {

  var object_instance;  #maybe a filename?

  // nested functions....

  function size(...return size of object instance...)

  function last_mod{,owner,destroy...} {
    // do operation on value of 'x' that was passed in
    // 'object_instance' when the function was initially called.
  }

   function check_mod_time {... checks last modification time
       on the var it was called with)
   }

    var myhash funcs_by_name = (\add(), \size, \last_mod()...);

    return refto(myhash).
}
</code>```

Now a program can pass in the name of a file that it wants to operate on.  The program doesn't need to know OS differences -- those can
be handled in each accessor func.  To access them:

```<code>var hashref = bigproducerfunc("/etc/passwd")

var href2   = bigproducerfunc("/another pathname/")....
</code>```

"$hashref->size" will use the value that was passed in when the reference list to the function was created and returned -- for each
time you call 'bigproducerfunc', it can create a list of functions that will operate on that 1 object and only it (no chance at misspellings etc...).

```<code>printf("Working name %s size = %s", $hashref->size);
</code>```

In this case, you can use that setup for creating a closed
'environment' function that will only work on the file you
passed in at creation.

For each file you want to work with, 'bigfunc' is called with a file arg, and hands back a pointer to a set of functions that will operate only on the filename they were created with.  It is considered
a "closed system" w/r/t the initial data.

This is sometimes called a 'closure' -- a function or set of functions that operate on closed data that is given to a 'function factory' or 'method factory' (bigfunc in our example), that packs up the data with the functions so they later can be used without respecifying the original data each time as well as ensuring what data the functions work with).

===============================================

Those are 2 types of different features you would be giving up by turning it into a 'dead-semantic' or 'dead-syntax' case that is flagged as an "error" rather than doing something useful with it....the above are two common examples of doing something with this use case, I'm sure there are others that can be created...

Dead-semantics and dead-syntax are "dead-space" in a language.

Take "perl" for example.   Perl created a dead spot that would be
harmless to fix, but likely won't be due to language ossification.

The syntax   "string" x   (e.g. "hi " x 5), will create
some number of repetitions of that string concatenated together.

Suppose you wanted to do that some multiple of 5 times, so you pass
in a multiplier:

```<code>"string" x 3*$x;  # error
</code>```

This yields an error in perl because 'x' is the same precedence as '*',
thus you can never use this without forcing it to be more cluttered
by adding parenthesis:

```<code>"string" x (3*$x);  #ok
</code>```

Now there is no reason to require that -- in the operator precedence table, x is at the same precedence as mult+divide, but it really shouldn't be considered the same because it is less flexible (it isn't associative and can't be mixed with mult+divide).

Since strings generally don't combine with numbers, creating a
precedence for 'x' (repetitions op) lower than math operators, would
make sense.  In the same way, the string concatenation feature should be lower than "addition + subtraction", so, while this works:

```<code>> perl -MP -we'use strict;
my $a="\nblah" . 4*5;   #concatenate 'blah w/result of 4*5'
P "%s", $a;'

blah20
</code>```

This:

```<code>> perl -MP -we'use strict;
my $a="\nblah" . 4+5;   #try to concat blah w/result of 4+5..(fail)
P "%s", $a;'

Argument "blah4" isn't numeric in addition (+) at -e line 2.
5
</code>```

Does not.

In both cases, dead semantics were designed into the language.

Not ideal for good use of language semantics.  It unnecessarily creates errors where perfectly good meaning can be unambiguously derived.

Hope this gives you some insight into what makes for good language design.  (I must note, that knowing what works and doesn't is always easier to see in hindsight ;-)).

Title: What negative consequences can arise from this language design rule?

Body:
Clarification: the rule is meant to prevent accessing variables that are not declared yet.

Clarification 2: the rule mandates that the compiler follows calls to functions which are defined in the same scope as the call and happen before the actual definition (forward referencing)  - making the compiler much alike an interpreter.

I'm thinking about a fictional programming language that behaves similar to JavaScript when declaring functions: that is, when using the function keyword to create named functions, they get "hoisted" to the top of the scope and can be used anywhere where their name is visible.

For example, the following is legal:

```<code>f();
function f() { console.log("f called") };
</code>```

However, there is a potential problem: what if the function f uses a variable x, that is defined after the call, like here:

```<code>f();
var x = 1;
function f() { console.log(x); }
</code>```

In case of JavaScript, this is also legal, because variables are hoisted as well - the program gets essentially transformed into something like this:

```<code>var x;
function f() { console.log(x); }

f();
x = 1;
</code>```

And therefore just prints undefined.

In my fictional language, variables wouldn't get hoisted, which means that the example before would produce an error. The rule concerns how this error is generated:

Functions are visible for the entire block in which they are defined,
  but it is illegal to call a function that accesses a variable declared
  after the call.

This means that each time the compiler for this language would encounter a function call, it would have to check if the function is defined in the current scope, and if it is, check if it accesses variables in the current scope that are declared after the call.

The reason for this rule is that it makes no sense to access variables before they are declared. Hoisting the variables to the top of their scopes like JavaScript does is a hack that only leaves room for error! This is why I believe it must not be done, but such situations should be detected and treated as errors (because they are, you're referencing something that doesn't chronologically exist yet).

I'm looking for reasons why this is a bad rule, i.e. results in complications or inconsistencies.

The reason I suspect that the rule is a bad one is that it does not exist in the Scala language. Scala solved this problem with a much more general rule:

The scope of a name introduced by a declaration or definition is the
  whole statement sequence containing the binding. However, there is a
  restriction on forward references in blocks: In a statement sequence
  s[1]...s[n] making up a block, if a simple name in s[i] refers to
  an entity defined by s[j] where j >= i, then for all s[k]
  between and including s[i] and s[j],

s[k] cannot be a variable definition.

If s[k] is a value definition, it must be lazy.

UPDATE:

For the time being I have adopted Scala's approach.

This approach is a more general version of my rule: it will catch all illegal accesses, but also some that are not - this is a tradeoff that I'm willing to make since I think that my rule may be too complicated or even impossible to implement.

Here's the rephrased/explained rule from Scala:

Variables cannot be forward-referenced, but lazy values, functions defined with def (which are just syntax sugar for lambdas assigned to (lazy) values, might even remove them as Doval suggested), classes, and modules can.

The restriction is that between the reference and the declaration (inclusive), there must be no variable definitions, because they might be altered by the entity being referenced before they are introduced to the program.

Body:
The 'fictional consequences' vs. the 'fictional benefits' means you are looking for the downsides of such a rule if you were designing a language.

The biggest downside i see is that anytime you don't make your language do something "useful" (generating an error falls under this class), you weaken the power of the language.  You are missing an opportunity to do anything useful with it.

You could make both of the defined in the same scope as you say javascript does: the benefit being that something has to come first -- the vars, or the functions -- if your want your functions to be able
to make use of the variables in the lexical scope of its definition, then it makes perfect sense to treat those variables as though they'd been declared before "f"'s first call.

That's useful for having local functions

func bigfunc() {...
  prologue... setup .. parameter checking...

Now:

  for loop over the sanitized params (p1, p2, p3...) {

    func a_case () {...will need access to prologue and setup vars}

    func b_case () {... ditto....}

    ....
    func z_case() {}

Look for input & lowercase it... then take first letter
and prepend it to '_case', and call that function for further  processing.

  endloop
} #end func

So the functions in this case are helper functions that "want" or "need" access to the setup information created by bigfunc, but have no reason to be seen outside of bigfunc's scope.

So that's one possible feature you miss out on -- the ability to have nested functions where the inner ones are only callable by code in 'bigfunc').

Another option would have each invocation of bigfunc gets it's own
private copy of the value of the var when it is defined.

I.e. suppose bigfunc is a "function factory", that returns anonymous
bindings to that use a "specific" value of the var 'x', when the function is invoked.

So we have...

func bigproducerfunc(parameters: object_instance) {

  var object_instance;  #maybe a filename?

  // nested functions....

  function size(...return size of object instance...)

  function last_mod{,owner,destroy...} {
    // do operation on value of 'x' that was passed in
    // 'object_instance' when the function was initially called.
  }

   function check_mod_time {... checks last modification time
       on the var it was called with)
   }

    var myhash funcs_by_name = (\add(), \size, \last_mod()...);

    return refto(myhash).
}

Now a program can pass in the name of a file that it wants to operate on.  The program doesn't need to know OS differences -- those can
be handled in each accessor func.  To access them:

var hashref = bigproducerfunc("/etc/passwd")

var href2   = bigproducerfunc("/another pathname/")....

"$hashref->size" will use the value that was passed in when the reference list to the function was created and returned -- for each
time you call 'bigproducerfunc', it can create a list of functions that will operate on that 1 object and only it (no chance at misspellings etc...).

printf("Working name %s size = %s", $hashref->size);

In this case, you can use that setup for creating a closed
'environment' function that will only work on the file you
passed in at creation.

For each file you want to work with, 'bigfunc' is called with a file arg, and hands back a pointer to a set of functions that will operate only on the filename they were created with.  It is considered
a "closed system" w/r/t the initial data.

This is sometimes called a 'closure' -- a function or set of functions that operate on closed data that is given to a 'function factory' or 'method factory' (bigfunc in our example), that packs up the data with the functions so they later can be used without respecifying the original data each time as well as ensuring what data the functions work with).

===============================================

Those are 2 types of different features you would be giving up by turning it into a 'dead-semantic' or 'dead-syntax' case that is flagged as an "error" rather than doing something useful with it....the above are two common examples of doing something with this use case, I'm sure there are others that can be created...

Dead-semantics and dead-syntax are "dead-space" in a language.

Take "perl" for example.   Perl created a dead spot that would be
harmless to fix, but likely won't be due to language ossification.

The syntax   "string" x   (e.g. "hi " x 5), will create
some number of repetitions of that string concatenated together.

Suppose you wanted to do that some multiple of 5 times, so you pass
in a multiplier:

"string" x 3*$x;  # error

This yields an error in perl because 'x' is the same precedence as '*',
thus you can never use this without forcing it to be more cluttered
by adding parenthesis:

"string" x (3*$x);  #ok

Now there is no reason to require that -- in the operator precedence table, x is at the same precedence as mult+divide, but it really shouldn't be considered the same because it is less flexible (it isn't associative and can't be mixed with mult+divide).

Since strings generally don't combine with numbers, creating a
precedence for 'x' (repetitions op) lower than math operators, would
make sense.  In the same way, the string concatenation feature should be lower than "addition + subtraction", so, while this works:

> perl -MP -we'use strict;
my $a="\nblah" . 4*5;   #concatenate 'blah w/result of 4*5'
P "%s", $a;'

blah20

This:

> perl -MP -we'use strict;
my $a="\nblah" . 4+5;   #try to concat blah w/result of 4+5..(fail)
P "%s", $a;'

Argument "blah4" isn't numeric in addition (+) at -e line 2.
5

Does not.

In both cases, dead semantics were designed into the language.

Not ideal for good use of language semantics.  It unnecessarily creates errors where perfectly good meaning can be unambiguously derived.

Hope this gives you some insight into what makes for good language design.  (I must note, that knowing what works and doesn't is always easier to see in hindsight ;-)).


问:
Thoughts and Best Practices on Static Classes and Members
I am very curious as to thoughts and industry best practices regarding static members, or entire static classes.  Are there any downsides to this, or does it participate in any anti-patterns?

I see these entities as "utility classes/members", in the sense that they don't require or demand instantiating the class in order to provide the functionality.

What are the general thoughts and industry best practices on this?

See the below example classes and members to illustrate what I am referencing.

```<code>// non-static class with static members
//
public class Class1
{
    // ... other non-static members ...

    public static string GetSomeString()
    {
        // do something
    }
}

// static class
//
public static class Class2
{
    // ... other static members ...

    public static string GetSomeString()
    {
        // do something
    }
}
</code>```

Thank you in advance!

答:
In general, avoid statics - especially any sort of static state.

Why?

Statics cause trouble with concurrency. Since there is only one instance, it is naturally shared amongst concurrent execution. Those shared resources are the bane of concurrent programming, and often do not need to be shared.

Statics cause trouble with unit testing. Any unit testing framework worth it's salt runs tests concurrently. Then you run into #1. Worse yet, you complicate your tests with all of the setup/teardown stuff, and the hackery you'll fall into to try and "share" setup code.

There are a plenty of small things too. Statics tend to be inflexible. You can't interface them, you can't override them, you can't control the timing of their construction, you can't use them well in generics. You can't really version them.

There are certainly uses of statics: constant values work great. Pure methods that don't fit in a single class can work great here.

But in general, avoid them.


答: One. But you better be damn good at it.</p>

Title: How many programming languages is a programmer expected to be an expert at?

Body:
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.

Body: One. But you better be damn good at it.


答:
If the function is "pure" I see no problems. A pure function operates only in the input parameters, and provide a result based on that. It does not depend on any global state or external context.

If I look at your own code example:

```<code>public class Class1
{
    public static string GetSomeString()
    {
        // do something
    }
}
</code>```

This function does not take any parameters. Thus, it is probably not pure (the only pure implementation of this function would be to return a constant). I assume that this example is not representative of your actual problem, I am merely pointing out that this is probably not a pure function.

Lets take a different example:

```<code>public static bool IsOdd(int number) { return (number % 2) == 1; }
</code>```

There is nothing wrong with this function being static. We could even make this into an extension function, allowing client code to become even more readable. Extension functions are basically just a special kind of static functions.

Telastyn correctly mentions concurrency as a potential problem with static members. However, since this function does not use shared state, there are no concurrency problems here. A thousand threads can call this function simultaneously without any concurrency issues.

In the .NET framework, extension methods have existed for quite some time. LINQ contains a lot of extension functions (e.g. Enumerable.Where(), Enumerable.First(), Enumerable.Single(), etc.).  We don't see these as bad, do we?

Unit testing can often benefit when the code uses replaceable abstractions, allowing the unit test to replace system code with a test double. Static functions prohibit this flexibility, but this is mostly important at architectural layer boundaries, where we want to replace, for example, an actual data access layer with a fake data access layer.

However, when writing a test for an object that behaves differently, depending on whether  some number is odd or even, we don't really need to be able to replace the IsOdd() function with an alternative implementation. Likewise, I don't see when we need to provide a different Enumerable.Where() implementation for the purpose of testing.

So let's examine the readability of client code for this function:

Option a (with the function declared as an extension method):

```<code>public void Execute(int number) {
    if (number.IsOdd())
        // Do something
}
</code>```

Option b:

```<code>public void Execute(int number) {
    var helper = new NumberHelper();
    if (helper.IsOdd(number))
        // Do something
}
</code>```

The static (extension) function makes the first piece of code much more readable, and readability matters a lot, so use static functions where appropriate.

Title: Thoughts and Best Practices on Static Classes and Members

Body:
I am very curious as to thoughts and industry best practices regarding static members, or entire static classes.  Are there any downsides to this, or does it participate in any anti-patterns?

I see these entities as "utility classes/members", in the sense that they don't require or demand instantiating the class in order to provide the functionality.

What are the general thoughts and industry best practices on this?

See the below example classes and members to illustrate what I am referencing.

```<code>// non-static class with static members
//
public class Class1
{
    // ... other non-static members ...

    public static string GetSomeString()
    {
        // do something
    }
}

// static class
//
public static class Class2
{
    // ... other static members ...

    public static string GetSomeString()
    {
        // do something
    }
}
</code>```

Thank you in advance!

Body:
If the function is "pure" I see no problems. A pure function operates only in the input parameters, and provide a result based on that. It does not depend on any global state or external context.

If I look at your own code example:

public class Class1
{
    public static string GetSomeString()
    {
        // do something
    }
}

This function does not take any parameters. Thus, it is probably not pure (the only pure implementation of this function would be to return a constant). I assume that this example is not representative of your actual problem, I am merely pointing out that this is probably not a pure function.

Lets take a different example:

public static bool IsOdd(int number) { return (number % 2) == 1; }

There is nothing wrong with this function being static. We could even make this into an extension function, allowing client code to become even more readable. Extension functions are basically just a special kind of static functions.

Telastyn correctly mentions concurrency as a potential problem with static members. However, since this function does not use shared state, there are no concurrency problems here. A thousand threads can call this function simultaneously without any concurrency issues.

In the .NET framework, extension methods have existed for quite some time. LINQ contains a lot of extension functions (e.g. Enumerable.Where(), Enumerable.First(), Enumerable.Single(), etc.).  We don't see these as bad, do we?

Unit testing can often benefit when the code uses replaceable abstractions, allowing the unit test to replace system code with a test double. Static functions prohibit this flexibility, but this is mostly important at architectural layer boundaries, where we want to replace, for example, an actual data access layer with a fake data access layer.

However, when writing a test for an object that behaves differently, depending on whether  some number is odd or even, we don't really need to be able to replace the IsOdd() function with an alternative implementation. Likewise, I don't see when we need to provide a different Enumerable.Where() implementation for the purpose of testing.

So let's examine the readability of client code for this function:

Option a (with the function declared as an extension method):

public void Execute(int number) {
    if (number.IsOdd())
        // Do something
}

Option b:

public void Execute(int number) {
    var helper = new NumberHelper();
    if (helper.IsOdd(number))
        // Do something
}

The static (extension) function makes the first piece of code much more readable, and readability matters a lot, so use static functions where appropriate.


答:
I think it probably depends on your personality, there are people who revel in digging down into the nooks and crannies of a subject, and there are others who like to get a broad view of things. You probably will need to figure out what type of personality you are. I am not putting one above the other each have their uses.

As the former you will be the expert, the guru, the specialist. As the latter you will be of more general use and possible used in a variety of situations but possibly not go as deep or long into a subject.


问:
Does this in the Observer pattern count as composition?
In a classic implementation of the Observer design pattern, the subject has a list of references to all of it's observers, and each observer might have a reference to it's subject.

Is this considered composition? As far as I understand, composition means one object 'includes' in itself another object, in order to use functionality of that object. In the Observer pattern, the subject does include in itself references to it's observers, but it doesn't exactly use their functionality internally to do things outwardly. It keeps references so it can notify them.

On the other hand, the subject and observers maintain a relationship of HAS-A, which often characterizes composition (the subject has observers, the observers have a subject).

Is this considered a kind of composition?

答:
In and of itself the observer pattern is not based on composition - it does not require composition.

Your object "has" an observer now, but the next second its observer can be gone (disattached).

Contrary to what composition implies, the lifetimes of the observer and the observable can be independent of eachother, so it's not really a "has-a" relationship. I believe it's an example of aggregation.

If your implementation is tightly coupled and the observable instantiates its own observers, then they'll not survive after the observable is disposed and thus this is indeed composition.


答:
Being notified as per the observer pattern is part of the functionality of the observing object. Insofar, this is an instance of composition.

It's just not a very large part of its functionality: typically, it means implementing one simple method to satisfy one very  light-weight interface. Therefore, this is in no way a prototypical example for what people will think of when you mention "composition" to them, the coupling is much looser than it might be, etc. All this teaches us is that even seemingly clear-cut definitions are almost always a matter of degree in practice.

Title: Does this in the Observer pattern count as composition?

Body:
In a classic implementation of the Observer design pattern, the subject has a list of references to all of it's observers, and each observer might have a reference to it's subject.

Is this considered composition? As far as I understand, composition means one object 'includes' in itself another object, in order to use functionality of that object. In the Observer pattern, the subject does include in itself references to it's observers, but it doesn't exactly use their functionality internally to do things outwardly. It keeps references so it can notify them.

On the other hand, the subject and observers maintain a relationship of HAS-A, which often characterizes composition (the subject has observers, the observers have a subject).

Is this considered a kind of composition?


答:
The observer pattern as it is shown in Wikipedia seems to be indeed based on composition - for calling the notify() method, the subjects needs to "own" the observers. The criteria for this not the usage of an object, but the lifetime - when the lifetime of the subject ends, the lifetime of the observers (which are parts of the subjects) also ends.

However, the original Observer Pattern from the GOF book is better known under the name publisher-subscriber: the notification of other objects works here in a similar manner, but the lifetime of the "observers" and the "observed" objects is completely independent. Thus, publisher-subscriber needs a little bit more effort to implement, subscriber objects (=observers) have to register themselves at the publisher objects (=subject), or to deregister when they don't want to be notified any more. And when the subject's life time ends, the observer objects can still remain, they just won't get any more notification.

So the answer is: it depends which "observer" pattern definition you are using.


问:
can I sell a software that uses a GPL library and another BSD licensed library?
This is the first time I have dealt with licensing issues so I am sorry if I am making any stupid assumptions. My issue is that I have written a program in Python that uses PyQT for the GUI and also uses another library licensed under BSD.

PyQT comes with GPL v2 and GPL v3 as well as a commercial license. From what I have read until now (including the GPL license), I understand that you can sell a software that is licensed under GPL. However, there is an issue if you're not the original author and you are reusing source code that is licensed under GPL. So here are my questions:

In my case since I am using PyQT I believe that I should license my program under GPL as well? Also if this is the case I can sell my software provided that I release the source code as well right?

If PyQT is released under GPL which as far as I understand gives you freedom to sell your software if you use the library why do they also provide a commercial license? Is it only for the case where you do not want to release the source code?

Since I am also using a library that is licensed under BSD it is OK to license my software only under GPL and mention that my program uses this library in the License.txt and the About section of my program?

答:
To answer the third question first, the fact that your program uses a library licensed with license X does not necessarily mean that your program must also use license X.

For permissive licenses, like BSD, you are completely free to choose a different license for your own code.

When the library uses a strong copyleft license, like GPL, then you can avoid a lot of legal questions and uncertainty by using the same license for your code.

The reason for this is because copyleft licenses require you to distribute the entire product that makes use of the copyleft licensed source under the copyleft license conditions. So, when you distribute your program, the GPL conditions of having to provide source code apply to both your code, the PyQT library and the additional BSD-licensed library that you use.

Neither the BSD nor the GPL license prevent you from asking money for your program, but they also don't forbid anyone to buy the program from you and redistribute it further without asking money for it.

The reason that PyQT is available both with the GPL and a commercial license is to make it possible to write commercial applications based on PyQT without having to release your source code.


问:
Should I include myself as an author after modifying 3rd-party code?
It's common practice to make some tweaks or fixes in 3rd-party code (be it a simple gist or an entire library). But it's also common that many of these code have their own licensing rules and eventually a header on every file with copyright informations.

After making those modifications what's the correct thing to do next? Keep the licence info untouchable or try to update it including yourself with something like @author or @revision tags?

Another common problem is changing the 3rd-party namespace/package to fit it to your project conventions. Some license types include these kind of information in their license block, can I change it freely?

I know the answer for these questions depends on each license type, so to make my question more specific...

Considering general license rules (usually they are different in minor aspects, right?), is ethical(or at least allowed) that I freely add information to the license block about my modifications and perhaps also modify how do I refer to it in my code (e.g use YACorp.YALib as Utils.YALib)?

答:
You'll have to consult the licensing rule of the code.

In general, many open source frontend applications (e.g. Firefox, OpenOffice) considers their application name and logo as a trademark; so if you were to release a modified version of the app you will not be able to use the original trademarks/trade dress (thus IceWeasel, Torbrowser, LibreOffice).

However, most programming libraries are often less concerned about trademarks as long as it's fairly clear who does what (usually this can be found from the version control metadata).

Author information serves two purposes:

Giving credit where it is due

Giving blame where it deserves

The latter become more important as your changes become larger. The actual authorship information can generally be found in the version control, but some projects formally credit a set of authors in a separate file. The cutoff point where people would be formally credited varies for each projects, contact the original authors if in doubt.

ContentLicense: CC BY-SA 4.0


答:
GPL nor BSD prevents you from selling your product

GPL requires you to release everything under GPL, and make all source code available

You can't change the license of the BSD licensed library to GPL

Conclusion: you can't release it as is.

As Bart hinted, you can get a commercial license for pyQT which would allow you to release it without putting everything under GPL. I'm not sure if that would clash with the BSD license but I doubt it.

Title: can I sell a software that uses a GPL library and another BSD licensed library?

Body:
This is the first time I have dealt with licensing issues so I am sorry if I am making any stupid assumptions. My issue is that I have written a program in Python that uses PyQT for the GUI and also uses another library licensed under BSD.

PyQT comes with GPL v2 and GPL v3 as well as a commercial license. From what I have read until now (including the GPL license), I understand that you can sell a software that is licensed under GPL. However, there is an issue if you're not the original author and you are reusing source code that is licensed under GPL. So here are my questions:

In my case since I am using PyQT I believe that I should license my program under GPL as well? Also if this is the case I can sell my software provided that I release the source code as well right?

If PyQT is released under GPL which as far as I understand gives you freedom to sell your software if you use the library why do they also provide a commercial license? Is it only for the case where you do not want to release the source code?

Since I am also using a library that is licensed under BSD it is OK to license my software only under GPL and mention that my program uses this library in the License.txt and the About section of my program?


答:
I've always coded in the Windows environment. For me, Linux just used to be another OS I'd have as a backup in case my Windows ran into trouble. I only knew basic commands and everything I tried to do on it seemed to be hard. But now at my current job as a web developer, we all use Linux so I am forced to learn it and use it for everything. The more I use it, the more I like it and I think it's a lot more productive and flexible. I regret not having messed more with Linux before. Now I'm just catching up.

So yes, you should learn it whenever you can.

Title: Which features of shell scripting are relevant for PHP/Python development?

Body:
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?


问:
Java Method Returns Unbounded Type
I was reading this article, https://weblogs.java.net/blog/emcmanus/archive/2010/10/25/using-builder-pattern-subclasses, about subclassing a builder class. I understood the article but there was one small bit that bothered me. There was this method,

```<code>public static Builder<?> builder() {
        return new Builder2();
}
</code>```

When I changed Builder<?> to Builder, a raw type, the compiler would not compile the code. What is the additional information was passed to the compiler via with the additional <?>?

I have pasted the code here:

```<code>public class Shape {

  private final double opacity;

     public static class Builder<T extends Builder<T>> {
         private double opacity;

         public T opacity(double opacity) {
             this.opacity = opacity;
             return self();
         }

 /*
         public T height(double height) {
             System.out.println("height not set");
             return self();
         }
 */
         protected T self() {
             System.out.println("shape.self -> " + this);
             return (T) this;
         }

         public Shape build() {
             return new Shape(this);
         }
     }

     public static Builder<?> builder() {
         return new Builder();
     }

     protected Shape(Builder builder) {
         this.opacity = builder.opacity;
     }
 }

 public class Rectangle extends Shape {
     private final double height;

     public static class Builder<T extends Builder<T>> extends Shape.Builder<T> {
         private double height;

         public T height(double height) {
             System.out.println("height is set");
             this.height = height;
             return self();
         }

         public Rectangle build() {
             return new Rectangle(this);
         }
     }

     public static Builder<?> builder() {
         return new Builder();
     }

     protected Rectangle(Builder builder) {
         super(builder);
         this.height = builder.height;
     }

     public static void main(String[] args) {
         Rectangle r = Rectangle.builder().opacity(0.5).height(250).build();
     }
}
</code>```

答: If you remove the generic part <?> of Builder<?>, all generic information is removed and the T in your Builder class becomes Object - Object does not have an opacity() method.

Title: Java Method Returns Unbounded Type


问:
Invalid data returned, which HttpCode to return?
My web application calls a third party API.

If I successfully call the API but invalid data is returned which cannot be processed by my system what is the most appropriate HttpCode to return to the user calling me?

500, I'm not convinced. Although it was an internal error it's due to external factors

503, Perhaps, although very vague

400, 4XX errors are usually related to the client contacting our server and so could be misleading.

Which is the most appropriate response to return to my client?

答:
If the problem is not the user / client's fault then your server should return a 5xx error.  A 4xx error should only be returned if the >>request<< is incorrect in some way.

Depending on the situation, either 500 or 503 could be appropriate:

As far as a client is concerned the "external factors" are internal to your server / service. So 500 could be appropriate.

If the problem is likely to resolve itself (or be resolved) in a relatively short period of time, 503 could be appropriate.

Probably either of those is OK.

Another possibility is to return a non-standard 5xx code.  Note that non-standard (i.e. not defined in the HTTP 1.1 spec) status codes are not wrong.  There is ample precedent for doing this ... including the precedent of other RFCs defining extra codes; see the Wikipedia List of HTTP Status Codes for examples.

I noticed a comment suggesting this:

In that case I will go for 500, however your users might blame on you for the error.

Provided that you include details of the cause of the problem in the 500 response body (in an appropriate format!), that should not be a problem.

I'd output a proper page -- 200 code, informing them about the third-party call failure and will ask them to try it again later.

IMO, that is incorrect.  A 200 code means that the request has succeeded ... which it patently hasn't.  Assuming that this is a RESTful service, the client is going to use the status code to decide what to do next.  It should not be a lie.  If you want to say "try again later", you should send a 503 response, possibly with a Retry-After header.


答:
As Joel said in the SO podcast, it's better to know many many languages and know how/when to use the right language for the task. There are things you can do way faster in one language than another.
I think it would be good to know an imperative language and a functional language for example. Many times learning a harder or more esoteric language trains your brain to just be a better programmer overall.</p>


问:
Web API architecture design
I'm learning and diving into Web API.  I've used web services before but not specifically with web API.  Below is how I am designing it so far and I was curious on the feedback.

I have a ReturnMessages object.  This basically is a standard object that gets returned from any of the API calls, correctly executed or an error happens.   Within each API method I have a try catch.  if everything is alright, I specify the values I need within my ReturnMessages object and than Ok(_returnMessages).   Now if an error happens I fill in the ReturnMessages object with the error information and once again return Ok(_returnMessages).

The ReturnMessages object contains a ReturnClass field to hold any type of other objects I may need to return.  A single object or an Array.  It also has a return code, return message, friendly message for the end user in case something wrong happens and than a generic string list of data that was passed in that I can send off and use for testing purposes to try and re-create the error.

Below is a code sample from one of the methods that shows off what I am talking about.  Is this approach ok with always returning Ok with the object I'm returning or am I missing potential pieces within the Web API that I should be utilizing?  I've seen the NotFound exceptions and all that other fun stuff.

**EDIT:  I made some changes in terms of what I was passing back for when things don't work out.  I took out the ReturnMessage and also the ReturnData and wrote that to the Application event log for a new string value for this particular web api.  Taht occurs in the _lw code line which is just a LogWriter class that uses the values passed in to write to the application event log.

```<code>public IHttpActionResult method1(string arg 1= null, string arg2 = null, string arg3 = null)
        {
            try
            {
                clrObject1 varClrObject = (from p in db.clrObject1
                                            where p.column1 == arg1
                                            select p).SingleOrDefault();

                if (varClrObject == null)
                {
                    _returnMessages = new ReturnMessages
                    {
                        ReturnCode = 204,
                        FriendlyErrorMessage = "Nothing found matches the supplied values."
                    };

                   _lw.SetupEventLog("No data was found that matched the information supplied.\n\nParameters:\narg1: " + arg1 + "\narg2: " + arg2 + "\narg2=" + arg2, "Warning");
                }
                else
                {
                    _returnMessages = new ReturnMessages
                    {
                        ReturnCode = 200,
                        ReturnClass = varClrObject,
                        ReturnMessage = "Information Successfully Retrieved"
                    };
                }
            }
            catch (Exception e)
            {
                _returnMessages = new ReturnMessages
                {
                    FriendlyErrorMessage = "An error has occurred while getting your information. Please try again in a few minutes.  A notification was already sent to the company about this issue.",
                    ReturnCode = 400
                };

                _lw.SetupEventLog("Parameters:\narg1: " + arg1 + "\narg2: " + arg2 + "\narg3=" + arg3, "Error", e);
            }

            return Ok(new { Response = _returnMessages });
        }
</code>```

答:
I agree with @jhominal that you are making this way more complicated than it needs to be. First, your action should return a concrete instance of an object. The reason for this is to allow the Web API framework to perform content negotiation between JSON and Xml without a lot of fuss. If you don't have to worry about this and can choose between one or the other, you can use an interface for your object (which is typically ideal), but you do not need an HttpActionResult because when you're performing a get in Web API you're looking for a specific resource and that resource should have a type. Anything that does not return a resource should return a properly formatted HttpResponseMessage which is most easily handled through an HttpResponseException. I'll paste a snippet below with comments to describe how I like to build controller actions:

```<code>// I always specify the http verb that the method is
// intended to respond to. It's extremely rare that
// multiple verbs should perform the same actions in
// an API. Also, I'm not a big fan of using optional
// parameters in this manner. I much prefer to use a
// common get action and then pull the arguments like
// this from the RequestUri. It helps keep my routes
// nice and clean
[HttpGet]
public MyCustomObject Post(string arg 1= null, string arg2 = null, string arg3 = null)
{
    // Perform validation of arguments as necessary
    // If it's not necessary, then skip this
    if (string.IsNullOrWhiteSpace(arg1))
    {
        throw new HttpResponseException(Request.CreateErrorResponse(
            HttpStatusCode.BadRequest,
            "I need to be supplied with arg1."));
    }

    // I prefer to send a request with relevant data to
    // a rules engine/library of some sort that returns
    // a formatted response (very similar to your
    // ReturnMessages object
    var response = MyRules.PerformQuery<MyCustomObject>(arg1, arg2, arg3);

    // Just as your ReturnMessages I use a status code
    if (response.Code == ResponseCode.Success)
    {
        return response.Entity;
        // In my preferred architecture, response.Entity is a
        // generic type, in this case MyCustomObject as above
    }

    // If you get to this point, something has gone wrong.
    // You can add additional logic before or after your
    // call to deliver this response message. The arguments
    // necessary are a property HttpStatusCode (any code)
    // and a valid response message string.
    throw new HttpResponseException(
        Request.CreateErrorResponse(response.Code, response.Message));
}
</code>```

So to sum up, I try to keep my architecture as simple as possible. The bones of it are argument validation, a call to a rules engine, concrete object response, and then exception cases. It helps keep the controller action delivering properly http responses relative to resources and messages.

Title: Web API architecture design

Body:
I agree with @jhominal that you are making this way more complicated than it needs to be. First, your action should return a concrete instance of an object. The reason for this is to allow the Web API framework to perform content negotiation between JSON and Xml without a lot of fuss. If you don't have to worry about this and can choose between one or the other, you can use an interface for your object (which is typically ideal), but you do not need an HttpActionResult because when you're performing a get in Web API you're looking for a specific resource and that resource should have a type. Anything that does not return a resource should return a properly formatted HttpResponseMessage which is most easily handled through an HttpResponseException. I'll paste a snippet below with comments to describe how I like to build controller actions:

// I always specify the http verb that the method is
// intended to respond to. It's extremely rare that
// multiple verbs should perform the same actions in
// an API. Also, I'm not a big fan of using optional
// parameters in this manner. I much prefer to use a
// common get action and then pull the arguments like
// this from the RequestUri. It helps keep my routes
// nice and clean
[HttpGet]
public MyCustomObject Post(string arg 1= null, string arg2 = null, string arg3 = null)
{
    // Perform validation of arguments as necessary
    // If it's not necessary, then skip this
    if (string.IsNullOrWhiteSpace(arg1))
    {
        throw new HttpResponseException(Request.CreateErrorResponse(
            HttpStatusCode.BadRequest,
            "I need to be supplied with arg1."));
    }

    // I prefer to send a request with relevant data to
    // a rules engine/library of some sort that returns
    // a formatted response (very similar to your
    // ReturnMessages object
    var response = MyRules.PerformQuery<MyCustomObject>(arg1, arg2, arg3);

    // Just as your ReturnMessages I use a status code
    if (response.Code == ResponseCode.Success)
    {
        return response.Entity;
        // In my preferred architecture, response.Entity is a
        // generic type, in this case MyCustomObject as above
    }

    // If you get to this point, something has gone wrong.
    // You can add additional logic before or after your
    // call to deliver this response message. The arguments
    // necessary are a property HttpStatusCode (any code)
    // and a valid response message string.
    throw new HttpResponseException(
        Request.CreateErrorResponse(response.Code, response.Message));
}

So to sum up, I try to keep my architecture as simple as possible. The bones of it are argument validation, a call to a rules engine, concrete object response, and then exception cases. It helps keep the controller action delivering properly http responses relative to resources and messages.