答:
So based on details OP provided, it sounds like the question is, "how do I learn my own code so that when asked to find X or explain Y, I'm able to respond quickly."

Few suggestions that I can think of:

When coding, you need to take the time to learn and understand your own code. This could be what your TL is trying to get across to you in not so many words. Being a TL on the current project, I've done a lot of code reviews in the last 11 months and I do notice a practice of some developers to search for "example code" either in our own code base, or somewhere else (google, etc...) and copy/paste it in. Personally, I can't stand it because while their code passes the simple unit tests, they do not understand what it is actually doing, so we are never guaranteed that there isn't some boundary case or an expected failure condition that could occur.

As a corollary to previous statement, if you have to copy/paste, try to only copy/paste the code YOU have previously written and that you understand. It is certainly ok to "borrow" other people's idea but in that case, rewrite their code line by line because as you are writing it, you will gain better understanding into what it does. If you are using external APIs, even if you have an example that uses that API, take a few minutes anyway to find a reference and learn how that API works.  Don't just assume that if it worked before, it will also work in your situation.

Read up and learn to love the DRY principle. A lot of times what you are tempted to copy/paste could be placed in a common location (separate function, separate class, separate library...)

Read up and learn to love SOLID principles and while you are at it, review KISS which was already mentioned by mouviciel.  These principles are all oriented at producing very concise, clean and modular code.  If you have large classes and large functions within those, it is clearly going to be much harder to find things and on top of that try to explain what the code does.  On the other hand, if you follow (or at least try to follow) SRP and make each class/function responsible for one thing only, your code will be small and very readable.

Pick up a copy of Clean Code. Very good book.  It talks about writing code that is self explanatory and easy to read, maintain and extend.  If you practice writing code that is easy to read, you shouldn't have problems reading your own code in the code reviews.  And this is the funny part, I've asked people to read their own code or simply tell me what the variables were representing and they couldn't answer even though they wrote that code (brand new classes, not legacy) only a week ago.  Good naming goes a long way.

If after all the simplification and refactoring, you still have a function that has to perform some kind of algorithm which is not very apparent, take the time and write a comment block in that function explaining the algorithm.  Not only will it be helpful when you have to modify that function 2 months from now, but if you get ambushed in a code review, you'd be able to simply read back what you wrote.

If after all the items above, do you still find yourself in trouble? are you new to the team and asked to work with a lot of legacy code? In that case, it could be that your TL is being an A$$ and you could be proactive by asking him before the meeting to go easy and not waste the time of everyone involved.  When new people join a team, TL needs to have enough patience because working in a new platform, new product, new people, new environment takes a lot of concentration from a new person, and that person will be missing some details in the beginning.  Works as Designed and your TL should just accept that.

If after all items above, you still feel that you have horrible code reviews. Talk to your TL. Sometimes people feel bad because of the nature of code review meetings when in fact TL is perfectly happy with you.  When I do code reviews, my goal is to highlight what needs to be changed, make sure you understand the changes and move on.  A lot of times I don't have time to be polite and some people get defensive and attempt to answer every single one of my comments.  In those situations code review meeting grinds to a halt so I tend to interrupt them and move on.  Generally, after the meeting I would talk to the new guys to make sure they understand the process and that it is nothing personal.  After few code reviews people are generally much more comfortable.

Title: Being prepared for a code review as a developer?

Body:
I am looking for some ideas here.

I read the article How should code reviews be Carried Out and Code Reviews, what are the advantages? which were very informative but I still need more clarity on the question below.

My Question is,

Being the target developer, can you suggest some best practices a developer can incorporate before his code is going get reviewed.

Currently I practice the following methods

PPT for a logical flow

Detailed comments.

Issue: Even though I have implemented the above practices, they do not help on the review. The problem I faced is, when certain logic is referred, I keep searching for the implementation and the flow and too much time is wasted in the process and I get on people’s nerve.

I think a lot of developers would be going through what I am going through as well.


问:
Is it better to return NULL or empty values from functions/methods where the return value is not present?
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.

答:
1) If semantic of function is that it can return nothing, caller MUST test for it, otherwise he will eg. take your money and give it to no-one.

2) Its good to make functions that semantically always return something (or throw).

With a logger, it make sense to return logger that does not log if no logger was defined. When returning collection, it almost never makes sense (except on "low enough level", where the collection itself is THE data, not what it contains) to return nothing, because an empty set is a set, not nothing.

With a person example, I would go "hibernate" way (get vs load, IIRC, but there it is complicated by proxy objects for lazy loading) of having two functions, one that returns null and second that throws.

ContentLicense: CC BY-SA 3.0


答: Methods returning collections should return empty but others could return null, because for the collections it might so happen that you will have object but there are no elements in it, so the caller will validate for just size rather both.</p>

Title: Is it better to return NULL or empty values from functions/methods where the return value is not present?

Body:
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.


问:
What, if anything, to do about bow-shaped burndowns?
I've started to notice a recurring pattern to our team's burndown charts, which I call a "bowstring" pattern.  The ideal line is the "string" and the actual line starts out relatively flat, then curves down to meet the target like a bow.

My theory on why they look like this is that toward the beginning of the story, we are doing a lot of debugging or exploratory work that is difficult to estimate remaining work for.  Sometimes it even goes up a little as we discover a task is more difficult once we get into it.  Then we get into implementation and test which is more predictable, hence the curving down graph.  Note I'm not talking about a big scale like BDUF, just the natural short-term constraint that you have to find the bug before you can fix it, coupled with the fact that stories are most likely to start toward the beginning of a two-week iteration.

Is this a common occurrence among scrum teams?  Do people see it as a problem?  If so, what is the root cause and some techniques to deal with it?

答:
If you're still meeting the target, I don't necessarily see this as a problem. You met your target!

Part of the reason for short sprints/increments is to keeps the team focussed: this batch of work should be finished by the end of this sprint.

If you have a long iteration, the amount of time stretches out like the horizon: the deadline never looms until you're right under it.

Also, more loose ends may be tied up towards the end of the sprint. Again, this is fine. The short two week sprint has helped resolve these things before they pile up into a big six month panicky rush mountain.


问:
Refactoring in domain driven design
I've just started working on a project and we're using domain-driven design (as defined by Eric Evans in Domain-Driven Design: Tackling Complexity in the Heart of Software.  I believe that our project is certainly a candidate for this design pattern as Evans describes it in his book.

I'm struggling with the idea of constantly refactoring.

I know refactoring is a necessity in any project and will happen inevitably as the software changes.  However, in my experience, refactoring occurs when the needs of the development team change, not as understanding of the domain changes ("refactoring to greater insight" as Evans calls it).  I'm most concerned with breakthroughs in understanding of the domain model.  I understand making small changes, but what if a large change in the model is necessary?

What's an effective way of convincing yourself (and others) you should refactor after you obtain a clearer domain model?  After all, refactoring to improve code organization or performance could be completely separate from how expressive in terms of the ubiquitous language code is. Sometimes it just seems like there's not enough time to refactor.

Luckily, SCRUM lends it self to refactoring.  The iterative nature of SCRUM makes it easy to build a small piece and change and it.  But over time that piece will get larger and what if you have a breakthrough after that piece is so large that it will be too difficult to change?

Has anyone worked on a project employing domain-driven design? If so, it would be great to get some insight on this one.  I'd especially like to hear some success stories, since DDD seems very difficult to get right.

Thanks!

答:
For some portions of the code, continuous refactoring is overkill. For some other portion of the code (in DDD, the so called Core Domain) is a necessity. Understanding that the code is not how it should be places an extra cognitive load on the developer (the difference between our understanding of the domain and the current implementation) that will make further evolutions more difficult and/or expensive.

The question is: "will these evolution be needed?". In the Core Domain (the area that is making a business difference) the answer is "Yes!". Because that's the potion of the domain the business is more concerned about and the one that will make a difference for the stakeholders. That's the place where you want to keep your code in perfect shape, ready to implement the next requirement with minimal effort, due to the flexibility of your Domain Model.

However that's going to be expensive when applied to all the application code. Areas which are not that significant for the business (Supporting or Generic Subdomains in DDD lingo) might require a less sophisticated approach than the one reserved for the core.

ContentLicense: CC BY-SA 2.5

Title: Refactoring in domain driven design


问:
Why aren't postfix and primary expressions symmetrical?
Every primary expression is a postfix expression but a postfix expression is not primary expression.

But in mathematics, equality seems to be symmetrical. That is:

If A is B, then B is A

Why isn't this the case for postfix and primary expressions?

答:
But In mathematic sense, when A is B then B is also A. I don't get this. How come this is not true? what sort of logic is this or am i missing something here?

To give it a mathematical sense, you have to define the meaning of is in the sentence ''A is B'' in a precise, mathematical way.

I will use small letters from now on (''a is b'' instead of ''A is B'') to indicate elements of a set, and capital letters to indicate sets.

Take a set A and a relation R that is a subset of A x A, i.e. a set of pairs {(a1, b1), (a2, b2) ... | a1, a2, b1, b2, ... in A}. Instead of writing "(a1, b1) belongs to R", write "a1 R b1".

If the relation is

Reflexive: for all a in A, we have a R a.

Symmetric: for all a, b in A, we have that a R b implies b R a.

Transitive: for all a, b, c in A, we have that a R b and b R c implies a R c.

then R is called an equivalence relation.

An example of an equivalence relation is the following:

A is the set of all Java String objects.

For any two strings s1, s2, define s1 R s2 if and only if s1.equals(s2)

A particular equivalence relation is the identity. R is the identify of a set A, if, for all a, b in A, a R b implies a = b. ('=' is equal in a mathematical sense).
An example in Java is the == operator on objects, i.e., for two objects o1, o2, let o1 R o2 if and only if o1 == o2.

Coming back to your question: "A is B then B is also A" refers to a symmetric relation, and the two Java examples above (relations induced by equals(), ==) are example thereof. In this case, a programming language feature corresponds to your "mathematic sense".

There is however, another informal use of "A is B". Let A and B be two sets, and A a subset of B. In this case we say "A is B" (e.g. a Dialog is a Widget) meaning "an element a of A is also an element of B". In general, A is a subset of B does not imply that B is a subset of A. This is only the case when the two sets are equal. Note that the subset relation is a relation between sets and not between their elements.

If A is a subset of B but A is not equal to B, we say that A is a proper subset of B. In your example, the set of primary expressions is a proper subset of the set of postfix expressions.

So, according to the context and the precise definition of "A", "B", and "is" your statement "when A is B then B is also A" can be true or false.


答: You can look for examples of logic in programs, but the question I think you're answering isn't really appropriate (if you're asking it as a logician), since programs are sets of instructions not logical statements (in the symbolic logic sense).

Title: Why aren't postfix and primary expressions symmetrical?

Body:
Every primary expression is a postfix expression but a postfix expression is not primary expression.

But in mathematics, equality seems to be symmetrical. That is:

If A is B, then B is A

Why isn't this the case for postfix and primary expressions?


答:
But In mathematic sense, when A is B then B is also A

From a logical perspective, the verb "to be" is overloaded. In this sentence, "is" means "identity", which is a symmetric, reflexive, transitive relation, so A = B  <=>  B = A. If Superman is Clark Kent, then Clark Kent is also Superman.

In the example you quoted, "a primary expression is also a postfix expression", "is" means "for every x, if x has property A then x also has property B". This is not a symmetric relation. For example, every human is mortal, but not every mortal is human. (Sometimes, this is shortened to "humans are mortal" or in this case "A human is moral, provided...")

Another common use is "x is F" as in "Socrates is human", where "is" means "exemplifies the property" or "has the property". This is not a relation (not in first order logic, anyway), so the terms reflective/symmetric/transitive don't really apply, but you can't deduce from "Socrates is human" that "human is Socrates" or from "Socrates is human and Mike Tyson is human" that "Socrates is Mike Tyson".

The difference is that Socrates, Clark Kent and Superman are individuals (and A and B are meant to be variables referring to individuals) while "primary expression", "postfix expression", "human", "mortal" are properties.

Things get really weird when you have a sentence like "Socrates was Plato's teacher", because "Plato's teacher" is a property, but only one individual has (had) this property, so it can also be used as a name for that individual (in fact, according to some theories of naming, proper names like "Plato" and "Socrates" are simply properties that are only exemplified by one individual and names of fictional characters like "Clark Kent" and "Superman" are actually properties that aren't exemplified by anything). So you might deduce from "Socrates was Plato's Teacher" and "Plato's teacher was poisoned" that "Socrates was poisoned". But this is really a border case that only works because Plato had only one teacher.


答:
In my opinion there is a difference between returning NULL, returning some empty result (e.g. the empty string or an empty list), and throwing an exception.

I normally take the following approach. I consider a function or method f(v1, ..., vn) call as the application of a function

```<code>f : S x T1 x ... x Tn -> T
</code>```

where S it the "state of the world" T1, ..., Tn are the types of input parameters, and T is the return type.

I first try to define this function. If the function is partial (i.e. there are some input values for which it is not defined) I return NULL to signal this. This is because I want the computation to terminate normally and tell me that the function I have requested is not defined on the given inputs. Using, e.g., an empty string as return value is ambiguous because it could be that the function is defined on the inputs and the empty string is the correct result.

I think the extra check for a NULL pointer in the calling code is necessary because you are applying a partial function and it is the task of the called method to tell you if the function if not defined for the given input.

I prefer to use exceptions for errors that do not allow to carry out the computation (i.e. it was not possible to find any answer).

For example, suppose I have a class Customer and I want to implement a method

Customer findCustomer(String customerCode)
```

<p>to search for a customer in the application database by its code.
In this method, I would</p>

<ul>
<li>Return an object of class Customer if the query is successful,</li>
<li>Return null if the query does not find any customer.</li>
<li>Throw an exception if it is not possible to connect to the database.</li>
</ul>

<p>The extra checks for null, e.g.</p>

<pre class="lang-java prettyprint-override"><code>Customer customer = findCustomer("...");
if (customer != null && customer.getOrders() > 0)
{
    ...
}
</code>```

are part of the semantics of what I am doing and I would not just "skip them" in order to make the code read better. I do not think it is a good practice to simplify the semantics of the problem at hand just to simplify the code.

Of course, since the check for null occurs very often is it good if the language supports some special syntax for it.

I would also consider using the Null Object pattern (as suggested by Laf) as long as I can distinguish the null object of a class from all other objects.

Body:
In my opinion there is a difference between returning NULL, returning some empty result (e.g. the empty string or an empty list), and throwing an exception.

I normally take the following approach. I consider a function or method f(v1, ..., vn) call as the application of a function

f : S x T1 x ... x Tn -> T

where S it the "state of the world" T1, ..., Tn are the types of input parameters, and T is the return type.

I first try to define this function. If the function is partial (i.e. there are some input values for which it is not defined) I return NULL to signal this. This is because I want the computation to terminate normally and tell me that the function I have requested is not defined on the given inputs. Using, e.g., an empty string as return value is ambiguous because it could be that the function is defined on the inputs and the empty string is the correct result.

I think the extra check for a NULL pointer in the calling code is necessary because you are applying a partial function and it is the task of the called method to tell you if the function if not defined for the given input.

I prefer to use exceptions for errors that do not allow to carry out the computation (i.e. it was not possible to find any answer).

For example, suppose I have a class Customer and I want to implement a method

Customer findCustomer(String customerCode)

to search for a customer in the application database by its code.
In this method, I would

Return an object of class Customer if the query is successful,

Return null if the query does not find any customer.

Throw an exception if it is not possible to connect to the database.

The extra checks for null, e.g.

Customer customer = findCustomer("...");
if (customer != null && customer.getOrders() > 0)
{
    ...
}

are part of the semantics of what I am doing and I would not just "skip them" in order to make the code read better. I do not think it is a good practice to simplify the semantics of the problem at hand just to simplify the code.

Of course, since the check for null occurs very often is it good if the language supports some special syntax for it.

I would also consider using the Null Object pattern (as suggested by Laf) as long as I can distinguish the null object of a class from all other objects.


问:
What are some of the benefits of a "Micro-ORM"?
I've been looking into the so-called "Micro ORMs" like Dapper and (to a lesser extent as it relies on .NET 4.0) Massive as these might be easier to implement at work than a full-blown ORM since our current system is highly reliant on stored procedures and would require significant refactoring to work with an ORM like NHibernate or EF.  What is the benefit of using one of these over a full-featured ORM?  It seems like just a thin layer around a database connection that still forces you to write raw SQL - perhaps I'm wrong but I was always told the reason for ORMs in the first place is so you didn't have to write SQL, it could be automatically generated; especially for multi-table joins and mapping relationships between tables which are a pain to do in pure SQL but trivial with an ORM.

For instance, looking at an example of Dapper:

```<code>var connection = new SqlConnection(); // setup here...
var person = connection.Query<Person>("select * from people where PersonId = @personId", new { PersonId = 42 });
</code>```

How is that any different than using a handrolled ADO.NET data layer, except that you don't have to write the command, set the parameters and I suppose map the entity back using a Builder.  It looks like you could even use a stored procedure call as the SQL string.

Are there other tangible benefits that I'm missing here where a Micro ORM makes sense to use?  I'm not really seeing how it's saving anything over the "old" way of using ADO.NET except maybe a few lines of code - you still have to write to figure out what SQL you need to execute (which can get hairy) and you still have to map relationships between tables (the part that IMHO ORMs help the most with).

答:
In the website of micro ORM PetaPoco he explain some advantage with other ORM.
to explain more

PetaPoco is a tiny, fast, single-file micro-ORM for .NET and Mono.

Like Massive it's a single file that you easily add to any project

Unlike Massive it works with strongly typed POCO's

Like Massive, it now also supports dynamic Expandos too - read more

Like ActiveRecord, it supports a close relationship between object and database table

Like SubSonic, it supports generation of poco classes with T4 templates

Like Dapper, it's fast because it uses dynamic method generation (MSIL) to assign column values to properties


答:
The disconnect that you have described can be answered by predicate logic, which deals with relationships between classes of objects.

For example "All ostriches are birds" is a true statement, but "All birds are ostriches" is a false statement.

Therefore in this branch of maths, it is not necessarily true that every relation is symmetric,

e.g. all A's are B's therefore all B's are A's.


答:
How is that any different than using a handrolled ADO.NET data layer,
  except that you don't have to write the command, set the parameters
  and I suppose map the entity back using a Builder. It looks like you
  could even use a stored procedure call as the SQL string.

I believe that is the main benefit of a Micro-ORM, to get the other benefits of an ORM you would need to use a full blown one. That and the code is relatively smaller, so if you need to customize it, that would be easier.

Title: What are some of the benefits of a "Micro-ORM"?

Body:
I've been looking into the so-called "Micro ORMs" like Dapper and (to a lesser extent as it relies on .NET 4.0) Massive as these might be easier to implement at work than a full-blown ORM since our current system is highly reliant on stored procedures and would require significant refactoring to work with an ORM like NHibernate or EF.  What is the benefit of using one of these over a full-featured ORM?  It seems like just a thin layer around a database connection that still forces you to write raw SQL - perhaps I'm wrong but I was always told the reason for ORMs in the first place is so you didn't have to write SQL, it could be automatically generated; especially for multi-table joins and mapping relationships between tables which are a pain to do in pure SQL but trivial with an ORM.

For instance, looking at an example of Dapper:

```<code>var connection = new SqlConnection(); // setup here...
var person = connection.Query<Person>("select * from people where PersonId = @personId", new { PersonId = 42 });
</code>```

How is that any different than using a handrolled ADO.NET data layer, except that you don't have to write the command, set the parameters and I suppose map the entity back using a Builder.  It looks like you could even use a stored procedure call as the SQL string.

Are there other tangible benefits that I'm missing here where a Micro ORM makes sense to use?  I'm not really seeing how it's saving anything over the "old" way of using ADO.NET except maybe a few lines of code - you still have to write to figure out what SQL you need to execute (which can get hairy) and you still have to map relationships between tables (the part that IMHO ORMs help the most with).


答:
Benefits:

Similar performance to a raw SqlCommand with DataReader and parsing.

No need to roll your own conversion layer for the DataReader.

That's pretty much it, to be honest. You've got a very lightweight wrapper to your sql connections that will do the object conversion for you. You can, obviously, fine-tune the queries without having to deal with any autogenerated SQL.

Cons:

Not even slightly typesafe. If you make a typo in the SQL your CI server is not going to catch it, you'll have to hope it's caught during automated UI or functional testing.

A pain to maintain. You've got a bunch of inline SQL statements that do various queries that have no strong ties to the DB architecture. This can quite easily lead to queries that get "left behind" when the underlying DB structure changes, which, again, you will not see at build time.

They have their place, and they're a very effective tool that can take away some of the "donkey work" from developers when interacting with the DB, but in reality they simply cannot take the place of a full ORM in any large-scale system for queries that are not performance-critical, simply due to the increased maintenance cost.

If you are struggling with performance on DB queries I'd suggest that it would be better to use these mapping frameworks with Stored Procedures only, in order to get a compile-time indication of whether your SQL is valid (plus the additional performance benefits).


答:
the value of A and B are the same but their location in the computer's memory are different

Reading the concept of references would perhaps give your stated logic a satisfaction
http://en.wikipedia.org/wiki/Reference_(computer_science)


问:
What modern alternatives to Numerical Recipes exist?
In the past, the Numerical Recipes book was considered the gold standard reference for numerical algorithms.  The earliest Fortran Edition was followed by editions in C and C++ and others, bringing it then more up-to-date.  Through these, it provided reference code for the state-of-the-art algorithms of the day.

Older editions are available online for free nowadays.

Unfortunately, I think it is now mostly useful only as a historic tome.  The "software engineering" practices seem to me to be outdated, and the actual content hasn't kept pace with the literature.

What similarly comprehensive yet approachable references should the modern programmer look at instead?

答:
In terms of Numerical Recipes, we need two things - the understanding of how algorithms translates into programming implementation and second, a reference implementation that books things.

There seems to be NO combination of BOOK + Reference software. However, there are some good reference softwares and some of this provides reference to papers on the basis of such an algorithms.

Here is a list of some reference (mostly open source) libraries that might help:

GNU Scientific Library

LAPACK it has a good book as a user manual
There is also LAPACK++ and other (TNT) derived/related packages. See this for more information.

Boost Linear Algebra

Armadillo

BLAS

Other specific things are

Apophenia for statistical models

Colt

FFTW

The R package - and a book

OpenCV

Intel Math kernel Library

For pattern recognition

You can also check out "Data Analysis with Open Source Tools".

Here is a huge list of comparison though i haven't verified everything.

http://www.netlib.org/utk/people/JackDongarra/la-sw.html


答:
Every primary expression is a postfix expression but a postfix expression is not primary expression.

(I have my doubts as to the accuracy of that statement.  Did you transcribe it correctly?)

But the answer is that since the statement is using the phrase "is a" it is talking about sets and using set logic.

The first part of the statement translates to:

```<code>ForAll(e In PrimaryExpression | e In PostfixExpression)
</code>```

the second part doesn't parse as English so I won't attempt to translate it.

Body:
Every primary expression is a postfix expression but a postfix expression is not primary expression.

(I have my doubts as to the accuracy of that statement.  Did you transcribe it correctly?)

But the answer is that since the statement is using the phrase "is a" it is talking about sets and using set logic.

The first part of the statement translates to:

ForAll(e In PrimaryExpression | e In PostfixExpression)

the second part doesn't parse as English so I won't attempt to translate it.


问:
I want to start using TDD. Any tips for a beginner?
I never used an automated test mechanism in any of my projects and I feel I'm missing a lot. I want to improve myself, so I have to start tackling some issues I've been neglecting like this and trying Git instead of being stuck on SVN.

What's a good way to learn TDD? I'll probably be using Eclipse to program in Java. I've heard of JUnit, but I don't know if there's anything else I should consider.

答:
I highly recommend this book: Growing Object-Oriented Software Guided by Tests

It has a worked example running through the book and provides a very coherent view of when test should be created, what they ought to contain and how they should be constructed and refactored.


问:
What Part of Your Project Should be in Source Code Control?
A fellow developer has started work on a new Drupal project, and the sysadmin has suggested that they should only put the sites/default subdirectory in source control, because it "will make updates easily scriptable."  Setting aside that somewhat dubious claim, it raises another question -- what files should be under source control?  And is there a situation where some large chunk of files should be excluded?

My opinion is that the entire tree for the project should be under control, and this would be true for a Drupal project, rails, or anything else. This seems like a no-brainer -- you clearly need versioning for your framework as much as you do for any custom code you write.

That said, I would love to get other opinions on this.  Are there any arguments for not having everything under control?

答:
Anything that contributes to the project and for which you want to track changes.

Exceptions can include large binary blobs such as images, if you're using an scm that doesn't handle binary data very well.


答: I would say that the minimum that source control should contain is all of the files necessary to recreate a running version of the project. This even includes DDL files to set up and modify any database schema, and in the correct sequence too. Minus, of course, the tools necessary to build and execute the project as well as anything that can be automatically derived/generated from other files in source control (such as JavaDoc files generated from the Java files in source control).

Title: What Part of Your Project Should be in Source Code Control?

Body:
A fellow developer has started work on a new Drupal project, and the sysadmin has suggested that they should only put the sites/default subdirectory in source control, because it "will make updates easily scriptable."  Setting aside that somewhat dubious claim, it raises another question -- what files should be under source control?  And is there a situation where some large chunk of files should be excluded?

My opinion is that the entire tree for the project should be under control, and this would be true for a Drupal project, rails, or anything else. This seems like a no-brainer -- you clearly need versioning for your framework as much as you do for any custom code you write.

That said, I would love to get other opinions on this.  Are there any arguments for not having everything under control?


答: The only things that I do not put under source control are files that you can easily regenerate or are developer specific. This means executables and binaries that are composed of your source code, documentation that is generated from reading/parsing files under source control, and IDE-specific files. Everything else goes into version control and is appropriately managed.</p>


答:
I would say that;

any file needed to perform the build goes into version control

any file (which can be) generated by the build does not

I would tend to put large binaries such as tool install packages somewhere outside of the trunk, but they should still be under version control.


答:
Everything should be under source control, except:

Configuration files, if they include configuration options that are different for each developer and / or each environment (development, testing, production)

Cache files, if you are using filesystem caching

Log files, if you are logging to text files

Anything that like cache files and log files is generated content

(Very) Large binary files that are unlikely to change (some version control systems don't like them, but if you are using hg or git they don't mind much)

Think of it like that: Every new member to the team should be able to checkout a working copy of the project (minus the configuration items).

And don't forget to put database schema changes (simple sql dumps of every schema change) under version control too. You could include user and api documentation, if it makes sense to the project.

@maple_shaft raises an important issue with my first statement regarding environment configuration files in the comments. I'd like to clarify that my answer is to the specifics of the question, which is about Drupal or generic CMS projects. In such scenarios you typically have a local and a production database, and one environment configuration option is the credentials to these databases (and similar credentials). It's advisable that these are NOT under source control, as that would create several security concerns.

In a more typical development workflow however, I do agree with maple_shaft that environment configuration options should be under source control to enable for an one-step build and deploy of any environment.


答:
It is best to put just about everything under the sun into source control.

Code

Libraries

Resources

Build/Deploy Scripts

Database creation and update scripts

Certain documentation

Environment Specific Configuration Files

The only thing that shouldn't be put into source control are build artifacts for your project.


答: And don't forget to put all database code in Source Control as well! This would include the orginal create scripts, the scripts to alter tables (that are marked by what version of the software uses them, so you can recreate any version of the database for any version of the applications) and scripts to populate any lookup tables.</p>


问:
How can you achieve and maintain flow while pair programming?
Flow is a concept introduced by Mihaly Csikszentmihalyi; in short, it means to get into the "zone". You feel immersed in your task, focused; the task can be difficult but challenging at the same time. When people achieve flow their productivity shoots up. Programming requires a great deal of mental focus because we often need to juggle several things in our minds at once. Many like to work in a quiet environment where they can direct their full attention to the task. If they are interrupted, it may take several minutes or even hours to get back into flow.

I understand there's a practice in agile development and extreme programming called pair programming. It means you put the whole software development team in one room so that communication is seamless. You do write code with your pair because this way you get instant code reviews and fewer bugs get through.

I've always had problems achieving flow while doing pair programming because of constant interruptions. I'm thinking deep about an issue then all of sudden someone asks me a question from another pair. My train of thought is lost.

How can you achieve and maintain flow while pair programming?

答:
As a developer attempting to get into the zone, you'll attempt to isolate yourself as best as you can to get comfortable and clear your mind. Why should pair programming be any different?

You and your partner should find a zone-inducing environment that works for you both. This will possibly require compromise on some things, but my main point is that the pair environment should be similar to the solo. Turn off the external world. The pair is programming together; other pairs (other co-workers in general) should not be interrupting (excepting critical, drop-what-you-are-doing problems).


问:
HTTP events? Is there a standard / precedent for this?
Our architecture is HTTP servers (custom written) whereby custom clients send a HTTP request for some information and information is returned just as HTTP works. Now we need a special custom 'extension' which is a request which is a subscription for receiving asynchronous 'events' on a resource.

For example, the client sends an http request subscribing for events on some entity. As the 'entity' generates events they are passed to the http server and the http server must then lookup subscriptions for that entity and send the event message to all subscribed clients. Hope that makes sense.

So my questions are:

Has this been done before / or is there a standard I should be looking at?

If no standard, any suggestions on how to implement?

How does a http server send an unsolicited 'message' to a client?

答:
You can't (that I know of) open an unsolicited CONNECTION (as in socket connection) to an HTTP client. You can, however, send unsolicited MESSAGES across a channel the client has left open. This concept is called Comet.

This pattern works nicely, and it should be able to provide the kind of pub-sub updates you are talking about.


答: It's really not what HTTP, as a connectionless protocol, was designed for so you may want to consider using something else for this type of communication, for example the XMPP protocol, or an enterprise messaging solution such as RabbitMQ.</p>

Title: HTTP events? Is there a standard / precedent for this?

Body:
Our architecture is HTTP servers (custom written) whereby custom clients send a HTTP request for some information and information is returned just as HTTP works. Now we need a special custom 'extension' which is a request which is a subscription for receiving asynchronous 'events' on a resource.

For example, the client sends an http request subscribing for events on some entity. As the 'entity' generates events they are passed to the http server and the http server must then lookup subscriptions for that entity and send the event message to all subscribed clients. Hope that makes sense.

So my questions are:

Has this been done before / or is there a standard I should be looking at?

If no standard, any suggestions on how to implement?

How does a http server send an unsolicited 'message' to a client?


问:
Why are public and private accessors considered good practice?

Possible Duplicate:

  When are Getters and Setters Justified

Why exactly is having public and private accessors like these:

```<code>private string foo;

public string Foo
{
    get
    {
        return foo;
    }
    set
    {
        foo = value;
    }
}
</code>```

considered better than just having public ones like this:

```<code>public string Foo;
</code>```

The end result seems to be the same.

答:
So you can protect the internal state of your classes.

You can set the property to have validation happen during set (some argue this should be done with a method)

You can hide variables that the user of the class should never see nor modify.

I don't care about your internal counter, or whatever other variables you need.  And modifying certain variables in a class will completely break it.


问:
Is there a canonical tutorial or book on functional programming concepts?
Coming from a procedural/OO programming background, I tend to write Scheme programs in a procedural fashion. I would be intersted in learning Scheme or Lisp in a functional way from the ground up, to kind of reset my programmer's mind.

Is there a tutorial or book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on functional programming concepts? What about that book makes it special?

答:
The book I always see recommended when talking about Scheme or Lisp is The Structure and Interpretation of Computer Programs. It's freely available on that website, and I think it's provided as a PDF if you search around.

I've been meaning to work through it, but I'm not sure when I'll get the time. I can't comment on how good the book actually is, though. But it's been recommended by multiple people, so I'm guessing its pretty good.

If you are interested in other functional programming languages, I've been told that it's rather easy to do the exercises in languages like Haskell or F#. I think there's also a blogger who is working through SICP using Haskell and posting his solutions to the exercises, but I can't find the link right now.

ContentLicense: CC BY-SA 4.0


问:
Programming in academic environment vs industry environment

Possible Duplicate:

  Differences between programming in school vs programming in industry?

This is a general discussion about programming in the industry environment.
The background story is that my colleague sent me a very interesting article called "10 Things Entrepreneurs Don’t Learn in College." The first point in that post is about the author's experience of programming in the academic environment vs industry environment. After finishing a 4 year Computer Science degree course, I am currently working in the academic environment as a developer, mainly writing Java, J2EE, Javascript code. I know there are differences between academic programming and industry programming, but I was shocked after reading that post.

Trying to avoid this happening on me in the future, or the others. Can anyone from industry give some general advice about how to program in industry. For example,

What exactly happens when a task is received?

What is the flow from the beginning to the end?

What are the main differences between the programming in industry and academia?

Is it more structured?

Are more frameworks used?

It would be great if some code examples could be given.

Thanks.

答:
From a day to day coding perspective the biggest difference I noticed was that in academia I never had to work with legacy code, and any code I wrote was probably never going to be maintained by anyone else for very long.

It took year or two of working in industry to realise the importance of writing maintainable code - agile methodologies such as refactoring, unit testing, keeping methods and classes short, using good names instead of short ones, automated building, continuous integration etc.


问:
how to layout good documentation
I need to write out a documentation for developers to be able to use some API web software how should i lay out a documentation? What should always be included? And does it need to be really long or keep it simple and easy as possible for anybody to understand?</p>

答:
Describe what each API call does, include a description of any parameters and also what the return value if any is (including possible errors/exceptions).

Additionally if there's time, provide real world examples of how your API is used, if the API is for developers or you are passing it on to someone who will be maintaining the code a nice way to do this is by providing automated unit tests that demonstrate the use of the API and also assert it is working correctly.

Title: how to layout good documentation


答:
HTTP protocol is an application layer protocol, and it sounds like what you want isn't really HTTP at all.

Just open a simple TCP/IP connection socket and have the client on a seperate thread listen for messages from the server.  There are also plenty of frameworks as others are pointing out that will handle this complexity for you.


答:
One reason might be that you want to perform some validation or additional operations in the setter.

(Sorry mis-read this first, have edited my answer)

Title: Why are public and private accessors considered good practice?

Body:
Possible Duplicate:

  When are Getters and Setters Justified

Why exactly is having public and private accessors like these:

```<code>private string foo;

public string Foo
{
    get
    {
        return foo;
    }
    set
    {
        foo = value;
    }
}
</code>```

considered better than just having public ones like this:

```<code>public string Foo;
</code>```

The end result seems to be the same.


答:
I believe Einstein's quote, "Everything should be made as simple as possible, but no simpler," applies well here.  If you can convey your ideas in 5 pages of text, no reason to write 50.

One way to do this is to setup a wiki site and write documentation in it.  Advantage of that is that you can start writing documentation, whatever you miss or stuff that's not clear, other people will be able to correct and add to.

In my team we are also experimenting with using Doxygen. The good part is that it makes you document public interfaces in your code and that's good even without online documentation.  But then it generates HTML pages which could contain a description of all your method calls (similar to "Reference" sections in MSDN library).

However, my problem with Doxygen is that often times it feels that "Reference" section is not enough and you want to add MSDN's equivalent "Using" section (and maybe event "About"), but so far I haven't been able to figure out how to do that with Doxygen.  And the links it generates are not permalinks so you can't have wiki pages that automatically take you to a specific reference page.

Title: how to layout good documentation

Body: I need to write out a documentation for developers to be able to use some API web software how should i lay out a documentation? What should always be included? And does it need to be really long or keep it simple and easy as possible for anybody to understand?</p>


问:
Being prepared for a code review as a developer?
I am looking for some ideas here.

I read the article How should code reviews be Carried Out and Code Reviews, what are the advantages? which were very informative but I still need more clarity on the question below.

My Question is,

Being the target developer, can you suggest some best practices a developer can incorporate before his code is going get reviewed.

Currently I practice the following methods

PPT for a logical flow

Detailed comments.

Issue: Even though I have implemented the above practices, they do not help on the review. The problem I faced is, when certain logic is referred, I keep searching for the implementation and the flow and too much time is wasted in the process and I get on people’s nerve.

I think a lot of developers would be going through what I am going through as well.

答:
One more thing to add to the other answers: to make formal code reviewers easier, conduct LOTS of informal code reviews! For instance:

"Hey Bob, can I show you how I implemented the foo() function?"
"Hey Steve, can you take a look at this class diagram and let me know what you think?"
"Hey Karen, can you help me think through this problem? I think I've got a good solution, but I could use your help..."

Make this a regular habit. When you involve your coworkers early in the design process, you:

Build relationships

Gain new insights into the problem

Improve your ability to explain the problem / solution at hand

Save time later in formal code reviews


答:
Properties do not have the same semantics as public variables:

Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to always use properties.

You can't databind against a variable.

Changing a variable to a property is a breaking change, if you decide you want to add validation or other logic later.

Automatic properties make it easier to use public properties exclusively.


问:
Referring to hardware/software in first-person?
At my company, there is a habit for the engineers to refer to their respective hardware/firmware/software in the first-person as if the device they are responsible for is a manifestation of themselves.

I'll give you an example:

Hardware Engineer: "I don't receive the first byte, so I stay off."

Software Engineer: "I'm sending you the first byte after the ack flag, so I thought you were getting it."

Hardware Engineer: "No, you're not turning me on."

It was this very example I overheard today that nearly had me giggling in fits. "You're not turning me on." Well, I should hope not!

So, is it common practice for engineers to do this, or simply unprofessional?

Any suggestions for changing this apparently bad habit?

答:
If the two engineers understand each other and are working through their problem, their choice of person is irrelevant.

Professionalism doesn't enter into this.


答: In this example it's proabably not any advantage, but when systems get large and complex it can really come in useful to restrict a classes "access points".</p>


答:
I suppose in your particular case it is okay and only because there are usually such clear lines of delineation between the hardware, firmware and software guys.

If they were all software guys working on the same application however I would see it as a warning sign that little fiefdoms may be forming around particular components or domain areas.  This runs counter to Agile, which suggests all developers should be able to play different roles at different times.

Title: Referring to hardware/software in first-person?

Body:
At my company, there is a habit for the engineers to refer to their respective hardware/firmware/software in the first-person as if the device they are responsible for is a manifestation of themselves.

I'll give you an example:

Hardware Engineer: "I don't receive the first byte, so I stay off."

Software Engineer: "I'm sending you the first byte after the ack flag, so I thought you were getting it."

Hardware Engineer: "No, you're not turning me on."

It was this very example I overheard today that nearly had me giggling in fits. "You're not turning me on." Well, I should hope not!

So, is it common practice for engineers to do this, or simply unprofessional?

Any suggestions for changing this apparently bad habit?


答:
Pair programming sometimes requires periods of isolation from your partner.

Example

You are working together on a particular class, and you realize that you need to write a method that requires deep thought on some complex logic, but otherwise returns a mundane result.  You work together on creating unit tests for that method, and defer the writing of that method to a period of time when you're working in isolation.  When the method is completed, you get back together as a pair and evaluate the results.

Body:
Flow is a concept introduced by Mihaly Csikszentmihalyi; in short, it means to get into the "zone". You feel immersed in your task, focused; the task can be difficult but challenging at the same time. When people achieve flow their productivity shoots up. Programming requires a great deal of mental focus because we often need to juggle several things in our minds at once. Many like to work in a quiet environment where they can direct their full attention to the task. If they are interrupted, it may take several minutes or even hours to get back into flow.

I understand there's a practice in agile development and extreme programming called pair programming. It means you put the whole software development team in one room so that communication is seamless. You do write code with your pair because this way you get instant code reviews and fewer bugs get through.

I've always had problems achieving flow while doing pair programming because of constant interruptions. I'm thinking deep about an issue then all of sudden someone asks me a question from another pair. My train of thought is lost.

How can you achieve and maintain flow while pair programming?


问:
How can I improve my error checking and handling?
Lately I have been struggling to understand what the right amount of checking is and what the proper methods are.

I have a few questions regarding this:

What is the proper way to check for errors (bad input, bad states, etc)? Is it better to explicitly check for errors, or use functions like asserts which can be optimized out of your final code? I feel like explicitly checking clutters a program with a lot of extra code which shouldn't be executed in most situations anyway-- and not to mention most errors end up with an abort/exit failure. Why clutter a function with explicit checks just to abort? I have looked for asserts versus explicit checking of errors and found little to truly explain when to do either.

Most say 'use asserts to check for logic errors and use explicit checks to check for other failures.' This doesn't seem to get us very far though. Would we say this is feasible:

```<code>Malloc returning null, check explictly
API user inserting odd input for functions, use asserts
</code>```

Would this make me any better at error checking? What else can I do? I really want to improve and write better, 'professional' code.

答:
The various things that you can do is

 1.Read and assimilate lot of code online and see how it is done

 2.Use some debugging tools so as to help you locate regions of errors

3.Be aware of trivial errors due to improper assignments and syntax errors.

4. Some worse errors arrise due to logical errors in the program which are harder to find .For this you can pen it out and find or for more complicated ones try speaking to people or use resources like Stackoverflow, Wikipedia, google to get help from people.

OwnerDisplayName: Google


答:
The use-case for source control is : What if all our developers machines and all of our deployment machines were hit by a meteor? You want recovery to be as close to checkout and build as possible. (If that's too silly, you can go with "hire a new developer.")

In other words, everything other than OS, apps, and tools should be in VCS, and in embedded systems, where there can be a dependency on a specific tool binary version, I've seen the tools kept in VCS too!

Incomplete source control is one of the most common risks I see when consulting -- there's all sorts of friction associated with bringing on a new developer or setting up a new machine. Along with the concepts of Continuous Integration and Continuous Delivery you ought to have a sense of "Continuous Development" -- can an IT person set up a new development or deployment machine essentially automatically, so that the developer can be looking at code before they finish their first cup of coffee?


答:
Keep all code in version control and all the configurations & user data out.
To be specific to drupal, you need to put everything in version control except files and settings.php</p>


答: Drupal uses git so I will use git's terminology.  I would use subrepos for each module to be able to pull down module updates from drupal's official repos, while still preserving the structure of individual deployments.  That way you get the scriptability benefits without losing the benefits of having everything under source control.  </p>


问:
Is PHP suitable for downloading large amounts of data?
Is PHP suitable for downloading large amounts of data, usually via cron? Should I worry about the memory footprint when I am using PHP for downloading multiple zip files?</p>

答: While you can use PHP for this, it is hardly the most efficient tool, nor the easiest to use. Specialized command-line downloaders such as wget or curl are much better suited; you can drive them directly from cron, or you can write a simple shell script to encapsulate the required parameters. Another advantage of using shell script is that it is fairly easy to do multiple downloads in parallel (by chaining commands together with &).


答:
I've found there is a small class of problems for which pair programming works.  For example, if you are working on a cross platform product and the Winders guy has implemented a feature that requires OS specific code, he can help the Mac guy implement the same feature on the Mac code while the Mac guy drives.

However in my experience pair programming unusually results in a net loss of productivity.  It so often feels like we're paying two developers to do the job of one.

Yes, it reduces the horrifying possibility that a dev might take a stackexchange break during the workday.

IMHO it would be cheaper for those companies who want to police their devs to just pair every dev with a private security guard to stand behind the developer and hit the dev with a truncheon if he ever slows down or tries to peak at a non-essential web page.

Title: How can you achieve and maintain flow while pair programming?


问:
ResourceSerializable: an alternate to ORM and ActiveRecord
A few opinionated reasons I don't like the traditional ORM and ActiveRecord patterns:

They work only with a database. Sometimes I'm dealing with objects from an API and other objects from a database.  All the implementations I have seen don't allow for that. Feel free to clue me in if I'm wrong on this.

They are brittle. Changes in the database will likely break your implemenation.  Some implementations can help reduce this, but a few of the ones I've seen don't.

Their very design is influenced by the database. If I want to switch to using an API, I'll have to redesign the object to get it to work (likely).

It seems to violate the single-responsibility pattern. They know what they are and how they act, but they also know how they are created, destroyed and saved?  Seems a bit much.

What about an approach that is somewhat more familiar in PHP: implementing an interface?  In php 5.4, we'll have the JsonSerializable interface that defines the data to be json_encoded, so users will become accustomed to this type of thing. What if there was a ResourceSerializable interface? This is still an ORM by name, but certainly not by tradition.

```<code>interface ResourceSerializable {
    /**
     * Returns the id that identifies the resource.
     */
    function resourceId();

    /**
     * Returns the 'type' of the resource.
     */
    function resourceType();

    /**
     * Returns the data to be serialized.
     */
    function resourceSerialize();
}
</code>```

Things might be poorly named, I'll take suggestions.

Notes:

ResourceId will work for API's and databases.  As long as your primary key in the database is the same as the resource ID in the API, there is no conflict.  All of the API's I've worked with have a unique ID for the resource, so I don't see any issues there.

ResourceType is the group or type associated with the resource.  You can use this to map the resource to an API call or a database table.  If the ResourceType was person, it could map to /api/1/person/{resourceId} and the table persons (or people, if it's smart enough).

resourceSerialize() returns the data to be stored. Keys would identify API parameters and database table columns.

This also seems easier to test than ActiveRecord / Orm implemenations. I haven't done much automated testing on traditional ActiveRecord/ORM implemenations, so this is merely a guess.  But it seems that I being able to create objects independently of the library helps me.  I don't have to use load() to get an existing resource, I can simply create one and set all the right properties.  This is not so easy in the ActiveRecord / Orm implemenations I've dealt with.

Downsides:

You need another object to serialize it. This also means you have more code in general as you have to use more objects.

You have to map resource types to API calls and database tables. This is even more work, but some ORMs and ActiveRecord implementations require you to map objects to table names anyway.

Are there other downsides that you see?

Does this seem feasible to you?

How would you improve it?

Note: I almost asked this on StackOverflow because it might be too vague for their standards, but I'm still not really familiar with programmers.stackexchange.com, so please help me improve my question if it doesn't shape up to standards here.

答:
Not all ORM's are the same.  For instance, (sorry for my non-PHP background here -- see later) Hibernate and NHibernate make a big deal out of the fact that your entity classes are "Plain Old Java Objects" or "Plain Old CLR Objects" (aka POJO's and POCO's).  EntityFramework 4.0 apparently allows this too.

That means they don't know anything about persisting themselves.  So if you use the Repository Pattern, then your persistence logic is all hidden away.  Inside your repository implementation you create a mapping from your entities to whatever database/service/whatever you want.  (N)Hibernate has options for specifying this in XML or fluently with an API.  However, you could replace this with a repository that persists your entities over a web service.

Downsides?

It's more work than entities auto-generated from the database, if your database already exists.  (On the other hand, (N)Hibernate can actually generate your database schema for you based on your entity mapping.)

Feasible?

Yes, I think it's just the repository pattern with another name.  However, I don't like the idea of having to derive my entity classes from a special base class, as you've defined.

Improve it?

Careful not to re-invent the wheel here.  Make sure you do a good survey of all your options first, like Doctrine or Propel.  Many brighter minds than us have been working at this kind of stuff for decades now, and they've come up with some very advanced and flexible solutions.


答:
Edit: Disclaimer - This is how I define "the zone":
A state of extreme focus, in which one is able to understand how many intricate details connect together, regardless of whether these do so elegantly (or simply) or not.

I try to avoid this state because, while I may produce correct code in the zone, I and other developers will have a hard time understanding it later on. To put it short: reading code that was written in the zone may often require the reader being in the zone. That constraint is my problem.

There's a lovely chapter on The Clean Coder where Uncle Bob persuasively explains why "getting into the zone" is a delusively bad idea.

Here's a possibly better alternative than "getting in the zone": think straight and consider calmly and professionally what you're doing. Communicate. Share thoughts with your partner(s). Identify the real problems. Discuss possible solutions. You might not feel supernaturely focused, but you're likely to make good decisions, and approachable designs.

If you and your pair-partner can discuss the problem without both of you being extremely focused, then chances are you've boiled the problem down to its simpler nature. That suggests you'll be able to understand it again whenever you need to.

On the flip side... If you just need some time alone to get your head straight (we all do sometimes), just take it. Get your thoughts together. Work the problem out in your head first.

But the thing is that if you do - don't use that time to write production code. Instead, play around with sample code and prototypes. Try to understand the problem, without thinking about solutions just yet. Once you get everything straight and written down, discuss it with your team and pair partner, or even the rubber duck on your desk. If you still can't articulate it, or they can't understand it, then refine your ideas. Once you've nailed all of that down - integrate all that thought and sample code into a real, working solution.


答:
As tdammers pointed out, PHP can do this, but there are far more efficient tools for this task.

One of the reasons for this is, as you pointed out, the extra memory footprint required to instantiate a PHP script.

Also, while PHP can run perfectly fine in a command line (or continuous) environment, it is not specifically designed to do so. I have seen many professionals neglect memory management in these circumstances, because they're used to the PHP "we'll clean it up at the end of the script" methodology.

As a final point, why write something that already exists? Assuming that you don't need any special logic, simple curl statement would be just fine to download the zips you require. Also, depending on what you will be doing after this, you could pipe them through zip command and decompress them automatically after download.

Title: Is PHP suitable for downloading large amounts of data?

Body: Is PHP suitable for downloading large amounts of data, usually via cron? Should I worry about the memory footprint when I am using PHP for downloading multiple zip files?</p>


问:
How to you "sell" support as an career option
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)

答:
If you think that support is a second-rate job, you'll likely have trouble hiring people for it.  If you treat it as a career-limiting and dead-end job, you won't get good applicants.

Support isn't generally seen as as much fun as new development, and if you've got separate development and support teams the support teams have to take what development gives them, which is often not fun.  (I worked at a place once where R&D would hand us some software that did something cool, but which typically needed redesign to be production-quality, and we didn't get enough time to do that, for political reasons.  That wasn't fun.)

If support really is business-critical, you have to treat it as such.  If you insist on having separate support teams, and it's important to have good ones, you need to address these issues.  Make sure there's a career path up.  Publicize the money you're making from support, partly for their self-esteem, partly to make other people realize their value, partly so they can put dollar figures for their activities on their resumes.  Establish standards, and allow the support teams some input in whether a project is ready to go from development to support.  Since the job is less fun and possibly more important, pay them better.  (I'd have more sympathy with managers who complain "we can't get the applicants we need" if it didn't usually translate as "we can't the the applicants we need cheap".)


问:
Why should I use Zend_Application?
I've been working on a Zend Framework application which currently does a bunch of things through Zend Application and a few resource plugins written for it.

However, looking at this codebase now, it seems to me that using Zend_Application just makes things more complicated; and a plain, more "traditional" bootstrap file would do a better job of being transparent. This is even more the case because the individual components of Zend -- Zend_Controller, Zend_Navigation, etc. -- don't reference Zend_Application at all. Therefore they do things like "Well just call setRoute and be on your way," and the user is left scratching their head as to how to implement that in terms of the application.ini configuration file.

This is not to say that one can't figure out what's going on by doing spelunking through the ZF source code. My problem with that approach is that it's to easy to depend on something that's an implementation detail, rather than a contract, and that all it seems to do is add an extra layer of indirection that one must wade through to understand an application.

I look at pre ZF 1.8 example code, before Zend_Application existed, and everywhere I see plain bootstrap files that setup the MVC framework and get on their way. The code is clear and easy to understand, even if it is a bit repetitive. I like the DRY concept that Application gets you, but particularly when I'm assuming first people looking at the app's code aren't really familiar with Zend at all, I'm considering blowing away any dependence I have on Zend_Application and returning to a traditional bootstrap file.

Now, my concern here is that I don't have much experience doing this, and I don't want to get rid of Zend_Application if it does something particularly important of which I am unaware, or something of that nature. Is there a really good reason I should keep it around?

答: Call me simplistic, but I don't see a reason to essentially rewrite a large portion of your code base that you describe as working well for no reason other than it seems to make things more complicated. Seems like a recipe for disaster, to me.</p>

Title: Why should I use Zend_Application?


问:
Is there a language that allows this syntax: add(elements)at(index);

Possible Duplicate:

  Is there a language out there in which parameters are placed inside method name?

Does a language exist with such a syntax? If not, what are some of the limitations/disadvantages to this syntax in case I want to write a language that supported it?

Some examples:

```<code>sort(array, fromIndex, toIndex);
</code>```

vs

```<code>sort(array)from(index1)to(index2);
</code>```

Method signature would like this:

```<code>sort(SomeType[] arr)from(int begin)to(int end){
...
}
</code>```

Update:

Because there might be some confusion, I'd like to clarify...
I meant this question as a general idea like this (not specific to sorting and possibly using keywords like from and to):

In JAVA(like language):

```<code>void myfancymethod(int arg1, String arg2){
...
}

myfancymethod(1, "foo");
</code>```

In imaginary language:

```<code>void my(int arg1)fancy(String arg2)method{
...
}

my(1)fancy("foo")method;
</code>```

答:
Smalltalk and derived languages (including Objective C) use a syntax like this for method calls.

In Objective C, for instance, one can work with an NSMutableArray container with something like:

```<code>id a = [[NSMutableArray alloc] initWithCapacity: 3]

[a insertObject: @"Bob" atIndex: 0]
[a insertObject: @"Fred" atIndex: 1]
[a insertObject: @"Mary" atIndex: 2]

[a replaceObjectAtIndex: 3 withObject: @"Hello, World!"]
</code>```

Body:
Smalltalk and derived languages (including Objective C) use a syntax like this for method calls.

In Objective C, for instance, one can work with an NSMutableArray container with something like:

id a = [[NSMutableArray alloc] initWithCapacity: 3]

[a insertObject: @"Bob" atIndex: 0]
[a insertObject: @"Fred" atIndex: 1]
[a insertObject: @"Mary" atIndex: 2]

[a replaceObjectAtIndex: 3 withObject: @"Hello, World!"]


问:
What's the real benefit of meta-modeling?
After reading several texts about meta-modeling I still do not really get the practical benefit. Sometimes I think it is only an interesting mind game but no useful tool. Sure it is wise to clarify your modeling vocabulary: some may say class where others say entity or concept, but this is just simple documentation your modeling terminology. Meta-modeling, as I understand it, is more complex, as it tries to formalize and abstract modeling. Some good examples are  Keet's formal comparison of conceptual data modeling languages (UML, ERM and ORM) from academia and the Meta Object Facility (MOF) from industry. To me MOF looks as impractical as CORBA, which was also created by OMG. In theory you could use meta-modeling to transform and integrate models in different modeling languages, but is anyone actually doing this?

答:
You have different layers of abstractions. MOF is the highest, then using a transformation you get UML or BPM models, then views. Modelers usually talks about M0,M1..M3
I think that with new technologies traditional barriers between metamodelling and modeling is disappearing. Let's consider EMF (eclipse modeling technology). Ecore is a kind of MOF then using EMF serialization you get an UML model, then using GMF you get graphical representations.  </p>


答:
If you create a fluent interface, you can write it more or less like this:

```<code>array.From(fromIndex).To(toIndex).Sort();
</code>```

But method overload resolution will give you simpler syntax:

```<code>array.Sort(fromIndex, toIndex);
</code>```

...and if you name things sensibly, it's still self-describing.

If you still need the descriptive verbiage, some languages (like C# 4.0) allow you to specify the names for each method parameter:

```<code>array.Sort(from:= fromIndex, to:= toIndex);
</code>```

Title: Is there a language that allows this syntax: add(elements)at(index);

Body:
Possible Duplicate:

  Is there a language out there in which parameters are placed inside method name?

Does a language exist with such a syntax? If not, what are some of the limitations/disadvantages to this syntax in case I want to write a language that supported it?

Some examples:

```<code>sort(array, fromIndex, toIndex);
</code>```

vs

```<code>sort(array)from(index1)to(index2);
</code>```

Method signature would like this:

```<code>sort(SomeType[] arr)from(int begin)to(int end){
...
}
</code>```

Update:

Because there might be some confusion, I'd like to clarify...
I meant this question as a general idea like this (not specific to sorting and possibly using keywords like from and to):

In JAVA(like language):

```<code>void myfancymethod(int arg1, String arg2){
...
}

myfancymethod(1, "foo");
</code>```

In imaginary language:

```<code>void my(int arg1)fancy(String arg2)method{
...
}

my(1)fancy("foo")method;
</code>```

Body:
If you create a fluent interface, you can write it more or less like this:

array.From(fromIndex).To(toIndex).Sort();

But method overload resolution will give you simpler syntax:

array.Sort(fromIndex, toIndex);

...and if you name things sensibly, it's still self-describing.

If you still need the descriptive verbiage, some languages (like C# 4.0) allow you to specify the names for each method parameter:

array.Sort(from:= fromIndex, to:= toIndex);


答:
In Agda an identifier containing underscores can be used infix. Consider the declaration of if:

```<code>if_then_else_ : {A : Set} -> Bool -> A -> A -> A
if true  then x else y = x
if false then x else y = y
</code>```

Body:
In Agda an identifier containing underscores can be used infix. Consider the declaration of if:

if_then_else_ : {A : Set} -> Bool -> A -> A -> A
if true  then x else y = x
if false then x else y = y


答:
There is much talk about ORM's being storage-independent, under the theory that you might want to change out the underlying data store.  In practice this hardly ever happens, and it's a lot of work when it does; it's not simply a matter of unplugging one vendor's RDBMS and plugging in another.

You can stay vendor-independent by sticking to a dialect of SQL that works with all the vendors, but in the end you're still talking about a SQL database (as opposed to a key-value store like BigTable), and if you need SQL's unique capabilities, then you're pretty much stuck with an RDBMS.

Notice that the farther away you get from SQL, the less shape your data objects have, and the more work you have to do yourself.

Title: ResourceSerializable: an alternate to ORM and ActiveRecord

Body:
A few opinionated reasons I don't like the traditional ORM and ActiveRecord patterns:

They work only with a database. Sometimes I'm dealing with objects from an API and other objects from a database.  All the implementations I have seen don't allow for that. Feel free to clue me in if I'm wrong on this.

They are brittle. Changes in the database will likely break your implemenation.  Some implementations can help reduce this, but a few of the ones I've seen don't.

Their very design is influenced by the database. If I want to switch to using an API, I'll have to redesign the object to get it to work (likely).

It seems to violate the single-responsibility pattern. They know what they are and how they act, but they also know how they are created, destroyed and saved?  Seems a bit much.

What about an approach that is somewhat more familiar in PHP: implementing an interface?  In php 5.4, we'll have the JsonSerializable interface that defines the data to be json_encoded, so users will become accustomed to this type of thing. What if there was a ResourceSerializable interface? This is still an ORM by name, but certainly not by tradition.

```<code>interface ResourceSerializable {
    /**
     * Returns the id that identifies the resource.
     */
    function resourceId();

    /**
     * Returns the 'type' of the resource.
     */
    function resourceType();

    /**
     * Returns the data to be serialized.
     */
    function resourceSerialize();
}
</code>```

Things might be poorly named, I'll take suggestions.

Notes:

ResourceId will work for API's and databases.  As long as your primary key in the database is the same as the resource ID in the API, there is no conflict.  All of the API's I've worked with have a unique ID for the resource, so I don't see any issues there.

ResourceType is the group or type associated with the resource.  You can use this to map the resource to an API call or a database table.  If the ResourceType was person, it could map to /api/1/person/{resourceId} and the table persons (or people, if it's smart enough).

resourceSerialize() returns the data to be stored. Keys would identify API parameters and database table columns.

This also seems easier to test than ActiveRecord / Orm implemenations. I haven't done much automated testing on traditional ActiveRecord/ORM implemenations, so this is merely a guess.  But it seems that I being able to create objects independently of the library helps me.  I don't have to use load() to get an existing resource, I can simply create one and set all the right properties.  This is not so easy in the ActiveRecord / Orm implemenations I've dealt with.

Downsides:

You need another object to serialize it. This also means you have more code in general as you have to use more objects.

You have to map resource types to API calls and database tables. This is even more work, but some ORMs and ActiveRecord implementations require you to map objects to table names anyway.

Are there other downsides that you see?

Does this seem feasible to you?

How would you improve it?

Note: I almost asked this on StackOverflow because it might be too vague for their standards, but I'm still not really familiar with programmers.stackexchange.com, so please help me improve my question if it doesn't shape up to standards here.


答:
My answer's pretty simple: not binaries. By implication, almost everything else.

(Definitely not database backups or schema migrations or user-data, though.)


答:
Source control is a change tracking mechanism.  Use it when you want to know who changed what and when.

Source control is not free.  It adds complexity to your workflow, and requires training for new collegues.  Weigh the benefits against the cost.

For example, it can be tough to control databases.  We used to have a system where you had to manually save definitions in a text file and then add those to source control.  This took a lot of time and was unreliable.  Because it was unreliable, you could not use it to set up a new database, or to check at what time a change was made.  But we kept it for years, wasting countless hours, because our manager thought "all things should be in source control".

Source control is not magic.  Try it, but abandon it if it doesn't add enough value to offset the cost.


问:
Is there a version control system that can show changes to a specific method or function?
Sometimes it would be nice to be able to say something like:

```<code>(git|svn|hg|etc) diff Foo.c:main
(git|svn|hg|etc) log log Foo.c:main
</code>```

to see the changes made to a specific function within a source file since the last commit, or the complete history of changes. My question is two-fold:

Does something exist that does this?

Would such a tool be practical? It would have to do some simple parsing of the code at each revision in order to compare different versions of the function; would the overhead be too much for it to be efficient?

答:
As far as I know, it does not. One might, but I would not expect it to be production quality if it did.

I don't think it is practical, but not for the reason you listed. It is not practical because the VCS would have to be language aware to support that kind of functionality. Essentially, you would need to embed something to parse the language text (one of the big steps a compiler does). This adds a lot of extra weigh to you VCS, which is already doing a fairly complex job.

But more importantly, you would need to do the same thing for every language you want to support. A VCS who's selling point only works on C code is not going to get a lot of traction. Even if you ignore all the obscure languages, it would be a massive undertaking to support even the top 10 languages.

And as Robert pointed out, being able to immediately jump to a method is not a huge gain over having to manually jump to the method within the diff tool.


问:
What Part of Your Project Should be in Source Code Control?
A fellow developer has started work on a new Drupal project, and the sysadmin has suggested that they should only put the sites/default subdirectory in source control, because it "will make updates easily scriptable."  Setting aside that somewhat dubious claim, it raises another question -- what files should be under source control?  And is there a situation where some large chunk of files should be excluded?

My opinion is that the entire tree for the project should be under control, and this would be true for a Drupal project, rails, or anything else. This seems like a no-brainer -- you clearly need versioning for your framework as much as you do for any custom code you write.

That said, I would love to get other opinions on this.  Are there any arguments for not having everything under control?

答:
Anything your automated build does generates does not go in source control. Anything that requires no modification during build does go in source control. It's that simple.

For example, the following don't go in source control:

generated code

generated binaries

anything created by your build

anything created at runtime by your service, process, web application

What does go in source control:

anything a human creates

anything that is created by another person or group (e.g. a third-party in-house library where source control is distributed or an open-source project's binaries).

scripts and other source that create things like a database (i.e. how would you recreate the db if all the DBA's go AWOL).

These rules-of-thumb are predicated on the notion that whatever is in source control could be modified by a human and could take someone's valuable time to understand why it's there.


答:
I'm not aware of any language with syntax quite like that, although QBasic and Visual Basic had some built-in statements with custom syntax, like "LINE (10,10)-(80,95)".

I like your idea as a general-purpose feature. I think "sort(array from index1 to index2)" would look slightly more attractive and be easier to type, and presumably you're talking about a single function call here, which is not as clear if several sets of parenthesis are required. Parsing might be challenging: "from" and "to" basically represent commas in the syntax I just suggested, but the parser wouldn't know that for certain until the function name is resolved. However, it could be parsed as a sequence of expressions: (array), (from), (index1), (to), (index2) where (from) and (to) are replaced with commas during semantic analysis.

Instead of defining "sort" in a special way, you could also envision this as a way of representing named parameters:

```<code>sort (SomeType[] arr, int from, int to) { ... } // declaration
sort (arr from: index1 to: index2); // possible call syntax 1
sort (arr, from index1, to index2); // possible call syntax 2
sort (arr from index1 to index2); // possible call syntax 3
</code>```

Body:
I'm not aware of any language with syntax quite like that, although QBasic and Visual Basic had some built-in statements with custom syntax, like "LINE (10,10)-(80,95)".

I like your idea as a general-purpose feature. I think "sort(array from index1 to index2)" would look slightly more attractive and be easier to type, and presumably you're talking about a single function call here, which is not as clear if several sets of parenthesis are required. Parsing might be challenging: "from" and "to" basically represent commas in the syntax I just suggested, but the parser wouldn't know that for certain until the function name is resolved. However, it could be parsed as a sequence of expressions: (array), (from), (index1), (to), (index2) where (from) and (to) are replaced with commas during semantic analysis.

Instead of defining "sort" in a special way, you could also envision this as a way of representing named parameters:

sort (SomeType[] arr, int from, int to) { ... } // declaration
sort (arr from: index1 to: index2); // possible call syntax 1
sort (arr, from index1, to index2); // possible call syntax 2
sort (arr from index1 to index2); // possible call syntax 3


答:
Anything that you need to work and can change needs to be versioned some way or another. But there is rarely a need to have two independent systems keep track of it.

Anything generated in a reliable way can usually be attached to a source version - therefore it doesn't need to be tracked independantly: generated source, binaries that are not passed from a system to another, etc.

Build logs and other stuff that probably nobody cares about (but you never know for sure) are usually best tracked by whoever is generating it: jenkins, etc.

Build products that are passed from one system to another need to be tracked, but a maven repo is a good way to do it - you don't need the level of control a source control provides. Deliverables are often in the same category.

Whatever remains (and at this point, there should be little more than source files and build server configuration) goes into source control.


问:
Why binding is not a native feature in most of the languages?
IMHO binding a variable to another variable or an expression is a very common scenario in mathematics. In fact, in the beginning, many students think the assignment operator(=) is some kind of binding.  But in most of the languages, binding is not supported as a native feature. In some languages like C#, binding is supported in some cases with some conditions fulfilled.

But IMHO implementing this as a native feature was as simple as changing the following code-

```<code>int a,b,sum;
sum := a + b;
a = 10;
b = 20;
a++;
</code>```

to this-

```<code>int a,b,sum;
a = 10;
sum = a + b;
b = 20;
sum = a + b;
a++;
sum = a + b;
</code>```

Meaning placing the binding instruction as assignments after every instruction changing values of any of the variable contained in the expression at right side. After this, trimming redundant instructions (or optimization in assembly after compilation) will do.

So, why it is not supported natively in most of the languages. Specially in the C-family of languages?

Update:

From different opinions, I think I should define this proposed "binding" more precisely-

This is one way binding. Only sum is bound to a+b, not the vice versa.

The scope of the binding is local.

Once the binding is established, it cannot be changed. Meaning, once sum is bound to a+b, sum will always be a+b.

Hope the idea is clearer now.

Update 2:

I just wanted this P# feature. Hope it will be there in future.

答:
I think what you're describing is called a Spreadsheet:

```<code>A1=5
B1=A1+1
A1=6
</code>```

...then evaluating B1 returns 7.

EDIT

The C language is sometimes called "portable assembly".  It's an imperative language, whereas spreadsheets, etc., are declarative languages.  Saying B1=A1+1 and expecting B1 to re-evaluate when you change A1 is definitely declarative.  Declarative languages (of which functional languages are a subset) are generally considered higher level languages, because they're farther away from how the hardware works.

On a related note, automation languages like ladder logic are typically declarative.  If you write a rung of logic that says output A = input B OR input C it's going to re-evaluate that statement constantly, and A can change whenever B or C changes.  Other automation languages like Function Block Diagram (which you might be familiar with if you've used Simulink) are also declarative, and execute continually.

Some (embedded) automation equipment is programmed in C, and if it's a real-time system, it probably has an infinite loop that re-executes the logic over and over, similar to how ladder logic executes.  In that case, inside your main loop you could write:

```<code>A = B || C;
</code>```

...and since it's executing all the time, it becomes declarative.  A will constantly be re-evaluated.

Body:
I think what you're describing is called a Spreadsheet:

A1=5
B1=A1+1
A1=6

...then evaluating B1 returns 7.

EDIT

The C language is sometimes called "portable assembly".  It's an imperative language, whereas spreadsheets, etc., are declarative languages.  Saying B1=A1+1 and expecting B1 to re-evaluate when you change A1 is definitely declarative.  Declarative languages (of which functional languages are a subset) are generally considered higher level languages, because they're farther away from how the hardware works.

On a related note, automation languages like ladder logic are typically declarative.  If you write a rung of logic that says output A = input B OR input C it's going to re-evaluate that statement constantly, and A can change whenever B or C changes.  Other automation languages like Function Block Diagram (which you might be familiar with if you've used Simulink) are also declarative, and execute continually.

Some (embedded) automation equipment is programmed in C, and if it's a real-time system, it probably has an infinite loop that re-executes the logic over and over, similar to how ladder logic executes.  In that case, inside your main loop you could write:

A = B || C;

...and since it's executing all the time, it becomes declarative.  A will constantly be re-evaluated.


答:
You could write your example in Tcl like this if you wrote your own sort function:</p>

```<code>sort array from $index1 to $index2
</code>```

Body:
You could write your example in Tcl like this if you wrote your own sort function:

sort array from $index1 to $index2


问:
What are the disadvantages of test-first programming?
It's all the rage nowadays. "Everyone" recommends it. That in and of itself makes me suspicious.

What are some disadvantages you have found when doing test-first (test-driven) development? I'm looking for personal experiences from knowledgeable practitioners--I can read the hypothetical musings of a hundred wannabes elsewhere on the internet.

I ask not because I am looking to hate TDD, but because it is my job to improve software development process, and the more we can learn about the problems people encounter, the better chance we have of improving the process.

答:
For me there's some deep psychological problem with tests whenever I try to apply them extensively, as in TDD: if they're there, I code sloppily because I trust that the tests will catch any problems. But if there are no tests to provide a safety net, I code carefully, and the result is invariably better than with tests.

Maybe it's just me. But I've also read somewhere that cars with all kind of safety bells & whistles tend to crash more (because the drivers know that the safety features are there), so maybe this is something to acknowledge; TDD can be incompatible with some individuals.


问:
Why are cyclic imports considered so evil?
Seriously, what's the big deal about having a few cycles in one's import graph?  I see it as a lesser evil than having super fine grained imports that make keeping track of where to look for what code an absolute nightmare.</p>

答: My big feeling on cyclical module dependencies is that if those two modules really do depend on one another, perhaps they should be one module.  You can't use one without the other, so what's the point of splitting them up?</p>


答:
I did support for a couple of years for my first company out of college. What got me to sign up for a couple of years was:

The required career path for
becoming a Software Engineer.

I needed the time to brush up on the
company's main language (Fortran,
Circa 1989)

I wasn't married so I could quit if
I found I didn't like the company or
the job.

Title: How to you "sell" support as an career option

Body:
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)