问:
Can you use proprietary libraries in MPL 2.0 licensed source?
Is it legal to use a third party library in a software project that is itself licensed under MPL 2.0?

So some potential project hierarchies would look like this

Library Project [MPL 2.0] (Open Source, Distributed)

Third party library [Proprietary] (Closed source, not distributed)

Someone else's project [MPL 2.0] (Open source, distributed)

Library Project [MPL 2.0] (Open Source, Distributed)

Third party library [Proprietary] (Closed source, not distributed)

My practical feeling is that this is fine otherwise there could be no use of this license on many platforms whose base libraries are proprietary, like on iOS for example.  The only difference being that these libraries are distributed to registered developers.

答:
It should be sufficient to just read the MPL.

3.2. If You distribute Covered Software in Executable Form then:

Such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and

You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License.

3.3. Distribution of a Larger Work

You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).

So the MPL isn't viral in the sense that the GPL is. MPL software can't be re-licensed under your own incompatible license, but you can distribute it with any other code under any other license as long as the other license doesn't conflict with the MPL (as the GPL does), and as long as you still distribute the MPL source.

Also, if you're not distributing the software to anyone, then the discussion is moot, as you're not required to distribute source to anyone to whom you don't distribute binaries.


问:
business logic: client-side vs. server side
Let's say 3-5 years ago (more or less) n-tier application on the server side - and some javascript/html/CSS for the UI was a basic approach for web development.

Nowadays we can see that traditional web development paradigm changes a lot. Each day I saw more and more application who do not have server side in traditional way. They just consume some services (data-service, auth-service, etc.) but the business logic placed on client side. Also already a lot of javascript frameworks creates for simplify development according such model (Angular, Backbone, etc.)

What are the main benefits and disadvantages of new model versus traditional approach?

答:
In addition to what @James Anderson said, if you are working on a system that uses shared database tables, you want to avoid repeating the business rules on the server and on every type of client you choose to use. In some cases you have to, as the case is in validation, but other business rules should not be repeated if possible. Attempting to replicate the same rules in different languages is error prone. Also, sometimes you need to extract several pieces of data and pull this data to the client to perform your validation. This goes against responsiveness.

INMO, separation of concerns is to be considered a priority in design when responsiveness is not a critical issue.

One subject I avoided raising is "what do you do with clients that turn JS off?"...

ContentLicense: CC BY-SA 3.0


问:
Prefer examples over documentation. Is it a behavioral problem?
Whenever I come across a new API or programming language or even simple Linux man pages, I always (ever since I remember) avoided them and instead lazily relied on examples for gaining understanding of new concepts.

Subconsciously, I avoid documentation/APIs whenever it is not straightforward or cryptic or just plain boring. It's been years since I began programming and now I feel like I need to mend my ways as I now realize that I'm causing more damage by refraining from reading cryptic/difficult documentation as it is still a million times better than examples as the official documentation has more coverage than any example out there. Even after realizing that examples should be treated as "added" value instead of the "primary" source for learning.

How do I break this bad habit as a programmer or am I overthinking?

答:
The habit of relying in preference on examples has nothing wrong: for you, it's just the fastest way to get your answer. Moreover, examples are visual. It's easier to parse visually an example rather than read paragraphs of text and extract the information you need.

Example:

In order to list the products, one should use Index action of the Products controller, given that GET is the only possible verb here (see [Affecting products] for more information about the actions used to create, modify and delete the products from the database).

In order to obtain detailed information about a specific product, append its unique identifier to the end of the URI. If you want to get the list of every product available, don't append anything. You may also use filters, as described in the [REST filters for selecting data] section of the manual. Note that the list of products is limited to one thousand items. [Pagination] can be used to walk through the entire list, given that each page is still limited to one thousand items.

You may also want to force the service to refresh the quantities in stock. This is done by setting the refresh-quantities to one.

is detailed, but boring and barely readable. The fact that you need to follow links makes things even worse. If we append some samples, it becomes much easier to understand:

GET Products/Index/

GET Products/Index/12345/

GET Products/Index/?skip=100&take=20

GET Products/Index/?category=12

GET Products/Index/?price=0..39.90

GET Products/Index/?category=12&skip=100&take=20

The fact that you use only the examples may be a problem. Don't plainly stop using the examples, but remember that once you got the idea, a more verbose documentation may help. For example, the sample above doesn't show that the list of products is limited to 1 000: you have to read the documentation for that.

When do you know that you should read the documentation?

Every time the API or the library is not behaving as you expected. For example, you grab the sample and do:

GET Products/Index/?skip=6000&take=3000

For some reason, it returns less than 3 000 items, while you have over twenty thousand products in your database. Here, the API is not behaving like you expected, so it's a good time to read the detailed documentation.


问:
Is it normal for programmer to work on multiple projects simultaneously
On a current job I have two projects to work on. First is very huge system and the second one is smaller but it also big (first project is being developed for 12 years, second for 4 years).

At first I was working only on first project and was trying to get used to it. Then I was moved to second project and tried there, so my knowledge about first project became shady. Now I have to work on both projects at the same time.

It's very hard for me because despite they both use java, they use different frameworks and the amount of code and business-logic to understand is very big so I really can't hold both that projects in my head.

Is it normal and I should get used to it, although my expertise became very squashy, what won't happen if I would work only on a single project? Or should I raise a concern or maybe change employer?

答:
I understand how you are feeling, it is hard to make new employers understand the development processed involved, especially if you employer is not development focused.

The issue is they see 3 Jobs being worked on together more of a money maker than 1 at a time, and the statistics show 40% decrease in performance. Thats 40% loss in profit..

I have previousley worked for a orgonisation that allowed me to focus on 1 large project at a time with small jobs in between, tickets and support etc. We worked on a deal where 8:00-10:00AM was Ticket and support for current systems which come through via email / phone / helpdesk then 10:00 - 16:30 or your finish time was full solid development. This worked extreemley well, because we had a helpdesk to take the calls and emails, I was able to do the tickets in the morning and develop the rest of the day. The issue is if you have poor management. A manager makes all of this happen, and without their support or understanding of the challenges you face daily they are ignorant to the fact.

I have been thankful especially in my last job of the support and understanding from my manager, it made my life easier, less stress and we still got ALL of the work done..

Another issue is, Boss's love money, they see projects in money, When they have 5 Projects for £20,000 all on at the same time (and you are a solo developer) thats £100,000 in the books.. Looks great on paper but can damage company reputation when these are not met, deadlines are missed and systems are buggy because of lack of concentration.

I sympathise with you completely, Im in your position right now.


问:
What makes a hashing algorithm "secure"?
After reading this interesting question, I felt like I had a good idea of which insecure hashing algorithm I'd use if I needed one, but no idea why I might use a secure algorithm instead.

So what is the distinction?  Isn't the output just a random number representing the hashed thing?  What makes some hashing algorithms secure?

答:
Use the right algorithm for the task at hand.

CRCs are used for error detection/correction.

Cryptographic message digests such as SHA2 are used as a building block for cryptographic constructs (digital signatures, MACs, key derivation/password hashing functions) and security protocols.

In hash tables/dictionaries/maps use SipHash.

What you call insecure hashing algorithms should not be used in hash tables, as proven by the following CVE entries: CVE-2003-0364, CVE-2011-4461, CVE-2011-4838, CVE-2011-4885, CVE-2011-4462, CVE-2011-4815, CVE-2012-0840, CVE-2012-5371, CVE-2012-5374, CVE-2012-5375


问:
Is it more secure to hash a password multiple times?
I've read a few times that when storing passwords, it's good practice to 'double hash' the strings (eg. with md5 then sha1, both with salts, obviously).

I guess the first question is, "is this actually correct?" If not, then please, dismiss the rest of this question :)

The reason I ask is that on the face of it, I would say that this makes sense. However, when I think about it, every time a hash is rehashed (possibly with something added to it) all I can see is that there is a reduction in the upper bound on the final 'uniqueness'... that bound being related to the initial input.

Let me put it another way: we have x number of strings that, when hashed, are reduced to y possible strings. That is to say, there are collisions in the first set. Now coming from the second set to the third, is it not possible for the same thing to occur (ie. collisions in the set of all possible 'y' strings that result in the same hash in the third set)?

In my head, all I see is a 'funnel' for each hash function call, 'funneling' an infinite set of possibilities into a finite set and so on, but obviously each call is working on the finite set before it, giving us a set no larger than the input.

Maybe an example will explain my ramblings?
Take 'hash_function_a' that will give 'a' and 'b' the hash '1', and will give 'c' and 'd' the hash '2'. Using this function to store passwords, even if the password is 'a', I could use the password 'b'.

Take 'hash_function_b' that will give '1' and '2' the hash '3'. If I were to use it as a 'secondary hash' after 'hash_function_a' then even if the password is 'a' I could use 'b', 'c' or 'd'.

On top of all of that, I get that salts should be used, but they don't really change the fact that each time we are mapping 'x' inputs to 'less than x' outputs. I don't think.

Can someone please explain to me what it is that I am missing here?

Thanks!

EDIT: for what it's worth, I don't do this myself, I use bcrypt. And I'm not really concerned about whether or not it's useful for 'using up cycles' for a 'hacker'. I genuinely am just wondering whether or not the process reduces 'security' from a hash collision stand point.

答:
Do not try to write your own password hashing scheme unless your are willing to take a course in cryptography and/or security engineering.

You should use a well established implementation of password hashing which in turn should use a key derivation function (KDF) such as PBKDF2, bcrypt, scrypt or the newer Argon2.

Good KDFs include a workfactor, usually a number of iterations, in order to increase the cost of offline attacks. One could say that these KDFs hash the password multiple times, using the same algorithm each time. There is no point in using multiple message digest algorithm, as pointed out by others.


问:
Strategy for code review before merge to master from feature branches
Me and my team use feature branches (with git). I'm wondering which is the best strategy for code review before merge to master.

I checkout a new branch from master, lets call it fb_#1

I commit a few times and than want to merge it back to master

Before I merge someone is supposed to make a code review

Now there are 2 possibilities:

1st

I merge master to fb_#1 (not fb_#1 to master) to make it as up-to-date as possible

A teammate reviews changes between master head and fb_#1 head

If fb_#1 is ok we merge fb_#1 to master

Pros: no obsolete code in review

Cons: if someone else merges something between "1." and "2." his changes appear in the review, though they belong to another review.

2nd

A teammate reviews changes between the point of checkout (git merge-base master fb_#1) and fb_#1 head

Pros: we see exactly what was changed during working on the feature branch

Cons: some obsolete code may appear in the review.

Which way do you think is better and why? Maybe there is another more suitable approach?

答:
There's a variation of your 1st option:

merge master to fb_#1 (not fb_#1 to master) to make it as up-to-date as possible

A teammate reviews changes between master at the point you merged and fb_#1 head

If fb_#1 is ok we merge fb_#1 to master

quick check that the merge is ok

eg.

```<code>... ma -- ... -- mm -- ... -- mf  <- master
      \            \         /
       f1 ... fn -- fm -----      <-- fb_#1
</code>```

where:

ma is the ancestor of master and fb_#1.

fn is the last change on your branch

mm is the commit that was master/HEAD at the time you merged onto your branch (giving fm).

So, you compare mm and fm in your initial review, and then quickly check after merging back mf to make sure nothing significant changed on master during steps 1-3. This seems to have all of the pros and none of the cons for the initial review.

This assumes the review is quick compared to the normal frequency of changes pushed to master, so fm -> mf would often be a fast-forward.

If that is not the case, for whatever reason, the cons will just move from the initial review to the post-merge review, and it may be simpler just to merge directly onto master and do a single review there.

Body:
There's a variation of your 1st option:

merge master to fb_#1 (not fb_#1 to master) to make it as up-to-date as possible

A teammate reviews changes between master at the point you merged and fb_#1 head

If fb_#1 is ok we merge fb_#1 to master

quick check that the merge is ok

eg.

... ma -- ... -- mm -- ... -- mf  <- master
      \            \         /
       f1 ... fn -- fm -----      <-- fb_#1

where:

ma is the ancestor of master and fb_#1.

fn is the last change on your branch

mm is the commit that was master/HEAD at the time you merged onto your branch (giving fm).

So, you compare mm and fm in your initial review, and then quickly check after merging back mf to make sure nothing significant changed on master during steps 1-3. This seems to have all of the pros and none of the cons for the initial review.

This assumes the review is quick compared to the normal frequency of changes pushed to master, so fm -> mf would often be a fast-forward.

If that is not the case, for whatever reason, the cons will just move from the initial review to the post-merge review, and it may be simpler just to merge directly onto master and do a single review there.


问:
Best way to plan programming for small teams?
I am the Director of a small startup organisation. We currently have two programmers (one experienced, one less experienced) who are building a web application platform.

One of the greatest challenges so far is the planning process. The programmers usually are in charge of planning their own work, but we keep exceeding their self-imposed deadlines. For instance, a task that they estimate will take 2 days, ends up taking 8 days.

For me it is hard to support them in planning, as I lack the technical know-how to precisely estimate how long a certain task will last.

Do you have any idea:

What is the reason for this, is this common for programmers?

What I can do to support them in planning? Are there any methods or tools that are useful to programmers in small teams?

答:
The general techniques are somewhat common-sense, the important thing to know is that they don't require much technical expertise.

The starting point with planning is to identify the exact problem that needs to be solved and have a clear and unambiguous requirement. If you don't have that, your estimates will be incorrect. Having this documented in some kind of feature specification before anyone starts writing code will mean that any questions that need to be asked will have been asked before coding begins. This is a surprisingly effective timesaver. Going back and clarifying requirements breaks up one's flow as a programmer and waiting for responses can block progress.

Once you have identified the requirement you need to identify the work tasks involved in resolving it. This is a classic divide and conquer exercise - any task that can be broken down further needs to be broken down further.

In a larger team  you can use estimation poker to get an estimate based on the experience of everyone involved. That doesn't work as well in a smaller team, but it is still useful to get an independent estimate from both your developers and maybe to include one from yourself too- your lack of specific expertise can be helpful here because in explaining to you what the task involves from their perspective, the development team will probably grasp the problem better.

With a smaller team it can help to get a best/expected/worst case estimate for each task, that gives you a range of values, but if you are getting a lot of overrun estimates, you can incline towards the worst case until your devs learn to estimate more accurately.

In a small shop, developers often end up doubling as sysadmins, support team and even testers ( although of all the things they could be doing, testing is the one you should try to avoid at all costs ) so you need to account for that. Figure out how much of their time your developers actually spend working on new features and factor that into your estimates. If a task is estimated at 2 days but your devs are only able to work on new development 60% of the time, then you are going to need 4 days for it to be finished. You might be able to help with this as well by controlling the pipeline of other tasks they need to handle so that non-urgent admin or support tasks can be batched together somewhat rather than being handled on an ad-hoc basis. A lot of programmers ( certainly including myself on this one ) are not great time managers, so anything you can do to lend a hand in that respect will help. Single-tasking is always easier for programmers than multi-tasking. Blocking out time during the day can also help with this.

Keep a record - each time you have a planning session, record the estimates and actuals. You can then use this a) as a guide for how much to inflate their estimates by during planning and b) to help them refine their estimation skills. At the end of each iteration ( or whatever equivalent you have ) the whole team should review the work that was done and figure out why it took longer than expected so that this can be incorporated in future estimates. This needs to be a blameless task - you seem to have the right attitude here but this answer may be around a while so I'll make the observation. If someone says "I made a mistake here" you can turn that into "what could you have done better", but telling people they were too slow or got things wrong will only make matters worse.

I am aware of no silver bullet for this type of problem but the biggest factor is communication- which is actually easier with a smaller team -  and using feedback to refine your collective skills.


问:
Serializing Data Structures in C
I've recently read three separate books on algorithms and data structures, tcp/ip socket programming, and programming with memory. The book about memory briefly discussed the topic of serializing data structures for the purposes of storing it to disk, or sending it across a network. I can't help but wonder why the the other two books didn't discuss serialization at all.

After an unsuccessful web/book search I'm left wondering where I can find a good book/paper/tutorial on serializing data structures in C? Where or how did you learn it?

答:
It probably wasn't covered in your books because there are so many possible variations, all different trade-offs between runtime speed, ease of use, and portability.

For example, 1 and 3 are pretty much opposite ends of the spectrum, and 2 just illustrates the number of small variations possible between them:

Don't serialize, just copy the raw bytes

this leaves you dependent on architecture and compiler details (endianness, padding & alignment, floating-point representation), so is very non-portable

it does no (extra) work at all, so is very fast

it doesn't handle any form of indirection, so only works for flat, self-contained POD structures

it's an absolute pain to decode, if you need it for debugging

as 1, but explicitly specify padding, alignment and endianness

this is now portable, at the fairly minimal extra cost of byte-order conversions (on hosts with different native byte order to that specified) and the requirement to force appropriate alignment (which may not be optimal on all architectures)

serialize everything to a text format like XML or JSON

this is very portable

and very slow (relatively)

you can make it handle indirection, including circular references, if you need

it's really easy to read serialized messages directly

Oh, and I learnt about this stuff (all of the above, plus CORBA, ASN.1 and ProtocolBuffers) by implementing existing documented protocols.

If your main focus is on portability rather than speed, something towards the #3 end of the spectrum is probably a better fit. As for how you build that in the first place, it's almost more a question about reflection.

Title: Serializing Data Structures in C


答:
What is the reason for [their estimate of 2 days taking 8 days], is this common for programmers?

It is, if:

It isn't actually clear what they're supposed to do, so they take more time getting it right (and they should then say so, not guess about how long it will take)

They're unfamiliar with the task at hand (then they should mention that and include research in the estimate)

The integration of the finished task with the larger product takes longer than anticipated (which might mean the product's architecture is inferior)

The developer likes to reinvent the wheel, and doing so stumbles over problems that have been solved by others, freely available in a library

Changes are introduced by the product owner while the task is being implemented, requiring a different approach and the redo of work already done

The developers don't work in a productive environment (so when at home they guess it would take two days, but at work they'll require eight to compensate for all the distractions)

To name a few things.

Perhaps it's best to ask your developers why they think their estimates are way off. :-)

Title: Best way to plan programming for small teams?

Body:
I am the Director of a small startup organisation. We currently have two programmers (one experienced, one less experienced) who are building a web application platform.

One of the greatest challenges so far is the planning process. The programmers usually are in charge of planning their own work, but we keep exceeding their self-imposed deadlines. For instance, a task that they estimate will take 2 days, ends up taking 8 days.

For me it is hard to support them in planning, as I lack the technical know-how to precisely estimate how long a certain task will last.

Do you have any idea:

What is the reason for this, is this common for programmers?

What I can do to support them in planning? Are there any methods or tools that are useful to programmers in small teams?


答:
3rd

You rebase the branch on master to both make it up-to-date and keep the changes separate.

This creates a new history of the branch. It will be new revisions with new IDs that will have the same content, but will be derived from latest master and will not link to the old revisions. The old revisions are still accessible in "reflog" if you need to refer to them e.g. because you find you made mistake in conflict resolution. Besides that they are worthless. Git by default prunes the reflog after 3 months and discards the old revisions.

You use interactive rebase (git rebase -i and git commit --amend) to reorder, edit and clean up the changes so each does a logically closed change.

This again creates new history, this time with the added benefit that you can restructure the changes to make most sense during review.

Pros:

no obsolete code in review

we see exactly what was changed during working on the feature branch

Cons:

a bit more work

you have to take care not to rebase anything that is already merged or that you shared and the recipient does not expect it to be rewound.

Usually the extra work means you review the code thoroughly yourself first and that will catch many problems too.

This is what Linux and Git do. And it's not unusual to see series of 20 to 25 patches being submitted for review and rewritten several times over in those projects.

Actually Linux did it from early on in the project when their version control of choice was tarballs and patches. When many years later Linus set out to create git, it was the prime reason for implementing the rebase command and it's interactive variant. Also because of it git has separate notion of author and committer. Author is who first created the revision and committer is who last touched it. Since in both Linux and Git the patches are still submitted by email, the two are almost never the same person.

Title: Strategy for code review before merge to master from feature branches

Body:
Me and my team use feature branches (with git). I'm wondering which is the best strategy for code review before merge to master.

I checkout a new branch from master, lets call it fb_#1

I commit a few times and than want to merge it back to master

Before I merge someone is supposed to make a code review

Now there are 2 possibilities:

1st

I merge master to fb_#1 (not fb_#1 to master) to make it as up-to-date as possible

A teammate reviews changes between master head and fb_#1 head

If fb_#1 is ok we merge fb_#1 to master

Pros: no obsolete code in review

Cons: if someone else merges something between "1." and "2." his changes appear in the review, though they belong to another review.

2nd

A teammate reviews changes between the point of checkout (git merge-base master fb_#1) and fb_#1 head

Pros: we see exactly what was changed during working on the feature branch

Cons: some obsolete code may appear in the review.

Which way do you think is better and why? Maybe there is another more suitable approach?


问:
How large non-OO code bases are managed?
I always see abstraction is a very useful feature the OO provides for managing the code-base. But how are large non-OO code bases are managed? Or do those just become a "Big Ball of Mud" eventually?

Update:

It seemed everyone is thinking 'abstraction' is just modularization or data-hiding. But IMHO, it also means the use of 'Abstract Classes' or 'Interfaces' which is a must for dependency-injection and thus testing. How non-OO code bases manage this? And also, other than abstraction, the encapsulation also helps a lot to manage large code bases as it define and restrict the relation between data and functions.

With C, it is very much possible to write pseudo-OO code. I don't know much about other non-OO languages. So, is it THE way to manage large C code bases?

答:
Realistically either infrequent changes (think Social Security retirement calculations) and/or deeply ingrained knowledge because the people maintaining such as system have been doing so for awhile (cynical take is job security).

Better solutions are repeatable validation, by which I mean automated test (e.g. unit testing) and human testing that follows proscribed steps (e.g. regression testing) "as opposed to click around and see what breaks".

To start moving toward some sort of automated testing with an existing codebase I recommend reading Michael Feather's Working Effectively with Legacy Code, which details approaches for bringing existing codebases until some sort of repeatable testing framework OO or not. This leads to the sort of ideas others have answered with such as modularization, but the book describes the right approach to doing so while not breaking things.

ContentLicense: CC BY-SA 2.5


答:
There is actually a third possbility—and most probably plenty of others, since GIT is more an implementation of a SCM framework than an implementation of a SCM methodology.  This third possibility is based on rebase.

The rebase GIT subcommand takes a series of commit (typically from your branching point to the tip of your topic branch topic) and replay them somewhere else (typically at the tip of your integration branch, e.g. master).  The rebase subcommand produces new commits, which gives the opportunity of rearranging commits in a form that is easier to review.  This yields a new series of commit, similar to what topic used to be but appearing rooted at the top of the integration branch.  This new branch is still called topic by GIT, so that the old reference is discarded.  I informally label topic-0 the original state of your branch and topic-1 and so on its various refactoring.

Here is my suggestion for your topic branch:

(Optional step) You interactively rebase your topic branch topic on its branching point (see --fixup option for commit and the -i and --autosquash options on rebase), which gives you the opportunity to rewrite your commits in a way that is easier to review.  This results in a branch topic-1.

You rebase your topic branch at the top of your integration branch, is similar to doing a merge, but “does not pollute” history with a merge that is merely a software engineering artifact.  This results in a branch topic-2.

Send topic-2 to a teammate that reviews it against the tip of master.

If topic-2 is okay then merge it to master.

NOTE The branches—where branch refers to the commit tree—will all be called the same by GIT, thus, at the end of the process, only the branch topic-2 has a name in GIT.

Pros:

No obsolete code in review.

No spurious “foreign merges” reviews (the phenomenon you described in 1st).

Opportunity to rewrite commits in a clean way.

Cons:

Instead of one branch topic-0, there is three branches artifacts topic-0,  topic-1 and topic-2 that are created in the commit tree.  (Though at any time, only one of them has a name in GIT.)

In your 1st scenario «if someone merged something between "1." and "2."» refers to time spanning between the creation of the branch point and the time when you decide to merge.  In this scenario «if someone merged something between "1." and "2."» refers to the time spanning between the rebase and the merge, which is usually very short.  Thus in the scenario I provide, you can «lock» the master branch for the time of the merge without disturbing signigicantly your workflow, while it is impractical in the 1st scenario.

If you are doing systematic code reviews, it is probably a good idea to rearrange commits in an adequate way (optional step).

Managing the intermediate branch artifacts only presents a difficulty if you share them between repositories.


问:
Overcoming slow problem solving due to increased knowledge of what might go wrong
This has been troubling me for some time, and I'd really appreciate the input of other professionals.

Short background: I started programming when my parents bought me my first computer in 1988 (at age 14, I'm 39 now). I followed a couple of other career paths before finally becoming a professional programmer in 1997. Late bloomer, perhaps, but that's how it was. I'm still happy with my choice, I love programming, and I consider myself good at what I do.

Lately, I've been noticing that the more experience I gain, the longer it takes me to complete projects, or certain tasks in a project. I'm not going senile yet. It's just that I've seen so many different ways in which things can go wrong. And the potential pitfalls and gotchas that I know about and remember are just getting more and more.

Trivial example: it used to be just "okay, write a file here". Now I'm worrying about permissions, locking, concurrency, atomic operations, indirection/frameworks, different file systems, number of files in a directory, predictable temp file names, the quality of randomness in my PRNG, power shortages in the middle of any operation, an understandable API for what I'm doing, proper documentation, etc etc etc.

In short, the problems have long since moved from "how do I do this" to "what's the best/safest way of doing it".

The upshot is that it takes me longer to finish a project than a novice. My version may be rock solid, and as impenetrable as I know how to make it, but it takes longer.

The "create file" example above was just that, an example. Real tasks are obviously more complex, but less suited for a generic question like this one. I hope you understand where I'm going with this. I have no problem coming up with efficient algorithms, I love math, I enjoy complex subjects, I have no difficulties with concentration. I think I do have a problem with experience, and consequently with a fear of errors (intrinsic or extrinsic).

I spend almost two hours a day reading up on new developments, new techniques, languages, platforms, security vulnerabilities, and so on. The conundrum is that the more knowledge I gain, the slower I am in completing projects.

How do you deal with this?

答:
Another option is: stop writing code, instead sell your expertise in spotting the problems in advance.

In other words, become a Consultant.

Many organizations are happy to pay expensive dollars (if not top-dollar) for someone to spot the issues before spending months on creating the code that makes the problems. It is well known that fixing a bug in design, is orders of magnitude cheaper/easier than fixing it after it has been coded, tested, and deployed.

You won't be writing as much code, and you may likely miss that, but then it seems that the actual lines of code are not your core strength, but in knowing which lines of code should be written - and which shouldn't.

Focus on your strengths.

(well, if that's what you enjoy...)


答:
Information provided by documentation falls in three catgeories:

Recipe.

Reference.

Expert knowledge.

Recipes or example makes a bridge between the problem domain and the functionalities of the software.  Reference describes completely some functionality and is useful if you want to adapt a recipe to a specific case.

(Expert knowledge maps concepts of the problem domain to concepts of documentation, it is useful if concepts can be expressed in several manners or if users of the software are not experts in the field.)

How do I break this bad habit as a programmer or am I over thinking? Any wisdom from fellow programmers is appreciated.

I do not think that your habit is bad.  When you learn an API, you first get an idea of which problems can be solved and which methodologies are provided with the help of Recipes (your examples).  Reference documentation then helps you to fine tune the methodologies to special cases.

Title: Prefer examples over documentation. Is it a behavioral problem?

Body:
Whenever I come across a new API or programming language or even simple Linux man pages, I always (ever since I remember) avoided them and instead lazily relied on examples for gaining understanding of new concepts.

Subconsciously, I avoid documentation/APIs whenever it is not straightforward or cryptic or just plain boring. It's been years since I began programming and now I feel like I need to mend my ways as I now realize that I'm causing more damage by refraining from reading cryptic/difficult documentation as it is still a million times better than examples as the official documentation has more coverage than any example out there. Even after realizing that examples should be treated as "added" value instead of the "primary" source for learning.

How do I break this bad habit as a programmer or am I overthinking?


问:
Object oriented immutability: final classes or final methods
One of the things you see in numerous places in the standard java library is final classes. It is claimed that this is for immutability which I understand...to an extent.

Suppose you have a class:

```<code>final public class ImmutableTest {
    private String value;
    public ImmutableTest(String value) {
        this.value = value;
    }
    public String getValue() {
        return this.value;
    }
}
</code>```

You can say that the value is immutable because it can't be adapted after creation. However this limits usability of the class as no one can extend it (for example to use as a drop-in for a bad interfaceless design...).

Now suppose you have this class:

```<code>public class ImmutableTest {
    private String value;
    public ImmutableTest(String value) {
        this.value = value;
    }
    final public String getValue() {
        return this.value;
    }
}
</code>```

The "value" is still immutable but now at least people can extend the class. Someone once interjected: but if you extend it, the extended class is not guaranteed to be immutable!

While this is true, I think it is immaterial to the class itself.

If user A uses my ImmutableTest class everywhere in his code, he only has access to the "value" anyway which remains immutable. Unless he does explicit casting (in other words: he's aware that he's trying to access other stuff) he can't access a "mutable" part of the actual instance which means from the developer's point of view the class is as immutable as it should be, even if the actual instance has other mutable variables.

So in short: my opinion is that final classes are superfluous as final methods are all you need. I would love to hear arguments to the contrary though!

UPDATE

To clarify: I'm not claiming that adding "final" to a class or its methods makes it immutable.

Suppose you have a class that is designed to be immutable but you do not make the methods or class final, a subclass can of course make it mutable again. This argument is used as to why some classes in the standard library are final. My opinion is that it should've been enough to finalize the accessor methods to the immutable part and leave the class non-final.

This may leave the window open to the child objects adding mutable fields but the original set of fields would remain immutable hence satisfying the "immutable" requirement for the initial set of methods.

UPDATE2

The conclusion being that final classes have no real purpose except perhaps brevity which in itself is not enough of a reason to lose extensibility in my opinion.

答:
Classes are not mutable or immutable, mutability usually refers to the state of objects at runtime.

Final classes, methods and members have different goals.

An final class cannot be extended by other classes. Depending on your design, this may be a desirable design property of this class. It does not mean that all members of this class are immutable by default! Logical immutability can be a side effect as in your example. If a class is final and all of its fields are as well, the object is strongly immutable.

Final methods mean that the method cannot be overridden in a subclass. This can be for example useful with the template method pattern where you do not want clients to override the template method instead of the hooks. This, again, has nothing to do with immutable state because it does not directly relate to a member being immutable.

Final fields is where immutablity comes really into play. If you placed the final keyword in front of value like private final String value;, you would make sure that a value could not be overriden no matter who extended what.


答:
Declaring immutable class final saves programmer from the need to repeat declaring final in each and every method declaration, over and over and over again.

In classes like java.lang.String, having over 60 methods, this is substantial save, as well as important guarantee that necessary modifier won't be omitted by mistake.

When object is intended to be immutable, mistakes to declare final method may be hard to detect, because there is no reliable way to tell whether programmer omitted final modifier intentionally or by mistake.

final classes have no real purpose except perhaps brevity

Besides brevity and helping to avoid mistakes, a strong benefit of declaring immutable class final is that this makes programmer's intent explicit, unambiguously communicating to API users that none of class methods are intended for override.

Alternative way, that is, declaring all methods final, lacks this important "feature", as it leaves users of the API in the indecisive state, whether API designers intended to only protect some methods from overloading, and it only accidentally turned out that all of them got final, or there was a design decision to cover all the class.

my opinion is that final classes are superfluous as final methods are all you need

Given above, having final modifier for class doesn't look superfluous to me.

It is worth noting that Sun/Oracle Java tutorial presents final classes as a matter of usefulness and not as that of convenience. If final classes purpose was mere brevity / syntactic sugar, one would expect tutorial to explain these as convenience.

...you can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.

Title: Object oriented immutability: final classes or final methods

Body:
One of the things you see in numerous places in the standard java library is final classes. It is claimed that this is for immutability which I understand...to an extent.

Suppose you have a class:

```<code>final public class ImmutableTest {
    private String value;
    public ImmutableTest(String value) {
        this.value = value;
    }
    public String getValue() {
        return this.value;
    }
}
</code>```

You can say that the value is immutable because it can't be adapted after creation. However this limits usability of the class as no one can extend it (for example to use as a drop-in for a bad interfaceless design...).

Now suppose you have this class:

```<code>public class ImmutableTest {
    private String value;
    public ImmutableTest(String value) {
        this.value = value;
    }
    final public String getValue() {
        return this.value;
    }
}
</code>```

The "value" is still immutable but now at least people can extend the class. Someone once interjected: but if you extend it, the extended class is not guaranteed to be immutable!

While this is true, I think it is immaterial to the class itself.

If user A uses my ImmutableTest class everywhere in his code, he only has access to the "value" anyway which remains immutable. Unless he does explicit casting (in other words: he's aware that he's trying to access other stuff) he can't access a "mutable" part of the actual instance which means from the developer's point of view the class is as immutable as it should be, even if the actual instance has other mutable variables.

So in short: my opinion is that final classes are superfluous as final methods are all you need. I would love to hear arguments to the contrary though!

UPDATE

To clarify: I'm not claiming that adding "final" to a class or its methods makes it immutable.

Suppose you have a class that is designed to be immutable but you do not make the methods or class final, a subclass can of course make it mutable again. This argument is used as to why some classes in the standard library are final. My opinion is that it should've been enough to finalize the accessor methods to the immutable part and leave the class non-final.

This may leave the window open to the child objects adding mutable fields but the original set of fields would remain immutable hence satisfying the "immutable" requirement for the initial set of methods.

UPDATE2

The conclusion being that final classes have no real purpose except perhaps brevity which in itself is not enough of a reason to lose extensibility in my opinion.


问:
Why I'm not selected in an interview?
I'm working in development for 4 years, and 3.5 in PHP - why I don't seem to be able to be selected in an interview.

I want to know what special things the interviewer wants to see in candidates - for senior PHP developer roles.

Interviewer asks me 10 questions and I'm able to answer only 5. Does selection depend on these things? It doesn't mean that I can't solve the problem, I can google the question, I can ask on forums. Why don't they understand that a man can't remember all the answers for each and every question? Especially programming ones.

Please advise.

答:
"Interviewer asks me 10 questions and I'm able to answer only 5. Does selection depend on these things? It doesn't mean that I can't solve the problem, I can google the question, I can ask on forums. Why don't they understand that a man can't remember all the answers for each and every question? Expecially programming ones."

These things are very significant and will be a very significant part of the reason.

Interviewers do understand that you can't know everything and generally tailor the questions to suit.   Generally most questions an interviewer will ask will be the sorts of things they expect a candidate to be able to answer without access to the internet.

Why do they expect this standard?  A few reasons come to mind:

You indicate that you're looking at senior developer roles.  Senior
developers are by definition those who have a good level of
knowledge already and can help others out, not those who are
dependent on Google.

A programmer who knows this stuff - as opposed to having to post it
on forums - is going to be far more productive that one who relies
on the internet.  They're not having to wait for replies, understand
what's been posted and adapt it to their purpose, they're just
getting on and coding.

They're obviously finding candidates who can answer these questions
and in that instance wouldn't you hire the guy who got 9 out of 10
over the guy who got 5 out of 10.

If they were happy with someone bright who understands the basics
and Googles the rest, you can hire a junior developer for a lot less
money.

Personally out of 10 questions for an intermediate or senior role normally I'd expect a candidate to be answering perhaps 8 well and having a fair idea at least one of the others.

If you're not hitting that level then I suggest that you're probably applying for jobs a little above your current level and should adjust your expectations.

Title: Why I'm not selected in an interview?


问:
What's wrong with this approach to CSS?
I have a static Jekyll website.

The website is constructed once, on my computer, and then sent to the server in the form of plain HTML, image, and CSS files, to be served by a regular HTTP server.

This construction process involves a template engine that has to glue various components together.

For example, this is the template for my posts and pages (the only other template I have is for the main page, which shares quite a lot with this one):

```<code><!DOCTYPE html>
<html>
    <head>
        {% include head.html %}
        <link rel="stylesheet" href="/css/main.css">
        {% if page.title == "Tautological Cascade" %}
            <title>Tautological Cascade</title>
        {% else %}
            <title>Tautological Cascade: {{ page.title }}</title>
        {% endif %}
    </head>

    <body>
        <div class="site" >
            {% include header.html %}
            {{ content }}
            {% include footer.html %}
        </div>
    </body>
</html>
</code>```

The most important part to notice here is the body section. It basically sandwiches a processed markdown file between two HTML files.

Currently, I only have one, main CSS file, which is used by ALL pages.

I find this approach a bit unpractical. Everything is defined in there, and it's getting messy. Couple that with my general ignorance of anything but the basic CSS, and you get something close to a nightmare.

My idea is this: inline CSS for all of these parts that I glue together.

So header.html would have its CSS in its file, footer.html would have its CSS, and the file that describes the content int its own.

Is this the correct solution to my problem? Is there something wrong with this approach?

答:
Inlining CSS is a necessary evil for HTML-formatted e-mails because of poor client support for stylesheets, but for web pages it's preferable to find an approach which structures your CSS but keeps it separate from the HTML. This allows browsers to cache it separately.

There are three main approaches.

Link to multiple stylesheets from your , as mentioned by Bobson.

Split your stylesheets into self-contained sections and link them together with @import.

Use a CSS preprocessor. (Since you're using a Ruby tool to build your site, you'd probably want to use SASS. This allows you to work with a much simpler source file, because it factors out a lot of the redundancy that CSS has.

These approaches can also be combined.

Title: What's wrong with this approach to CSS?

Body:
Inlining CSS is a necessary evil for HTML-formatted e-mails because of poor client support for stylesheets, but for web pages it's preferable to find an approach which structures your CSS but keeps it separate from the HTML. This allows browsers to cache it separately.

There are three main approaches.

Link to multiple stylesheets from your <head>, as mentioned by Bobson.

Split your stylesheets into self-contained sections and link them together with @import.

Use a CSS preprocessor. (Since you're using a Ruby tool to build your site, you'd probably want to use SASS. This allows you to work with a much simpler source file, because it factors out a lot of the redundancy that CSS has.

These approaches can also be combined.


答:
The problem with that approach is that either you duplicate most of the same styles in footer.css and header.css or you'll have to include a common.css stylesheet in both the footer and the header, which most likely would still contain the bulk of the stylings.

The approach I often take is to have a style sheet called cbc.css strictly for guaranteeing same styles across multiple browsers.  It is an ugly bit of styling which usually involves setting the padding to 0 and things of that sort.  It also contains any browser-specific stylings in order to start off on the same page.

All theme-related stylings go in common.css.  It should not refer to any ids specifically, and, if I can help it, it should not refer to classes either (if you find yourself using classes as ids, it doesn't belong here).  The idea is that with cbc.css, most of your styles should already be set.  Save for structure and things specific to the layout of the page, it should already look like the final product.

Then, each included page has stylings for only that page or any page it includes within it, usually referred by id or by class if you use it in more than one spot (but not outside of that page, otherwise it belongs in common.css).

When I do it like this, common.css is fairly clean.  I won't say it is small, but it is uncluttered and easy to maintain, which is the idea.  You know that if you want to change a style that would have an impact on everything, you change common.css.  If you want to change the structure of that particular page, you look for <page name>.css.

I hope that helps.

Title: What's wrong with this approach to CSS?

Body:
I have a static Jekyll website.

The website is constructed once, on my computer, and then sent to the server in the form of plain HTML, image, and CSS files, to be served by a regular HTTP server.

This construction process involves a template engine that has to glue various components together.

For example, this is the template for my posts and pages (the only other template I have is for the main page, which shares quite a lot with this one):

```<code><!DOCTYPE html>
<html>
    <head>
        {% include head.html %}
        <link rel="stylesheet" href="/css/main.css">
        {% if page.title == "Tautological Cascade" %}
            <title>Tautological Cascade</title>
        {% else %}
            <title>Tautological Cascade: {{ page.title }}</title>
        {% endif %}
    </head>

    <body>
        <div class="site" >
            {% include header.html %}
            {{ content }}
            {% include footer.html %}
        </div>
    </body>
</html>
</code>```

The most important part to notice here is the body section. It basically sandwiches a processed markdown file between two HTML files.

Currently, I only have one, main CSS file, which is used by ALL pages.

I find this approach a bit unpractical. Everything is defined in there, and it's getting messy. Couple that with my general ignorance of anything but the basic CSS, and you get something close to a nightmare.

My idea is this: inline CSS for all of these parts that I glue together.

So header.html would have its CSS in its file, footer.html would have its CSS, and the file that describes the content int its own.

Is this the correct solution to my problem? Is there something wrong with this approach?


答:
You wouldn't be the first by a long shot to try to figure out the best way to plan development time.  This is in part due to the fact that it is difficult to quantify something you cannot actually see being built, and partly due to the mythical man-month, which is a direct contrast to the intuitive idea that if you have 2 programmers, you should be able to develop twice as fast than if you had 1 programmer.

As you've probably realized already, it is a lot more complicated than that.  One approach to estimating development time as rounding a group of highly qualified individuals for what concerns software development and ask them to estimate the amount of time it would take to finish a project (explaining as detailed as possible).  You take the highest of all the estimates and you double it.  Yes, you read correctly.  You double the highest estimate and you shall have a reasonably accurate estimate.  I know, because with time, this is how I've been able to accurately tell my bosses how long it takes me to do something.  I gather the opinions of my fellow programmers and my own and double the highest estimate.  If this seems like too high of a value, consider that testing new functionality is crucial and consider potential bug fixes afterwards, and it will seem like a more reasonable figure.

In my own personal experience as a programmer, I can tell you that it helps to break down projects into milestones.  How long does it take to reach milestone 1, then from milestone 1 to milestone 2, then milestone 2 to milestone 3, etc.?  When broken down like this, the answer is usually far more accurate than trying to estimate the entire project in its entirety.  Strangely enough, if you sum up the estimates of all these milestones, it will usually be larger than the original estimate on the entire project (if the programmer is being honest with himself anyway), which only leads me to think that detail is the key here.

Perhaps you lack the technical know-how, but you should still try to follow on a more general level.  Programmers have no problems with repetition.  It's the twists and turns that occupy all the time in developing a program.  So most likely, the more functionality that you wish to include, the more complicated the program is going to become, and assuming this new functionality has no influence on previously implemented sections of the code, development will be linear according to the amount of work to be done.  Most likely, new functionality heavily influences previously implemented sections and thus development involves not just implementing the new functionality but fixing the old code, making development time exponential.

My advice to you would be to, without telling the programmers how to do their job, try to get a handle of how the program works at a general level and you should soon be able to see how new functionality would modify that behavior and thus provide a reasonable estimate on how long it would take to do it.  Combine this with their estimates (double the highest), and you start getting a better idea of how to estimate development time.

I hope that helps!


答:
One of the reasons estimates are often way off is because estimation is actually quite hard and requires experience and knowledge about the system to be changed. Most often it is helpful to break big steps up into smaller ones.

Now you have many possibilities of those I will mention two:

Planning Poker

PERT (Program Evaluation and Review Technique)

Planning Poker

This works quite well in small agile teams.

Excerpt from wikipedia:

A Moderator, who will not play, chairs the meeting.

The Product Manager provides a short overview. The team is given an opportunity to ask questions and discuss to clarify assumptions and risks. A summary of the discussion is recorded by the Project Manager.

Each individual lays a card face down representing their estimate. Units used vary - they can be days duration, ideal days or story points. During discussion, numbers must not be mentioned at all in relation to feature size to avoid anchoring.

Everyone calls their cards simultaneously by turning them over.

People with high estimates and low estimates are given a soap box to offer their justification for their estimate and then discussion continues.

Repeat the estimation process until a consensus is reached. The developer who was likely to own the deliverable has a large portion of the "consensus vote", although the Moderator can negotiate the consensus.

An egg timer is used to ensure that discussion is structured; the Moderator or the Project Manager may at any point turn over the egg timer and when it runs out all discussion must cease and another round of poker is played. The structure in the conversation is re-introduced by the soap boxes.

The important bits here are clarification, discussion, simultaneously calling the estimate, so as no bias is introduced, and consensus.

PERT

It is often hard to give one exact estimate. What is easier is to give a likelihood. PERT uses 3 values for the estimate:

most optimistic time to finish (if less problems arise than expected)

most pessimistic time to finish (if everything goes wrong - excluding major catastrophes)

most likely time to finish (if everything goes as expected) <- this is what your developers most likely estimate right now

By weighting those three estimates you get a more reliable estimate.

```<code>t_expected = (t_opt + 4 * t_likely + t_pes) / 6
</code>```

And / or you are able to use these three values to construct a probability distribution that may reflect the uncertainty of the real world even more. Beta distribution and Triangular distribution are prominent choices. Using this you can now apply statistics like "how likely is it to finish at date x given current estimates" or "if i want 95% certainty, at what point in time will it be finished".

Actually PERT consists of more than these aspects mentioned here, that I omitted for the sake of brevity.

Body:
One of the reasons estimates are often way off is because estimation is actually quite hard and requires experience and knowledge about the system to be changed. Most often it is helpful to break big steps up into smaller ones.

Now you have many possibilities of those I will mention two:

Planning Poker

PERT (Program Evaluation and Review Technique)

Planning Poker

This works quite well in small agile teams.

Excerpt from wikipedia:

A Moderator, who will not play, chairs the meeting.

The Product Manager provides a short overview. The team is given an opportunity to ask questions and discuss to clarify assumptions and risks. A summary of the discussion is recorded by the Project Manager.

Each individual lays a card face down representing their estimate. Units used vary - they can be days duration, ideal days or story points. During discussion, numbers must not be mentioned at all in relation to feature size to avoid anchoring.

Everyone calls their cards simultaneously by turning them over.

People with high estimates and low estimates are given a soap box to offer their justification for their estimate and then discussion continues.

Repeat the estimation process until a consensus is reached. The developer who was likely to own the deliverable has a large portion of the "consensus vote", although the Moderator can negotiate the consensus.

An egg timer is used to ensure that discussion is structured; the Moderator or the Project Manager may at any point turn over the egg timer and when it runs out all discussion must cease and another round of poker is played. The structure in the conversation is re-introduced by the soap boxes.

The important bits here are clarification, discussion, simultaneously calling the estimate, so as no bias is introduced, and consensus.

PERT

It is often hard to give one exact estimate. What is easier is to give a likelihood. PERT uses 3 values for the estimate:

most optimistic time to finish (if less problems arise than expected)

most pessimistic time to finish (if everything goes wrong - excluding major catastrophes)

most likely time to finish (if everything goes as expected) <- this is what your developers most likely estimate right now

By weighting those three estimates you get a more reliable estimate.

t_expected = (t_opt + 4 * t_likely + t_pes) / 6

And / or you are able to use these three values to construct a probability distribution that may reflect the uncertainty of the real world even more. Beta distribution and Triangular distribution are prominent choices. Using this you can now apply statistics like "how likely is it to finish at date x given current estimates" or "if i want 95% certainty, at what point in time will it be finished".

Actually PERT consists of more than these aspects mentioned here, that I omitted for the sake of brevity.


答:
I have been a sole developer on a few small projects off my own and have some industrial experience working with a large team. I have noticed that the techniques that a big company uses does not necessarily work for a small team. At one point I was doing more planning and documentation rather than writing code. I suggest that you try to find a good way of working first by trying different techniques (the other answers provide some great insight) and tools, this will cost you some time and effort but you will benefit from it later on. Some tools/ techniques I found to be useful were:

-Pivotal Tracker - Great program for keeping track of stories and encourages breaking down -tasks, it is lightening quick at entering stories and automatically deduces velocity. https://www.pivotaltracker.com/.

-Gdocs for documentation as it is easy to have multiple users editing and discussing at the same time.

-At a company I used to work for we used to have a meeting for each and every story that we initiated, this meeting had to include a senior programmer since he would be better at judging how long a task would take. He would also be better at judging what the difficult part might be in a task.

In summary I believe that the key to working in small teams is to have a solid planning regime that is fast and fluid. Also any difficulties with the story can be identified early so that planning a task will keep that in mind (this could lead to building something differently).

Hope this helps


问:
What's the recommended control naming convention for XAML markup?
When working with WPF or Silverlight, how should one use control naming conventions? Do you name the controls in XAML markup? I have seen samples of projects at codeplex with control names such  as "selectButton" or "btnSelect". What would you recommend? </p>

答:
Microsoft has guidelines published here on their web site.  The bottom line is that Hungarian naming conventions are out.

EDIT

To make this more clear, Microsoft has dropped Hungarian notation from all of their naming conventions, including UI elements.  HOWEVER, MS has not documented any recommendations for UI elements.  There are lots of links out there that note this and offer their suggestions but the bottom line is that with UI elements, you're on your own.  Example link.

In our standard we've dropped Hungarian notation and are using explicit naming, meaning a button called OK would be named ButtonOK, a textblock called Comments would be TextblockComments.  The downside is that names can get kind of long, the positive is that EVERYONE knows exactly what the element is.

As long as you establish what works for you and use that standard consistently, you can't go wrong.


问:
REST or a message queue in a multi-tier heterogeneous system?
I'm designing a REST API for a three-tier system like: Client application -> Front-end API cloud server -> user's home API server (Home).

Home is a home device, and is supposed to maintain connection to Front-end via Websocket or a long poll (this is the first place where we're violating REST. It gets even worse later on). Front-end mostly tunnels Client requests to Home connection and handles some of the calls itself.
Sometimes Home sends notifications to Client.

Front-end and Home have basically the same API; Client might be connecting to Home directly, over LAN. In this case, Home needs to register some Client actions on a Front-end itself.

Pros for REST in this system are:

REST is human-readable;

REST has a well-defined mapping of verbs (like CRUD), nouns and response codes to protocol objects;

It works over HTTP and passes all the possible proxies;

REST contras are:

We need not only a request-response communication style, but also a publish-subscribe;

HTTP error codes might be insufficient to handle three-tier communication errors; Front-end might return 202 Accepted to some async call only to find out that necessary Home connection is broken and there should have been 503;

Home needs to send messages to Client. Client will have to poll Front-end or to maintain a connection.

We are considering WAMP/Autobahn over Websocket to get publish/subscribe functionality, when it struck me that it's already looking like a message queue.

Is it worth evaluating a sort of messaging queue as a transport?

Looks like message queue contras are:

I'll need to define CRUD verbs and error codes myself on a message level.

I read something about "higher maintenance cost", but what does it mean?

how serious are these considerations?

答:
If you have the connectivity, go with a message queue - although you have to define your own protocols (hardly a difficult task!) to send messages of a particular structure and format.

The problem with maintenance is that typically the client and server are built separately so you need to be careful to keep both ends using the same message definitions, but if you're not organised enough, just use the same XML you would use in your REST service.

If you have connectivity issues over the internet, with port 80 and http only and 'unidirectional' comms then a REST style system is probably the best. Send and poll, or get a websocket going for callback data, but generally architect your system be be client/server. If you have the ability to get the connectivity, then messaging systems are great.

I'd go with ZeroMQ for a messaging system, its configurable enough to twist in all manner of scenarios, including fault-tolerant ones. I'm not sure that it works over http though.


答: Examples are documentation.  I don't think it is bad from a getting familiar with the API standpoint. If it is the only documentation that you look at then it can be an issue.  Most examples skimp on error checking which can lead to overly brittle code if you don't go back and pick up the missing pieces from the reference documentation.</p>


问:
How should I start with Lisp?
I've been programming for years now, working my way through various iterations of Blub (BASIC, Assembler, C, C++, Visual Basic, Java, Ruby in no particular order of "Blub-ness") and I'd like to learn Lisp. However, I have a lot of intertia what with limited time (family, full time job etc) and a comfortable happiness with my current Blub (Java).

So my question is this, given that I'm someone who would really like to learn Lisp, what would be the initial steps to get a good result that demonstrates the superiority of Lisp in web development? Maybe I'm missing the point, but that's how I would initially see the application of my Lisp knowledge.

I'm thinking "use dialect A, use IDE B, follow instructions on page C, question your sanity after monads using counsellor D". I'd just like to know what people here consider to be an optimal set of values for A, B, C and perhaps D. Also some discussion on the relative merit of learning such a powerful language as opposed to, say, becoming a Rails expert.

Just to add some more detail, I'll be developing on MacOS (or a Linux VM) - no Windows based approaches will be necessary, thanks.

Notes for those just browsing by

I'm going to keep this question open for a while so that I can offer feedback on the suggestions after I've been able to explore them. If you happen to be browsing by and feel you have something to add, please do. I would really welcome your feedback.

Interesting links

Assuming you're coming at Lisp from a Java background, this set of links will get you started quickly.

Using Intellij's La Clojure plugin to integrate Lisp (videocast)

Lisp for the Web

Online version of Practical Common Lisp (c/o Frank Shearar)

Land of Lisp a (+ (+ very quirky) game based) way in but makes it all so straightforward

Install Clojure and Sublime 2 on MacOS an excellent getting started guide

Look at the Clojure in Action book. Worked for me.

答:
Conrad Barski has a great tutorial called Casting SPELs in Lisp (SPEL is his acronym for macros). It involves making a simple Adventure-type game, and jumps right into Lisp macros. He also has been working on an introductory book that is now available at:

Learn to program Lisp, one game at a time.

And, from the Table of Contents:

Create your own web server, and use it to play browser-based games

I don't know what this implies for web development (as in HTML pages) using Lisp, however. :)

Update - I see someone mentioned the book "Structure and Interpretation of Computer Programs", which reminded me that MIT has put online, the entire SICP Video Lectures by Hal Abelson and Gerald Jay Sussman. You might have found the book dry, but the lectures are excellent. Although they're Scheme-based, they still get across the basic concepts also in Lisp, very nicely. Well worth downloading and watching.

Title: How should I start with Lisp?


问:
Custom animation iOS
I have seen animation, and i can't figure out how to do something like in this video(youtube). I want to discuss how it's made. I don't think that they're using sprites.

I have one idea how to do this: for example i want to create animation of "walking" animal (when animal moves, he's legs "runs" moving animation), i should create customView with imageView of animalBody 3 and two imageViews of animal legs 2. Then i make hard coded animation of moving legs and voila, i have custom animation. When i move customView, then i should start animation of legs. But is there better approach to do this? Thanks!

答:
I'm not an IOS expert by far, but if it was me doing this, here's what I'd try to do:

Decide if you really want to have separate parts of your creature animated separatedly at the code level, or if it suffices to just make 1-animation sprites, each containing the whole creature. Here's what I mean:

What is this animation part of? Is it part of a game? If so, will the creature in question do multiple kinds of running? Like maybe run and wave his arms, run and throw bananas, etc? If yes, then you may benefit from having a separate set of sprites for the running legs, and a different separate set of sprites for each of the arm-flailing and banana-throwing actions. Then you can combine them to achive full animations

If on the other hand this guy will only run one way all the time (maybe it's just a cute loading animation), then you'll simplify your code and general project if you make animation sprites each containing the entire creature pose of running animation.

You'll need a way to pace the animation aka have it run at the same rate/speed on any device, no matter how powerful that device is. Normally, if you want to do it by hand you'd do a game loop. However I'm pretty sure IOS already comes with built in tools for making simple sprite based animations (like Android does), or (I've just googled this), far more fancier ones like : Sprite Kit. It's up to you do decide how you'll go about "pacing" your animation. My advice is to first see if you can't already use an existing IOS framework/library, before going into manual coding on this.

Title: Custom animation iOS


答:
It looks like Autobahn fits nicely with what you're trying to do. There are other tools available as well. Check out the Windows Azure Service Bus (which has client frameworks for Java, .NET, PHP, Python, NodeJS, and Ruby).

While the built in rest messages are useful. You'll find that your application will outgrow basic CRUD operations. For instance if your application were a banking system. Instead of

Update Acct 54321 Balance = Balance - 20.00
Update Acct 98765 Balance = Balance + 20.00

You'd probably want a single message like

Transfer 20.00 from account 54321 to account 98765

It's best that you discover this impediment with REST now rather than later. Check out Greg Young's Event Centric which discusses how to create a richer model for messaging within your application.

Title: REST or a message queue in a multi-tier heterogeneous system?

Body:
I'm designing a REST API for a three-tier system like: Client application -> Front-end API cloud server -> user's home API server (Home).

Home is a home device, and is supposed to maintain connection to Front-end via Websocket or a long poll (this is the first place where we're violating REST. It gets even worse later on). Front-end mostly tunnels Client requests to Home connection and handles some of the calls itself.
Sometimes Home sends notifications to Client.

Front-end and Home have basically the same API; Client might be connecting to Home directly, over LAN. In this case, Home needs to register some Client actions on a Front-end itself.

Pros for REST in this system are:

REST is human-readable;

REST has a well-defined mapping of verbs (like CRUD), nouns and response codes to protocol objects;

It works over HTTP and passes all the possible proxies;

REST contras are:

We need not only a request-response communication style, but also a publish-subscribe;

HTTP error codes might be insufficient to handle three-tier communication errors; Front-end might return 202 Accepted to some async call only to find out that necessary Home connection is broken and there should have been 503;

Home needs to send messages to Client. Client will have to poll Front-end or to maintain a connection.

We are considering WAMP/Autobahn over Websocket to get publish/subscribe functionality, when it struck me that it's already looking like a message queue.

Is it worth evaluating a sort of messaging queue as a transport?

Looks like message queue contras are:

I'll need to define CRUD verbs and error codes myself on a message level.

I read something about "higher maintenance cost", but what does it mean?

how serious are these considerations?


问:
adding data gathering to a utility app and publish it to partners?
I've been working on a utility app for a while, and when we're in the final phases the boss is asking for adding user behavior and location tracking and was explicit about publishing them to 3rd party developers to make use of them.

He seems to have set his mind about it, is there anything I can/should do about it?

Clarify: if you are an app developer who's asked to add data gathering of the app users and publishing it, is there anything you should say against it ?

答:
There is nothing inherently wrong with obtaining and selling some data, provided that this is legal in all applicable jurisdictions, and that you don't hide this fact. Specifically:

During installation, but before purchase, the app should inform the user that access to GPS etc. is required. Of course a potential user will become suspicious if such functionality is required without your app offering location-dependant functionality. You can ask your boss if potentially limiting the success of your app is a good business decision.

The privacy policy should mention that data may be shared with 3rd parties.

There are some considerations regarding good UX:

Do not continuously transmit telemetry. This avoids incurring unexpected data fees for the user, and conserves battery.

Do not unnecessarily run in the background, see the point about battery.

Do not create an app that behaves like malware or spyware.

I would also like to point out that it is possible to collect interesting data without including directly or indirectly identifying information. Data like usage patterns is extremely fascinating, but creating detailed movement patterns or extracting personal information from other apps is creepy.

It is interesting that these additional requirements came up very late in the development process, and it may be interesting to find out why. If this is just a case of shifting requirements during development (without accounting for this through agile methodologies), this is just the usual headache.

If however you have reason to believe these requirements have existed for a longer time, this is more interesting. In a worst case scenario, an evil boss would have waited until the project is almost completed, so that you have a high personal investment and do not wish it to fail for something “as minor” as ethically questionable data collection.

Determine the exact type and breadth of data collection, and evaluate it regarding legality, business concerns, user experience, and make sure the user isn't coaxed into using the app despite these data collections.

If there are objective issues, raise these in the context of whishing to ship the best possible product.

Determine your personal (subjective) ethical red line which you do not whish to cross.

If the project is well inside your comfort zone, implement the functionality.

If the project is far on the other side of your red line, voice your concerns and start looking for the next job.

If the project is in the neighborhood of the red line, implement the project but start looking for other jobs. It is probably not worth risking temporary unemployment if this is a one-off situation.


问:
Dependency injection with Finite State Machines and the Interface Segregation Principle
I am trying to figure out what is the best way to setup a FSM and also keep my interfaces clean and use an IOC container to use DI.

Let's just visit the Head First design pattern textbook example of the gumball machine.

```<code>interface IState
{
    InsertQuarter();
    EjectQuarter();
    TurnCrank();
    Dispense();
}
</code>```

Is the best practice to just thrown an exception for an invalid state?  Why add the state if it's not even applicable?  I guess that is the portion where I am confused.  I could see this simple example getting more complex.

My other related question is, how do I perform DI to these states?  Should a state machine and states should be registered in my IOC container?  Let's suppose I have an Order Service and an Inventory Service that have a dependency on a StageOrderState.  What might this object model look like?  I'm having a hard time digesting how to actually inject the dependencies in to these states.  My guess is that I could register the states and pass the container around to the states.

答:
It seems to me that you want to genericize the Head First example, so that it can accept an arbitrary collection of actions.

In C# you can have first-class functions, which means that you can pass functions to your finite state machine and have it maintain those functions in a list.  Something like:

```<code>interface IState
{
    void AddStep(Action<T> action);
}
</code>```

And then just pass your function to the AddStep method for insertion into the list by the state machine.

```<code>public class StateMachine : IState
{
    List<Action<T>> actions;

    public void AddStep(Action<T> action)
    {
        actions.Add(action);
    }
}
</code>```

Then you just add your actions.

```<code>var machine = new StateMachine();
machine.AddStep(x => Console.WriteLine(x.ToString()));
</code>```

Body:
It seems to me that you want to genericize the Head First example, so that it can accept an arbitrary collection of actions.

In C# you can have first-class functions, which means that you can pass functions to your finite state machine and have it maintain those functions in a list.  Something like:

interface IState
{
    void AddStep(Action<T> action);
}

And then just pass your function to the AddStep method for insertion into the list by the state machine.

public class StateMachine : IState
{
    List<Action<T>> actions;

    public void AddStep(Action<T> action)
    {
        actions.Add(action);
    }
}

Then you just add your actions.

var machine = new StateMachine();
machine.AddStep(x => Console.WriteLine(x.ToString()));


问:
Why is Python used for high-performance/scientific computing (but Ruby isn't)?
There's a quote from a PyCon 2011 talk that goes:

At least in our shop (Argonne National Laboratory) we have three
  accepted languages for scientific computing. In this order they are
  C/C++, Fortran in all its dialects, and Python. You’ll notice the
  absolute and total lack of Ruby, Perl, Java.

It was in the more general context of high-performance computing. Granted the quote is only from one shop, but another question about languages for HPC, also lists Python as one to learn (and not Ruby).

Now, I can understand C/C++ and Fortran being used in that problem-space (and Perl/Java not being used). But I'm surprised that there would be a major difference in Python and Ruby use for HPC, given that they are fairly similar. (Note - I'm a fan of Python, but have nothing against Ruby).

Is there some specific reason why the one language took off? Is it about the libraries available? Some specific language features? The community? Or maybe just historical contigency, and it could have gone the other way?

答:
Python has better support for N-dimensional arrays with the Numpy package.  I haven't seen anything similar for Ruby.

Python seems to be faster in the numerical computing / scientific computing that I have done.  I have no proof other than when I have written similar algorithms in Python and Ruby, the Python algorithms ran faster (YMMV).


问:
An extensible logging architecture for Android?
The end goal is to have a variety of data sets that can all be graphically plotted against eachother.

All data should correspond to a date, so that when plotted against each other, they show the correct relationship through time.

The key feature though, is to be able to add a new parameter to log at any time which will then be logged simultaneously and will then be able to be plotted against other data sets (from the time the later began onwards).

As a sub point, it also needs to be able to deal with sparse information which is sometimes available and sometimes not.

An example of the data can be seen below. C is sparse data and D is a data field added half way down the table.

I have considered SQLite but the thought of all the column changes due to columns added by myself and users didn't appeal.

Currently, I am thinking of creating an object which keeps track of time and contains a data field list of different data lists such as A, B, C and D as in the image. The thinking being that to add a new data field, I could just add a new parameter (e.g D) list to the data field list which already contains A, B, C.

Then I could just serialize this into JSON to keep it persistent and when I want to graph anything with sparse data, I could interpolate it.

That is my current solution but I would very much appreciate any opinions on better practices or flaws in my current solution.

答:
That's how I would approach this.

Two tables in the database.

1. log

[id] [timestamp] [dataset_id] [value]

[id] - auto-increment

[timestamp] - obvious

[dataset_id] - numeric ID of the dataset (related to datasets.id)

[value] - the numeric value for your graph (or all these 9, 7, 8 from your drawing)

2. datasets

[id] [name]

[id] - that's dataset_id from table log. Just an int.

[name] - that's the name of the dataset: "A", "B", "C" etc.

Now when D needs to be added, you don't add a datacolumn anywhere - just another row to table datasets.

I don't know the details (such as the expected size of your data), but I don't like the thought of using JSON. It doesn't feel like the right tool for the job.


答:
It is a fact that if you aren't keeping historical metrics then you can't even come close to giving reasonable estimates with a reasonable degree of accuracy. And asking some other company/person how long it wil take them doesn't help either. The problem is that each company and developer has their own way of doing things. Thus, every company will have different lengths of time for doing the exact same task. Each developer will have different lengths of time for doing the exact same task.

Your best course of action is to start keeping track of time and somehow figure out how to categorize the degree of difficulty for the task.  Some companies use lines of code, some use features, some just go by gut feel. Additionally, you also have to take into account if this is similar to something the developers have already built or something new, like new technology, new feature never built before by the team etc... Also, if it is an embedded or real-time system then complexity generally goes up quite a bit.

Unless you collect real data, no matter how many times your developers give you estimates they will really just be pulling numbers from their behind each time you ask them. Yes, collecting real data is a pain and at first it doesn't provide a lot of useful info, but over time it really does begin to provide reasonably accurate estimates.

I would also like to point out that estimates are generally only good over the big picture and not for short term measurements. For example, the developer estimates 2 days but it takes 8. Well the developer didn't account for having to setup a test environment and developing a simulator or that there was an entirely new technology they had to learn or they got stuck on a bug they couldn't figure out or the functionality required a refactoring of the existing system. You can't always predict those kinds of things for small tasks. However, over the course of an entire project those extra 6 days may get washed out by other tasks taking 6 days less duration.


问:
How much mocking is "just right?"
I titled the question jokingly because I'm sure that "it depends," but I have some specific questions.

Working in software that has many deep layers of dependency, my team has become accustomed using mocking fairly extensively to separate each code module from the dependencies beneath it.

Therefore I was surprised that Roy Osherove suggested in this video that you should be using mocking only something like 5% of the time. I'd guess that we're sitting somewhere between 70-90%.  I've seen other similar guidance from time to time as well.

I should define what I consider to be two categories of "integration tests" which are so distinct that they really should be given different names:  1) In-process tests which integrate multiple code modules and 2) Out-of-process tests which talk to databases, file systems, web services, etc.  It is type #1 that I am concerned with, tests which integrate multiple code modules all in-process.

Much of the community guidance I have read suggests that you should prefer a large number of isolated, fine-grained unit tests and a small number of coarse-grained end-to-end integration tests, because unit tests give you precise feedback on exactly where regressions might have been created, but the coarse tests, which are cumbersome to set up, actually verify more end-to-end functionality of the system.

Given this, it seems necessary to make rather frequent use of mocking to isolate these separate units of code.

Given an object model as follows:

... Also consider that our application's dependency depth goes much deeper than I could fit in this image, so that there are multiple layers N between the 2-4 layer and the 5-13 layer.

If I want to test some simple logical decision being made in unit #1, and if every dependency is constructor-injected into the code module that depends on it such that, say, 2, 3, and 4 are constructor injected into module 1 in the image, I would much rather inject mocks of 2, 3, and 4 into 1.

Otherwise, I would need to construct concrete instances of 2, 3, and 4.  This can be more difficult than just some extra typing.  Often 2, 3, and 4 will have constructor requirements which can be challenging to satisfy and according to the graph (and according to the reality of our project), I'll need to construct concrete instances of N through 13 to satisfy the constructors of 2, 3, and 4.

This situation becomes more challenging when I need 2, 3, or 4 to behave in some certain way so that I can test the simple logical decision in #1.  I might need to understand and "mentally reason about" the entire object graph/tree all at once to get 2, 3, or 4 to behave in the necessary way.  It often seems much easier to do myMockOfModule2.Setup(x=> x.GoLeftOrRight()).Returns(new Right()); to test that module 1 responds as expected when module 2 tells it to go right.

If I were to test concrete instances of 2 ... N ... 13 all together, the test setups would be very large and mostly duplicated.  Test failures might not do a very good job of pinpointing the locations of regressions failures.  Tests would not be independent (another supporting link).

Granted, it is often reasonable to do state-based, rather than interaction-based, testing of the bottom layer, since those modules seldom have any further dependency.  But it seems that mocking is almost necessary by definition to isolate any modules above the bottom-most.

Given all of this, can anyone tell me what I might be missing?  Is our team overusing mocks?  Or is there perhaps some assumption in typical unit testing guidance that the layers of dependency in most applications will be shallow enough that it is indeed reasonable to test all of the code modules integrated together (making our case "special")?  Or perhaps differently, is our team not bounding our bounded contexts adequately?

答:
Is our team overusing mocks?

Not at first glance.

If you have 1..13 modules, then each should have its own unit tests, and all (non-trivial, untrusted) dependencies should be replaced by test versions. That can mean mocks, but some people are pedantic with naming, so fakes, shims, null objects... some people refer to all test implementations as "mocks". This might be the source of the confusion about how much is "right".

Personally, I just call all test objects "mocks" because distinguishing between the variety of them isn't often useful. As long as they keep my unit tests fast, isolated and resilient... I don't care what they're named.

Title: How much mocking is "just right?"


答:
I suspect you wrote the question whilst frustrated - but this suggests a problem:

Interviewer asks me 10 questions and
  I'm able to answer only 5. Does
  selection depend on these things? It
  doesn't mean that I can't solve the
  problem, I can google the question, I
  can ask on forums. Why don't they
  understand that a man can't remember
  all the answers for each and every
  question? Expecially programming ones

I have two issues with this, first is that if you answer 5 out of 10 and someone else answers 6 out of 10 then all other things being equal that's game over - but second and more important is the question of how you respond when you don't know and your attitude to not knowing.

In terms of questions - it rather depends on the questions - but if its basic platform knowledge then you should be able to answer and if its a more detailed problem then you should be able to suggest approaches - "look on google and ask in forums" is not an approach.  Any programmer I interviewed that suggested either a) that he knew everything (unlikely and probably already proven to be false by poor answers) or b) that he didn't need to because all the answers were on google (or even stackoverflow) would not be coming back.

In terms of attitude... if you're being interviewed by someone qualified to ask the questions then they will have their own view of what a reasonable level of knowledge is based on their own capabilities and experience and you know what? It may be reasonable for a given job to expect the interviewee to give a good answer to most of their questions. If you're consistently failing to answer a significant number of questions (50% is significant) then you need to assess why.

Title: Why I'm not selected in an interview?

Body:
I'm working in development for 4 years, and 3.5 in PHP - why I don't seem to be able to be selected in an interview.

I want to know what special things the interviewer wants to see in candidates - for senior PHP developer roles.

Interviewer asks me 10 questions and I'm able to answer only 5. Does selection depend on these things? It doesn't mean that I can't solve the problem, I can google the question, I can ask on forums. Why don't they understand that a man can't remember all the answers for each and every question? Especially programming ones.

Please advise.


问:
Managing p/t consultants like Open Source contributors?
I just assumed tech lead for a project which has had a problem with its very part-time (maybe 2-5 hours / week) contractors:

submitting code that brings down the production app,

pull requests that cannot be auto-merged,

writing misnamed tests that don't actually test what they claim, and

not writing tests for the new submitted features.

A big problem is that these remote, part time contractors aren't in the office to respond immediately if there's a problem with their code.

Also, I'm the only full time developer on the app, and we can't afford to have my time spent checking and debugging others' code.

My idea is to adopt an open-source working style with them. I.e., would a big, important project (like Linux, Ruby, Rails, etc.) accept the proposed changes? We find out the criteria they have and then enforce that. We let go any contractor who doesn't play by the rules.

Is this the way to handle the relationships?

EDITED: To highlight the very part-time nature of the contractors. Less than 10 hours per week, usually 2-5.

答:
One thing I kept trying to get across in my previous company with limited success is that a project needs to maintain a minimum thinker-to-doer ratio, if you get to the threshold and go beyond that, you'll find yourself in a situation that you are in.  Way too many people who simple "do" the tasks are actually introducing more damage than good.

That's why I kept telling my boss and his boss that we need to spend time and invest in people. Give them some freedom and also more responsibility (if they choose to have it, don't shove it down their throats) and promote more thinking and taking ownership for the product.

However, everything I've dealt with has been internal within our own development team with full-time people on it. I've never been in your situation and it almost seems that contractor by its definition is a "doer", but then again, not necessarily.

So my only advice, and I'm making most of this up would be:

See if you can get one more permanent person on your team to help you with reviews and monitoring

Limit number of contractors you work with so that a) you only keep the top N which cause the least amount of overhead and b) you have more time to do your job, not just do reviews all day

Identify good, long-term contractors and try to convert some of them into "thinkers".  If you like working with them and they like working with you and you already established expectations, see if you can establish some kind of hierarchy where those guys would actually review work of other contractors.

As you suggested, establish some base guidelines that everyone should follow and when you do a review, if those guidelines aren't met, reject it with minimal effort on your part.

Unfortunately, IMO last thing you want to do is stop monitoring/reviewing/mentoring them.  As Dan suggested in the comments, as a team lead, this is your higher priority than delivering your own code.