问:
Examples of Finite State Machines
I'm looking for good examples of finite state machines; language isn't particularly important, just good examples.

Code implementations are useful (generalized pseudo-code), but it's also very useful to gather the various uses of FSM's.

Examples don't necessarily need to be computer based, for example Mike Dunlavey's Railroad networks example, is very useful.

答:
In practice, State Machines are often used for:

Design purposes (modeling the different actions in a program)

Natural language (grammar) parsers

String parsing

One example would be a State Machine that scans a string to see if it has the right syntax. Dutch ZIP codes for instance are formatted as "1234 AB". The first part may only contain numbers, the second only letters. A State Machine could be written that keeps track of whether it’s in the NUMBER state or in the LETTER state and if it encounters wrong input, reject it.

This acceptor state machine has two states: numeric and alpha. The state machine starts in the numeric state, and starts reading the characters of the string to check. If invalid characters are encountered during any of the states, the function returns with a False value, rejecting the input as invalid.

Python code:

```<code>import string

STATE_NUMERIC = 1
STATE_ALPHA = 2

CHAR_SPACE = " "

def validate_zipcode(s):
cur_state = STATE_NUMERIC

for char in s:
    if cur_state == STATE_NUMERIC:
        if char == CHAR_SPACE:
            cur_state = STATE_ALPHA
        elif char not in string.digits:
            return False
    elif cur_state == STATE_ALPHA:
        if char not in string.letters:
            return False
return True

zipcodes = [
    "3900 AB",
    "45D6 9A",
]

for zipcode in zipcodes:
    print zipcode, validate_zipcode(zipcode)
</code>```

Source:
(Finite-) State Machines in practice

Title: Examples of Finite State Machines

Body:
In practice, State Machines are often used for:

Design purposes (modeling the different actions in a program)

Natural language (grammar) parsers

String parsing

One example would be a State Machine that scans a string to see if it has the right syntax. Dutch ZIP codes for instance are formatted as "1234 AB". The first part may only contain numbers, the second only letters. A State Machine could be written that keeps track of whether it’s in the NUMBER state or in the LETTER state and if it encounters wrong input, reject it.

This acceptor state machine has two states: numeric and alpha. The state machine starts in the numeric state, and starts reading the characters of the string to check. If invalid characters are encountered during any of the states, the function returns with a False value, rejecting the input as invalid.

Python code:

import string

STATE_NUMERIC = 1
STATE_ALPHA = 2

CHAR_SPACE = " "

def validate_zipcode(s):
cur_state = STATE_NUMERIC

for char in s:
    if cur_state == STATE_NUMERIC:
        if char == CHAR_SPACE:
            cur_state = STATE_ALPHA
        elif char not in string.digits:
            return False
    elif cur_state == STATE_ALPHA:
        if char not in string.letters:
            return False
return True

zipcodes = [
    "3900 AB",
    "45D6 9A",
]

for zipcode in zipcodes:
    print zipcode, validate_zipcode(zipcode)

Source:
(Finite-) State Machines in practice


问:
Is verification and validation part of testing process?
Based on many sources I do not believe the simple definition that aim of testing is to find as many bugs as possible - we test to ensure that it works or that it does not. E.g. followint are goals of testing form ISTQB:

Determine that (software products) satisfy specified requirements ( I think its verificication)

Demonstrate that (software products) are fit for purpose (I think that is validation)

Detect defects

I would agree that testing is verification, validation and defect detection. Is that correct?

答:
I think you got it exactly right.

Verification and Validation are different things and are in fact pretty well defined. Although I don't like the document very much the ISO 9000ff is highly relevant for QA and defines Verification as comparing a product with its requirements and Validation as checking if it actually fits the needs of the customer/user and we all know this can differ.

Both can be done through testing. Verification would lead to tests generated form requirements. Validation leads to test done by Tests without direct reference to requirements. I think this is often called explorative testing. Obviously it must be done by people with a real understanding of the real needs of the users, so alpha and beta testing by real users are obvious options.

On a theoretic basis I guess one could argue anything covered by the first two isn't a bug and therefore finding bugs as a separate goal doesn't make sense. But I think there are things that you can't really verify or validate. For example security: How do you validate or verify that a software system is safe against attacks? Instead you try to find vulnerabilities. This search doesn't verify or validate anything if it fails to find problems, but it finds bugs if it succeeds.

ContentLicense: CC BY-SA 3.0


问:
Why would an employer ask for a 'long' code sample?
What would a large project that spanned multiple files and >1000 lines show to an employer that a few individual files and a couple hundred lines couldn't capture?</p>

答: Mostly because of the verbosity of the languages. After all 1000 lines of code in Java/C# especially if over engineered do not allow to cram much functionality inside. So he just have to ask for something big enough to have at least some insight in how you work or think.</p>


问:
Best place to put classes that extend the .net framework?
I have no clue where to put the following class and I've noticed I just keep putting them in a helpers folder which isn't much helpfull towards reusability in future projects.

Example:
I want to have the ability to use the DisplayNameAttribute together with resource files. In order for this to work I made a LocalizedDisplayNameAttribute which inherits the ´DisplayNameAttribute´ and adds the following properties DisplayNameResourceName and DisplayNameResourceType.

In which namespace/location would you place such a class which is likely to be reused in future projects?

答:
I think the best way to do this is putting all helper classes and methods in a separate project, and then reference this project in each solution you create. Much easier than copying folders from place x to place y.

This project with all kinds of extensions, helpers etc, can be called something like "Company.Core", or similar.

Example (your attributes):

```<code>using Company.Core.Attributes;

// ....

[LocalizedDisplayNameAttribute.DisplayNameResourceName("ResourceName"),
...]
public string Example { get; set; }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think the best way to do this is putting all helper classes and methods in a separate project, and then reference this project in each solution you create. Much easier than copying folders from place x to place y.

This project with all kinds of extensions, helpers etc, can be called something like "Company.Core", or similar.

Example (your attributes):

using Company.Core.Attributes;

// ....

[LocalizedDisplayNameAttribute.DisplayNameResourceName("ResourceName"),
...]
public string Example { get; set; }


问:
How long can a programmer concentrate in a day?
There is this question ( which is now closed as not constructive) that asked about the average productivity per day.

My question is, is there any scientific study on the productivity of programmers? I can't help but feel that doing 8 hours of quality programming work from Monday to Friday consistently is very hard. And if yes, is there any literature that investigates this?

答:
I don't think there would be any, for the simple reason that you can't study it objectively:

1. It varies from project to project

I had to work on projects so boring that working one hour per day was already too long. With badly written requirements, badly written existent codebase and no quality whatsoever required from me, I could try my best to concentrate, and find myself browsing Programmers.SE or doing other unrelated stuff for the last three hours.

I also had to work on projects so exciting that I spend 60 hours in a week on them (without being forced to), writing not so bad source code.

In those two cases, I was the same person. In the first case, my productivity was terrible and I was able to concentrate 0 hours per week. In the second one, my productivity was high and I was able to concentrate more than 40 hours per week.

2. It varies from company to company

As an experience, you can put two developers in different working conditions on the same project. One developer will work in her own office with a dual screen fast PC, comfortable chair, etc. The second one will have a desk in the middle of a call center, with an old PC, a 56k internet connection and a 50 MB limitation for all the personal files (and no right to use USB sticks).

Two weeks later, invert the working conditions. See the difference?

3. It varies from day to day

Imagine that on Thursday, the developer knows that he will be able to quickly solve the remaining issues, that the work to do is interesting, and everything is exciting and promising. She also learnt that she was promoted, and her husband contacted her to announce some good news related to her personal life.

On Friday, the same developer finds her old dog dead and her car won't start. She's late at work and spills her coffee on her desk, etc. How would this affect her daily performance, compared to the day before?


问:
Good example of gprof, for iOS project
The GNU profiler gprof, can be used to profile any application right on the device, allowing real world profiling.

As Xcode 4.5 based on LLVM plus it has GNU Debugger, Profiler, and others.

I need a better example, implementation example, for iOS projects.

答:
Utilize the followings

http://docs.freebsd.org/44doc/psd/18.gprof/paper.pdf

http://oprofile.sourceforge.net/about/

Title: Good example of gprof, for iOS project


答:
Lets see this from a practical point of view. For testing, you need to define test cases. Typically, you define test cases along the specified requirements, and they should cover "happy day" cases as well as "edge cases" - especially the latter are often defined with the intention of breaking the software. When some of your tests fail, they show up bugs/defects. When you have a reasonable amount of test cases for each requirement, and all that tests pass, you may not have fully proven that all requirements are fulfilled, but you have improved the probability for that, thus done some verification.

So for that part of the question, finding bugs and verification may be just two sides of the same process:

tests fail: defects found

tests pass: verification done (at least, to some degree, if you provide enough and the right tests)

Concerning validation: as @Mert pointed out, validation can be done by acceptance testing, but not by other forms of testing. Thus testing in general causes no validation, only when done as acceptance testing, by some of the potential users.

Title: Is verification and validation part of testing process?

Body:
Based on many sources I do not believe the simple definition that aim of testing is to find as many bugs as possible - we test to ensure that it works or that it does not. E.g. followint are goals of testing form ISTQB:

Determine that (software products) satisfy specified requirements ( I think its verificication)

Demonstrate that (software products) are fit for purpose (I think that is validation)

Detect defects

I would agree that testing is verification, validation and defect detection. Is that correct?


问:
Unit testing internal components
To what extent do you unit test internal/private components of a class/module/package/etc? Do you test them at all or do you just test the interface to the outside world? An example of these internal is private methods.

As an example, imagine a recursive descent parser, which has several internal procedures (functions/methods) called from one central procedure. The only interface to the outside world is the central procedure, which takes a string and returns the parsed information. The other procedures parse different parts of the string, and they are called either from the central procedure or other procedures.

Naturally, you should test the external interface by calling it with sample strings and comparing it with hand-parsed output. But what about the other procedures? Would you test them individually to check that they parse their substrings correctly?

I can think of a few arguments:

Pros:

More testing is always better, and this can help increase code coverage

Some internal components might be hard to give specific inputs (edge cases for example) by giving input to the external interface

Clearer testing. If an internal component has a (fixed) bug, a test case for that component makes it clear that the bug was in that specific component

Cons:

Refactoring becomes too painful and time-consuming. To change anything, you need to rewrite the unit tests, even if the users of the external interface are not affected

Some languages and testing frameworks don't allow it

What are your opinions?

答:
The approach to FSM-based code is a bit different from that used traditionally. It is very similar to what's described here for hardware testing (which is typically also an FSM).

In short, you create a test input sequence (or a set of test input sequences) which should not only produce a certain output, but also when producing a particular "bad" output lets identifying the failed component by the nature of failure.
The approach is quite scalable, the more time you spend on the test design the better the test will be.

This kind of testing is closer to what is called "functional tests" but it eliminates the need to change tests every time you slightly touch an implementation.

Title: Unit testing internal components


问:
Is a code review which uses only code comments a good idea?

Preconditions

Team uses DVCS

IDE supports comments parsing (like TODO and etc.)

Tools like CodeCollaborator are expensive for budget

Tools like gerrit are too complex for install or not usable

Workflow

Author publishes somewhere on central repo feature branch

Reviewer fetch it and start review

In case of some question/issue reviewer create comment with special label, like "REV". Such label MUST not be in production code -- only on review stage:

```<code>$somevar = 123;
// REV Why do echo this here?
echo $somevar;
</code>```

When reviewer finish post comments -- it just commits with stupid message "comments" and pushes back

Author pulls feature branch back and answer comments in similar way or improve code and push it back

When "REV" comments have gone we can think, that review has successfully finished.

Author interactively rebases feature branch, squashes it to remove those "comment" commits and now is ready to merge feature to develop or make any action that usualy could be after successful internal review

IDE support

I know, that custom comment tags are possible in eclipse & netbeans. Sure it also should be in blablaStorm family.

Questions

Do you think this methodology is viable?

Do you know something similar?

What can be improved in it?

答:
I would supplement the comments in the code with a companion document. This would summarize the findings and live on after the comments were removed. The advantages of this would be:

compactness. If the person routinely fails to check that a pointer passed in isn't null (or some other common beginner error in the language you're using) the reviewer can leave dozens of REV comments to that effect, and in the document can say "I found 37 places where pointers were not checked first" without listing them all

place for praise. A comment like REV this is a nice design just seems kind of odd, but my code reviews often include approval as well as corrections

interactivity. Your sample comment is "why did you do this?" and it's a very typical one. A comments-only approach doesn't support a conversation. The person can change their code and delete the comment, or delete the comment. But "why did you do this?" and "please change this, it's wrong" are not the same thing.

keeping a record. A later reviewer can check whether the code was actually changed, or the comments were just removed. They can also check that the comments have been "taken on board" and the developer is no longer making the same mistakes in a subsequent review.

I would also use a work item for doing the review and responding to the review, and associate the checkins with it. That makes it easy to find the comments in an old changeset, and to see how each was handled in another changeset.


问:
How do you stay motivated for hobby projects?
I started seriously programming as a hobbiest, student and then intern about 4 years ago and I've always done small projects on the side as a learning exercise.  Schools over now though, and I spend my days at work as a software developer. I would still love to do projects on the side to learn about areas in computer science that I'm not exposed to at work, but I've noticed that after 8 hours of starring at an IDE it's far to tempting to veg out.  Any time I do get up the gumption to work on something for a few hours lately it's gotten left by the wayside.

Anyone have any advice for sticking with side projects when you spend most of your day coding?

答:
Things that keep me motivated:

Pick a hobby project that you are really really interested in, and that you have no chance of ever doing anything like that at work. Start a game, a compiler, or anything else interests you. Don't pick something only because you think you should do this to help your career. Pick something you just want to try, and may have no value to your career.

Try to get some other people involved too at an early stage. This can be starting an open source project and inviting other programmers. But this can be as simple as telling your friends to try out the new piece of software you are writing. As soon as you start getting feedback, you will feel the need to keep making it better.


答:
Software testing is not same as QA. You got that right. Software testing overall includes many stages (smoke, unit, regression, integration, user acceptance, etc. ) in itself.

Thus, to assure that software works in accordance to the requirements is the man goal of QA (quality assurance specialist - aka used to be simply called testers years ago). However, it is not just testing. QA ensures that proper set of processes to perform quality check of the product in question are in place, or at least taken into design phase of the project.

Thus, ideally you would expect your QA to verify the application against set of requirements and not just try to test it by breaking the software and finding defects.


答:
These studies were done almost 100 years ago. Many times over.

Relations between industry and labor weren't exactly cozy at the start of the 20th century. Industry initially rejected demands from labor unions for a 40 hour week. A few reluctantly complied, and they quickly found that errors and rework went down, quality went up, productivity went up, and, most important of all, profits went up. The news spread fast, and so did research. There are some productivity gains with longer work weeks so long as those longer weeks aren't too long and are isolated. Quality, productivity, and profits suffer when those extended work hours last for any significant period of time. The need for extended bouts of long work weeks became viewed by management and stockholders as a key sign of inept management.

We knowledge workers and our managers have forgotten all this. Long hours are standard in the sciences, technology, engineering, and math. The arguments that those 40 hour weeks don't apply because we are using our minds rather than our bodies are fallacious. Even in physical labor jobs, the key problems with excessive work hours are largely mental rather than physical. Long hours make us stupid and error prone.

There's a reason that extreme programming has adopted a 40 hour week as one of its key tenets. It doesn't matter whether the product is manufactured or is programmed into existence. Longer hours are counterproductive and hurt the product.

Title: How long can a programmer concentrate in a day?

Body:
There is this question ( which is now closed as not constructive) that asked about the average productivity per day.

My question is, is there any scientific study on the productivity of programmers? I can't help but feel that doing 8 hours of quality programming work from Monday to Friday consistently is very hard. And if yes, is there any literature that investigates this?


问:
Should a domain expert make class diagrams?
The domain expert in our team uses UML class diagrams to model the domain model.

As a result, the class diagrams are more of technical models rather than domain models (it serves of some sort of technical specifications for developpers because they don't have to do any conception, they just have to implement the model).

In the end, the domain expert ends up doing the job of the architect/technical expert right?

Is it normal for a domain expert (not a developer or technical profile) to do class diagrams?

If not, what kind of modeling should he be using?

答:
Is it normal for a domain expert to do class diagrams?

If a domain expert does class diagrams in the traditional sense*, then the answer is "absolutely not". You should resist this as much as you can, for everyone's benefit.

I have been in a situation like that in a start-ups many years ago, where a very strong domain expert has been trying to map a business solution in very technical terms. The problem with that was that rather than explaining the business aspects that the team was to address, he provided lots of technical details of a solution that he built in the past. Eventually we agreed that he should explain to us what to do rather than how to do it, and together we made that project a success.

* Class diagrams are very flexible. They do not necessarily have to reflect classes in the computer science sense of the word. You can re-use the same drawing technique (boxes, arrows, inheritance, and so on) to map out relationships among business concepts from the real world. In this case, using class diagrams by a domain expert would be appropriate.


答:
It actually depends on the level of details in the class diagrams and the way they are used.

An important distinction that has to be made: a UML class is not (necessarily) the same as a programming language class. It denotes domain concepts that may be implemented in many different ways (or not at all).

Defining these concepts is a job for the domain experts. The specific format in which they will do so doesn't matter too much as long as it is clear enough (that is the hard part). So, it may be a verbal description or, as in your case, a UML diagram.

Now the thing is that these UML diagrams your domain experts produced don't need and most of the time shouldn't be used as blueprints for the code. They are there only to make it possible for the development team to understand the business domain. Then, if they feel that it is necessary, developers (including the system architects) create a different model that also takes into consideration technical limitation which are not known to the domain expert. Also, the format of that model is not particularly important. It may be another UML model, but also it can be a combination of code and project documentation.

Example:

Consider a banking software system. In this case the domain expert is someone who has the expertise in banking. His job is to communicate the business requirements to the development team and may choose to do so by modeling the document flow used by the bank. Now, the thing is that these documents (in the form in which they appear when printed and filled out by hand) are typically extremely un-normalized and contain lots of redundant data scattered across different forms. The model produced by the domain expert may contain all these redundancies, but the model implemented by the development will typically eliminate them where necessary. Nevertheless, both models had their use in the development process.

Title: Should a domain expert make class diagrams?

Body:
The domain expert in our team uses UML class diagrams to model the domain model.

As a result, the class diagrams are more of technical models rather than domain models (it serves of some sort of technical specifications for developpers because they don't have to do any conception, they just have to implement the model).

In the end, the domain expert ends up doing the job of the architect/technical expert right?

Is it normal for a domain expert (not a developer or technical profile) to do class diagrams?

If not, what kind of modeling should he be using?


答:
Is it normal for a domain expert (not a developer or technical profile) to do class diagrams?

NO, it is not usual thing to encounter, however there are always some exceptions.

Domain expert may build UML diagrams to capture business process and actors involved in it. That probably would be the best helpful document they can make ready for the project architect and entire team. Because, having 80-150 page long documentation document is hard to grasp and visualize by reading. In another words, business workflow, data-flow and decision processes-flow should be captured by that person.

However, detailed class diagram does require technical knowledge set of DDD (Domain-driven design) or Object-oriented modeling with good understanding in Class diagram.


答:
To stay motivated of something that doesn't bring you money you must have at least one of the element below:

you are proud of what you do (others can see it)

you are deeply interested of passionated by it. The simple fact that you achieve things give you high satisfaction

doing it allows you interesting social interactions

What I've put above is the three reasons why people begin to work as a volounteer in an organisation. Those are the real reasons, not the reason the person think.

The most effective but the most difficult to get is the first one.

If you are doing a software, release it!

Title: How do you stay motivated for hobby projects?

Body:
I started seriously programming as a hobbiest, student and then intern about 4 years ago and I've always done small projects on the side as a learning exercise.  Schools over now though, and I spend my days at work as a software developer. I would still love to do projects on the side to learn about areas in computer science that I'm not exposed to at work, but I've noticed that after 8 hours of starring at an IDE it's far to tempting to veg out.  Any time I do get up the gumption to work on something for a few hours lately it's gotten left by the wayside.

Anyone have any advice for sticking with side projects when you spend most of your day coding?


问:
C programming in 2011
Many moons ago I cut C code for a living, primarily while maintaining a POP3 server that supported a wide range of OSs (Linux, *BSD, HPUX, VMS ...).

I'm planning to polish the rust off my C skills and learn a bit about language implementation by coding a simple FORTH in C.

But I'm wondering how (or whether?) have things changed in the C world since 2000.  When I think C, I think ...

comp.lang.c

ANSI C wherever possible (but C89 as C99 isn't that widely supported)

gcc -Wall -ansi -pedantic in lieu of static analysis tools

Emacs

Ctags

Autoconf + make (and see point 2 for VMS, HP-UX etc. goodness)

Can anyone who's been writing in C for the past eleven years let me know what (if anything ;-) ) has changed over the years?

(In other news, holy crap, I've been doing this for more than a decade).

答:
2) and 3) have changed. C99 is mainstream, C90 is turning more and more obsolete. gcc -Wall -std=c99 -pedantic.

Apart from that, the two most noteworthy changes not already addressed in other answers are:

C11. ISO 9899:2011.

MISRA-C:2004.

Title: C programming in 2011


答:
It depends on the project.

If i have something big and just challenging enough that I can get my teeth into I can work for a good few hours without even realising and work 12+ hours in a day. However if I don't really know what I'm doing, have no pressure or don't see any value in the work then I get distracted every half hour.

I'm sure there are books around which describe how to improve productivity (though you have to make sure you find one written by a developer not a buzz word book written by a 'management consultant') however I don't think there's any concrete metrics out there.


问:
What causes overtime and how can it be avoided?
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.

答:
Your manager is either ignorant (he simply repeats what he learnt, and honestly thinks it is the way to go) or he does that on purpose and knows it's bad.

In both case it's a bad manager. But like everyone, he can change! Will you help him figure it out by leaving?

Regarding your last question, I think that the perfect employee must sometimes do sacrifices for his company, if the company do sacrifices sometimes too. An exemple? Because lack of cash I decided to cut my own salary for a full year in order to be able to pay everyone. No one knew that, but I'm sure that if they did, they would have helped me a bit when we had to finish that userstory before monday.


答:
The business analyst for my current team does exactly the same :) I wouldn't say it's commonplace, but it is a typical flaw for someone with a technical background who evolved into a business analyst/domain expert.

There are many ways to model a domain, from UML diagrams to words on a whiteboard to drawings on a piece of paper. The important thing is not the model's aspect but what it conveys. You should also keep in mind that modelling the domain is collaborative work and implies conversation between the domain expert and technical people. An environment where the business expert produces all the models (not to mention low-level technical models) alone and imposes them on the dev team seems somewhat dysfunctional to me.


问:
Is having functionality in DB a road block to scalability?
I may not be able to give the right title to the question. But here it is,

We are developing financial portal for wealth management. We are expecting over 10000 clients to use the application. The portal calculates various performance analytics based on the the technical analysis of the stock market.

We developed lot of the functionality through Stored procedures, user defined functions, triggers etc. through Database. We thought we can gain huge performance boost doing stuff directly in database than through C# code. And we actually did get a huge performance boost.

When I tried to brag about the achievement to our CTO, he counter questioned my decision of having functionality implemented in database rather than code. According to him such applications suffer scalability problems. In his words "These days things are kept in memory/cache. Clustered data is hard to manage over time. Facebook, Google have nothing in database. It is the era of thin servers and thick clients. DB is used only to store plain data and functionality should be completely decoupled from the database."

Can you guys please give me some suggestions as to whether what he says is right. How to go about architect such an application?

答: Anytime anyone mentions scalability and Google/Facebook/Twitter/etc, it's a red herring.  Unless you're providing essentially the same service, what works for them may not be appropriate for you.  In general, if you can scale from a single machine to an eight-machine cluster, you've probably covered all your bases.  Unless you have a hard business requirement to serve 20M page views a day, don't worry about hyper-scaling.  Do what makes sense for your application's real requirements, and worry about scaling up when it becomes obvious you need to.  And don't forget, most database servers can be clustered too, so just because it's all in one database doesn't mean it's on one server.


问:
Which .NET REST approach/technology/tool should I use?
I am implementing a RESTful web service and several client applications that are mostly in Silverlight. I am finding a litany of options for developing both the server-side and client-side of the API but am not sure which is the best approach. I'm concerned about stability as well as a platform that will continue to exist a few months from now.

We started using the REST Starter Kit with .NET 3.5 but moved to the new WCF Web API when updating to .NET 4.0. All of their documentation indicates that WCF Web API is the replacement for the RSK. However, Web API is only in Preview 4 and does not include support for Silverlight or Windows Phone 7 clients (yet).

WCF Web API looks like a wrapper on top of the WCF WebHttp Services stuff provided in the System.ServiceModel.Web library which makes me think that maybe it would be simpler to just go with the built-in stuff but Web API does offer some nice features.

I am specifically tied-up trying to determine the best course for the client-side. My main requirement is that I need to support deserializing into my client-side objects quickly and easily. The Web API offers a nice client library but doesn't have a Silverlight version.

I'd like to use the latest approach and the toolset that is being actively developed and supported.

Is the REST Starter Kit really obsolete?

Has anyone had any success implementing the WCF Web API toolkit?

Is there merit to using either of these over the built-in WCF WebHttp Services features found in System.ServiceModel.Web?

Is there a single solution that works for any client (web, Silverlight, etc.)?

What suggestions do you have?

答:
The WCF Web API doesn't provide any metadata information you would use to generate a service proxy and thus, be able to add a service reference. It is intended for the easy production of REST services under the WCF umbrella, just as you do with the ASP.NET MVC 4 Web API framework.

Therefore there is no support for WP7 or Silverlight, but it is almost perfect for the rest of the web.

However, WCF Data Services looks like a right candidate, it allows you to create RESTful services and easily consume them with Silverlight.


问:
What kind of permission is this? (Groups+Roles)
I'm starting to need an access control for roles in my app.

I don't know much of this, but I understand how vBulletin works:

```<code>I create groups, then give permissions to groups.
</code>```

I think that what I need is the Role Bases Access Control (RBAC) , but i'm not sure, because I need groups to give permissions instead of single users (Maybe it's not that complicated to achieve).

Example of what I'm thinking:

Given a post:

```<code>Editor's Group has permission to view it before it's published.
Editor's Group has permission to edit its content.
Public Group (Default) has not permission to view it before it's published.
Admin Group has permission to delete the post.
</code>```

So basically I wan't orientation about if RBAC is what I need.

And also, how would it be good to store group membership in a user, for example, would be good to have: ID NAME PASSWORD GROUPS (1, MyName, MyPassword, 1/2/3/4/5) and explode it via PHP or one registry for every Group membership in a table named permissions, example: USERID, USERGROUP values (1, 1), (1, 2)

Maybe should be the second way because of the formal norms but I didn't study yet Databases 1 at college.

答:
Allocate permissions to roles and then roles to users.

As for storage personally I'm quite fond of the unix method which uses one numerical value to store the roles. Each role has a numerical value and then all the roles a user has are added together, for example:

Role 1 = 1

Role 2 = 2

Role 1 and 2 = 3

However this is going to get confusing if you have a lot of roles.

The easiest human readable way to implement it is to give each user a unique generated ID number (use this as your primary key) in the user table and the same for each role in the roles table. Then use an intermediate table to match roles to users. NB: This intermediate table should have 2 columns so that a user id would have multiple entries if they have multiple roles.

This is also easier to extent than the previously mentioned method.


答:
If you're forced into working extra time, you should be able to take some time off later.

Work hard - rest hard. That's just the way it works, or at least should work.

When I work overtime and don't seem to get anything out of it, I think:

Am I learning?

If the answer to that question is yes, then the extra effort you put in at work is also an investment in yourself and your skills. That's worth a lot.

Still, you should get some kind of compensation for being forced into working extra time. If you don't get anything, it's a huge blow to the company you work for, because you probably won't stay for that much longer. And it's hard to find other developers who are willing to work extra for basically nothing.

Title: What causes overtime and how can it be avoided?

Body:
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.


问:
How can you tell whether to use Composite Pattern or a Tree Structure, or a third implementation?
I have two client types, an "Observer"-type and a "Subject"-type. They're both associated with a hierarchy of groups.

The Observer will receive (calendar) data from the groups it is associated with throughout the different hierarchies. This data is calculated by combining data from 'parent' groups of the group trying to collect data (each group can have only one parent).

The Subject will be able to create the data (that the Observers will receive) in the groups they're associated with.
When data is created in a group, all 'children' of the group will have the data as well, and they will be able to make their own version of a specific area of the data, but still linked to the original data created (in my specific implementation, the original data will contain time-period(s) and headline, while the subgroups specify the rest of the data for the receivers directly linked to their respective groups).

However, when the Subject creates data, it has to check if all affected Observers have any data that conflicts with this, which means a huge recursive function, as far as I can understand.

So I think this can be summed up to the fact that I need to be able to have a hierarchy that you can go up and down in, and some places be able to treat them as a whole (recursion, basically).

Also, I'm not just aiming at a solution that works. I'm hoping to find a solution that is relatively easy to understand (architecture-wise at least) and also flexible enough to be able to easily receive additional functionality in the future.

Is there a design pattern, or a good practice to go by, to solve this problem or similar hierarchy problems?

EDIT:

Here's the design I have:

The "Phoenix"-class is named that way because I didn't think of an appropriate name yet.

But besides this I need to be able to hide specific activities for specific observers, even though they are attached to them through the groups.

A little Off-topic:

Personally, I feel that I should be able to chop this problem down to smaller problems, but it escapes me how. I think it's because it involves multiple recursive functionalities that aren't associated with each other and different client types that needs to get information in different ways. I can't really wrap my head around it. If anyone can guide me in a direction of how to become better at encapsulating hierarchy problems, I'd be very glad to receive that as well.

答:
I know this is Kind of Obvious but I am going to say it anyway,
I think you should take a look at the Observer Pattern  you mentioned that you have an Observer Type and what you have looks kind of like the Observer Pattern to me.

couple of links:

DoFactory

oodesign

check those out.
 otherwise I would just Code what you have in your Diagram and then use the Design Pattern to simplify if necessary.   you already know what needs to happen and how the program is supposed to work.  Write some Code and see if it still fits.

OwnerDisplayName: Aske B.


答:
This is a pretty common task and has straight forward practices to follow and implement. You may choose one of the following approached that suits your requirements:

Level based

Group based

Responsibility based

User based - you already exclude that and it is wise decision

From your description of issue, it sounds like role-based access control would make more sense.  Here is a link to a list of a few implementations for PHP projects. I'd suggest glancing through and picking the one that fits your specific needs: RBAC+PHP

In the case, if none of the mentioned above works out, here is a tutorial on how to build your own (complete with source): PHP 5 CMS Framework Development

Title: What kind of permission is this? (Groups+Roles)

Body:
I'm starting to need an access control for roles in my app.

I don't know much of this, but I understand how vBulletin works:

```<code>I create groups, then give permissions to groups.
</code>```

I think that what I need is the Role Bases Access Control (RBAC) , but i'm not sure, because I need groups to give permissions instead of single users (Maybe it's not that complicated to achieve).

Example of what I'm thinking:

Given a post:

```<code>Editor's Group has permission to view it before it's published.
Editor's Group has permission to edit its content.
Public Group (Default) has not permission to view it before it's published.
Admin Group has permission to delete the post.
</code>```

So basically I wan't orientation about if RBAC is what I need.

And also, how would it be good to store group membership in a user, for example, would be good to have: ID NAME PASSWORD GROUPS (1, MyName, MyPassword, 1/2/3/4/5) and explode it via PHP or one registry for every Group membership in a table named permissions, example: USERID, USERGROUP values (1, 1), (1, 2)

Maybe should be the second way because of the formal norms but I didn't study yet Databases 1 at college.


问:
Is it necessary to create a database with as few tables as possible
Should we create a database structure with a minimum number of tables?

Should it be designed in a way that everything stays in one place or is it okay to have more tables?

Will it in anyway affect anything?

I am asking this question because a friend of mine modified some database structure in mediaWiki. In the end, instead of 20 tables he was using only 8, and it took him 8 months to do that (it was his college assignment).

EDIT

I am concluding the answer as: size of the tables does NOT matter, until the case is exceptional; in which case the denormalization may help.

Thanks to everyone for the answers.

答:
I think the number of tables matters and can have a great impact on performance if you chose to split data that should, for all business intents and purposes, stay together, into multiple tables (i.e. so you'd have a normalize database). Usually when you do this, you'll be forced to to JOIN Operations (or non-SQL equivalent) in order to get all the data that you need and for large enough tables structured like this, the performance bogs down fast.

I'm not gonna get into details, but I think that the very real fact that the number of tables can influence performance is one of the reasons why noSQL databases such as Cassandra, Mongo, and Google BigTable (sic!) have been invented, and that's also why they encourage de-normalization of data (and consequently avoiding large number of tables/collections, etc).

Same could be said for search servers such as Apache's Solr which doesn't really encourage or easily facilitates splitting your documents into multiple "tables" or "types of entries" encouraging you instead to have a "one encompasses all" schema that has fields common to all the document types that you want to index (and consequently avoid having to do JOIN-like operations).

I'm not saying that the simple fact of having x tables in a schema will necessarily make it slower than a schema with x/2 tables all the times, but there are certain contexts in which it can lead to slow-downs due to consequent extra operations needed to aggregate the data in all those tables. Continuing on this I also don't think that it's ok to say "any number of tables and extreme normalization of the data has no impact what so ever on performance".


问:
Should I have a separate method for Update(), Insert(), etc., or have a generic Query() that would be able to handle all of these?
I'm currently trying to write a class library for a connection to a database.  Looking over it, there are several different types of queries:  Select From, Update, Insert, etc.

My question is, what is the best practice for writing these queries in a C# application?

Should I have a separate method for each of them(i.e. Update(), Insert()), or have a generic Query() that would be able to handle all of these?  Thanks for any and all help!

答: Best practice is not to write such a lib at all. Use an OR mapper like MS entity framework or any of the available lightweight micro-ORMs (for example, see here https://stackoverflow.com/questions/5829891/which-micro-orm-to-use)</p>


答:
Looks like a bad manager but one thing is for sure sometimes we all have to give more than we get paid for. May be your Project is suffering and as a team you need to ensure that you, your Manager and the company succeed(this kind of team spirit is very rare most of the times Managers just USE thier employees).

Second thing you mentioned is.. Is it your company culture ? If this is the case you have no choice but to abide by it as long as you stay otherwise you will be singled out and than thrown out. It is not uncommon to see some companies over paying than the market standards and than asking thier employees for such thing.

Thirdly sometimes it is plain good to work more than your peers. It removes your peer competition and than you can stand up and ask for a raise/ more recognition/more responsibilities or a promotion.


问:
Downgrading from GPL v3 to GPL v2
I have this issue with licensing.

I downloaded a third-party class from GitHub and it's under the GPL v3 license. However, I used this class on another open-source project which is under the GPL v2 license, and submitting my script there, requires that everything is under GPL v2 from my side too.

Am I allowed to change the license for that class, even though I am not the author?

答:
I'm not a lawyer, but what I would do is read the license agreement of the GPLv2 work carefully.  It may allow you to release your derived work under the GPLv2 or later.  In that case, you can just release your combination as GPLv3.

It's very unlikely that you can take GPLv3 code and release it as GPLv2, so you'd have to ask the original author for permission.

Likely you can't do what you're trying to do.

OwnerDisplayName: Dugi

Title: Downgrading from GPL v3 to GPL v2


答:
One of the practices is the usage of ORM mapping frameworks (like Entity Framework, nHibernate, etc.)

You may utilize the power of LINQ syntax  with any .NET framework languages (C# and VB.NET particularly).

As a quick introduction, you may look at Getting Started with LINQ in C# and then with LINQ samples for C# while using these mentioned ORM's.

For some considerations, if you plan to skip ORM's then you may safely utilize stored procedures as a common way of maintaining SQL outside of C#.

Title: Should I have a separate method for Update(), Insert(), etc., or have a generic Query() that would be able to handle all of these?

Body:
I'm currently trying to write a class library for a connection to a database.  Looking over it, there are several different types of queries:  Select From, Update, Insert, etc.

My question is, what is the best practice for writing these queries in a C# application?

Should I have a separate method for each of them(i.e. Update(), Insert()), or have a generic Query() that would be able to handle all of these?  Thanks for any and all help!


答:
No, you are not.

As a rule of thumb, only the copyright holder (i.e., the author of your third-party library) is allowed to change the license under which code is distributed.

There is a weird exception in the GPL, but it doesn't help you: the FSF has historically encouraged that software be licensed under the GPLv2 or later.  Specifically, in most cases, you will find the following in the LICENSE file or equivalent:

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This means that GPLv2 code can be used in a GPLv3 project without incident.

Unfortunately, there is no clause, either in the GPLv2 or GPLv3, for using an earlier version of the GPL.  You'll either need to convince the GPLv2 project to upgrade to GPLv3 or avoid the GPLv3 library.

Title: Downgrading from GPL v3 to GPL v2

Body:
I have this issue with licensing.

I downloaded a third-party class from GitHub and it's under the GPL v3 license. However, I used this class on another open-source project which is under the GPL v2 license, and submitting my script there, requires that everything is under GPL v2 from my side too.

Am I allowed to change the license for that class, even though I am not the author?


答: As others have suggested, you can go with ORMs (unless you feel that ORMs are an antipattern). If for whatever reason you can't go with an existing ORM, you'll want to look up some DAO (Data Access Object) patterns to see if what fits. Another option would be to have the actual DML/SQL in a stored procedure and call the procedure by name. This would be more useful if your operations are a bit more complicated than just SELECT/UPDATE/INSERT.


答:
From the Free Software Fundation:

When we say that GPLv2 and GPLv3 are incompatible, it means there is
  no legal way to combine code under GPLv2 with code under GPLv3 in a
  single program. This is because both GPLv2 and GPLv3 are copyleft
  licenses: each of them says, “If you include code under this license
  in a larger program, the larger program must be under this license
  too.” There is no way to make them compatible. We could add a
  GPLv2-compatibility clause to GPLv3, but it wouldn't do the job,
  because GPLv2 would need a similar clause.

There is no way you can use GPLv2 and GPLv3 code in the same program and/or upgrade the licence.

Title: Downgrading from GPL v3 to GPL v2


问:
Status of stack based languages
I have recently become curious about Factor, which, as far as I understand, is the most practical stack-based language around. Forth seems not to be used much these days - I think it is because it was meant to be used on its own, instead of inside an operating system, although ports of course exist. It is also pretty low level. Joy is essentially dead, as the author stated that it does not make sense to mantain it in spite of adopting Factor.

The fact is that Factor itself does not seem much developed today. The GitHub repository does not seem very active, and a lot of stuff languishes in unmantained.

So, are there any other languages of this type that are more actively mantained? Are any in production use?

答:
I have no idea how you concluded that Factor's not actively developed.  Factor 0.95 was just released on August 17th, and if you look at the GitHub history page, you'll see that there are a lot of commits landing on a regular basis.  Most aren't done by Slava, as he's handed off the project to Doug Coleman (erg) and John Benediktsson (mrjbq7), but the language is continuing to see major improvements—some amazing.  (E.g., global-value numbering, which can result in massive speed boosts throughout the entire code-base by factoring out common expressions into a single location, just landed a few weeks ago.)

While you're right that there's a fair amount of code in unmaintained, there's a much greater volume of code that's in the core libraries—and in fact, the majority of code in unmaintained amounts to thought-experiments or code that no longer represents and ideal way to work in Factor.  I.e., in at least some circumstances, it'd be better called deprecated.

As far as other stack-based languages, there are some in active development, but none have the traction Factor has, and the only concatenative language I know with wide distribution other than Forth is PostScript—probably not what you want to write your next project in.  Unless you're unhappy with something Factor's offering, I think it's your best bet.  The community's friendly and active, and I'm sure would be thrilled to answer any questions you have or to accept any improvements you have in mind.

Title: Status of stack based languages


答:
on another open-source project which is under the GPL v2 license,

Many GPL v2 projects do not limit their license version to 2.0 only but allow any later version. Some even allow earlier ones (if no license version is specified with the software itself).

So you should double-check if that open source project really requires 2.0 only or if it is possible to add under the current version and allow the project to upgrade smoothly. You should add that open source project to your question to make it more exemplary (also the other one you want to take from).

Am I allowed to change the license for that class, even though I am not the author?

No. However what I wrote above for GPL v2 counts as well for GPL v3: If with that code no specific version has been named, you're allowed to use under any GPL version you wish, which would include GPL v2 then (note: then meaning if the needed pre-conditions are met).

Title: Downgrading from GPL v3 to GPL v2


答: The only hobby projects I've ever 'completed' are things that I actually need, or make my life easier. The downside is that once it's 'good enough', you lose the incentive to keep improving it (or cleaning up the code, etc.)


答:
First, a bit about the lingo. Insert, update are not queries. A query in RDBMS is strictly a SELECT (Or a a sub-statement having WHERE clause). The set of verbs: SELECT, INSERT, UPDATE, DELETE are action statements in Data Manipulation Language (DML).

Most answers so far revlove around how to achieve your objective, but your question is:

Should I have a separate method for each of them(i.e. Update(), Insert()), or have a generic Query()

The answer is yes. Each method should perform 1 function and return 1 type of result. You can re-use the connection logic or the ObjectContext (if you use Entity Framework) in each.

Most of the code for handling the database would typically live in a separate tier or layer from your presentation logic.


答:
Make sure you check exactly what the license on the GPLv2 software says. Many projects use the copyright notice from the FSF verbatim which includes this clause:

This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

If it does include this clause, then you can use both products under GPLv3. Some projects, notably the Linux kernel, do not include this clause. If this project doesn't include this clause, you are out of luck. The two versions of the license are not compatible without the "or any later version" clause and only the copyright holder can change the license.

If it does include this clause, you don't have to change either of the licenses, since GPLv2 with the "or any later version" clause is compatible with GPLv3.

Title: Downgrading from GPL v3 to GPL v2


问:
Amazon Kindle - Whispersync implementation?
For those who are not aware of Kindle's whispersync, here is how it works (from amazon.com):

"...Whispersync synchronizes the bookmarks and furthest page read among devices registered to the same account. Whispersync is on by default to ensure a seamless reading experience for a book read across multiple Kindles."

Can anyone give some details on how the Whispersync feature is implemented in Kindle and in the Backend of Amazon?

I am guessing this implementation involves a very simple hashmap for each user account. Each hashmap maps Books with satellite information about the book. Satellite information contains bookmarks, furthest page read, device on which it was read, etc..

Thanks!

答: Amazon provides some insight via their developer SDK aimed at games. I suspect you'll find little to no information on the actual internal implementation of WhisperSync on the grounds that it's a proprietary technology of a very large corporation. I'd recommend looking for "file synchronization over distributed devices" or something similar.</p>


问:
What are some really simple rules to keep a PHP codebase organized?
I'm new to PHP in a professional context. I want a few macro thumb rules to keep me on the enlightened path. Here are a few I'm proposing to myself:

no absolute paths in include|require(_once)? statements

no .. dirname(foo), or other means of walking up in include|require(_once)? statements

put libs on the include path, not in subdirectories

You can see that all of this is focusing on managing dependencies, because that is the problem I've encountered thus far.

What other thumb-rule solutions to macro level problems do you have?

答:
Without a little more context it's hard to suggest anything, but here are a few replies to your points you've made:

Dependencies - use Composer to manage your dependencies.  It'll dump them into vendor (configurable) and you'll be able to easily upgrade them or add new ones.  Don't use the include path unless its truly system wide stuff (such as phpunit).  If you have multiple apps on the same server, they may require different versions of libraries.

Relative Paths - use them where they make sense.  If your package is to be portable, it makes more sense to use relative paths.  __DIR__.'/some_subdirectory' is quite common and typically recommended for portability.  It really depends on what you are using it for though.

Loading Classes - the PHP community has widely adopted autoloading.  Composer will do this for you, but typically you see classes mapped to the filesystem

Company/Package/ClassName is located in src/Company/Package/ClassName.php (or that same Company/... structure inside a vendor directory).

Check out a new set of tutorials / guides called PHP: The Right Way which is trying to organize all these things into a large reference.  If you want the latest from the professional community, that's the place to check.  The web is littered with bad advice, so tread carefully!


答:
There are very common approaches which are true for every language. This set of principles may help to audit the code. I can think of a few coding practices that smell.

Error Suppression — From php.net:

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

Do yourself a favor and perform a find->all in your IDE for the @ symbol and divide and conquer.

Error Notices — Along the same vein as above, PHP allows you to set your error reporting level at runtime.  Many developers suppress simple warnings and notices.  You should use the [`error_reporting()`][2] function with a parameter of `E_ALL` or `E_STRICT` to display all PHP errors: `error_reporting(E_STRICT);`.

The global keyword — PHP allows programmers to define global variables to break function scope.  Scope is a little upside down in PHP...  If you create a variable outside of a function, it can be modified inside the function if it has been declared inside the function as [global][3].  That smells.

Deprecated Features — PHP is rife with functions and features, and many of them have been [deprecated][4].

 Hard-coded database query fragments - `mysql_query()` — If the devs haven't used or developed some kind of database abstraction, you're going to see a bunch of hard-coded database queries littered all over the place.  This should probably be moved to Code Smell #1.

Lots of Static Methods — maybe a code smell in any language, a developer can effectively globalize everything by making all of his classes/methods static.  Per  Jeremy Walton's suggestion, search for the word static and the Paamayim Nekudotayim operator (`::`).

Complex String Syntax and Variable Parsing — hard to explain on a dime, check out the reference here:  http://php.net/manual/en/language.types.string.php  Look for the section on Variable parsing a few screens down.  If this is abused it can be a nightmare to debug and/or understand.

Variable Variables — another whopper.  [This article][5] explains the madness best. Just search for two dollar signs `$$` to identify if they've succumbed to the [Dark Lord][6].

Tricky functions - `include_once()` and `require_once()` — These functions are fine, to be sure.  They are very useful when templating and separating view logic.  They ensure that a file is included only once when scripts are parsed.  However, if you see them used liberally in the **business logic** portion of the application, this is a red flag that the developer has written nested/circular includes, and may not be aware what portions of code have already been included.  This isn't *so* bad *per se*, but it's definitely a window into the competency-level of the developer(s).  Finally, @Phil suggests the use of autoloaders instead of `require_once()`.  [This article][7] explains autoloading in good detail.

String and Redundant Booleans — a lot of bad PHP code looks like this `if ($is_true == "true")`.  This is easy to search for, and harder to fix.  Something else to look out for--though not a PHP specific issue--is Redundant booleans:  `return ($isBad) ? true : false;`.

Short Tags — Here's what PHP.net has to say about short tags:

Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.

ASP style tags are even worse.

Accidental Assignment — More often than not, you'll see this happen in some non-critical component of the code, where it can sleep and/or lurk until you get an unexpected result one day:  `if ($foo = "Some Value")`.  This always evaluates `true`, of course, and was most likely due to a typo.  However, in rare circumstances you'll actually want to test for assignment.  If that is the case you should use double parenthesis to indicate intent:  `if (($foo = $this->bar()))`

Tools

Some tools you might look into:

PHP_CompatInfo can find dependencies (and thereby deprecated APIs)

PHP_CodeSniffer looks for coding styles foremost, but has some useful meta info on code quality

spike is a static security audit tool

maybe try RIPS a new static security checking tool

Quality Assurance tools - PHP_Depend might be most interesting to you

https://stackoverflow.com/questions/378959/is-there-a-static-code-analyzer-like-lint-for-php-files

nWire for Eclipse

There are more I think, but have no list. However it's all a bit involving (setup). So try one or two which sound most helpful for the start. After you've exhausted the visualization tools of your IDE.

References:

Organize your PHP Projects

Organize Your Next PHP Project the Right Way

Title: What are some really simple rules to keep a PHP codebase organized?

Body:
I'm new to PHP in a professional context. I want a few macro thumb rules to keep me on the enlightened path. Here are a few I'm proposing to myself:

no absolute paths in include|require(_once)? statements

no .. dirname(foo), or other means of walking up in include|require(_once)? statements

put libs on the include path, not in subdirectories

You can see that all of this is focusing on managing dependencies, because that is the problem I've encountered thus far.

What other thumb-rule solutions to macro level problems do you have?


问:
What can procs and lambdas do that functions can't in ruby
I've been working in Ruby for the last couple weeks, and I've come to the subject of procs, lambdas and blocks.  After reading a fair share of examples from a variety of sources, I don't how they're much different from small, specialized functions.  It's entirely possible that the examples I've read aren't showing the power behind procs and lambdas.

```<code>def zero_function(x)
    x = x.to_s
   if x.length == 1
    return x = "0" + x
   else
    return x
   end
end

zero_lambda = lambda {|x|
  x = x.to_s
   if x.length == 1
    return x = "0" + x
   else
    return x
   end
}

zero_proc = Proc.new {|x|
  x = x.to_s
   if x.length == 1
    puts x = "0" + x
   else
    puts x
   end
}

puts zero_function(4)
puts zero_lambda.call(3)
zero_proc.call(2)
</code>```

This function, proc, and lambda do the exact same thing, just slightly different.  Is there any reason to choose one over another?

答:
First of all, what do you mean by "functions"? Proc and lambda are "functions" -- and they evaluate to a function object, which could be assigned to a variable or used in any other expression. There is no other way to define a non-method "function" in Ruby.

def, by contrast, defines a method in the current module (you are always inside some module, either explicitly or implicitly). A method is obviously different from a bare function because a method implicitly has access to self and the instance variables of self.

More importantly, Proc and lambda are closures -- they capture local variables from the enclosing scope where they were created, and you can use those variables inside the closure. This allows function objects to hold state.

By contrast, defining a method inside another method definition will not give access to the local variables in the outer method body. So it's the same as if you moved the inner definition outside, except that the method defined by the inner def will only exist after the method defined by the outer def is run.


问:
Unit testing internal components
To what extent do you unit test internal/private components of a class/module/package/etc? Do you test them at all or do you just test the interface to the outside world? An example of these internal is private methods.

As an example, imagine a recursive descent parser, which has several internal procedures (functions/methods) called from one central procedure. The only interface to the outside world is the central procedure, which takes a string and returns the parsed information. The other procedures parse different parts of the string, and they are called either from the central procedure or other procedures.

Naturally, you should test the external interface by calling it with sample strings and comparing it with hand-parsed output. But what about the other procedures? Would you test them individually to check that they parse their substrings correctly?

I can think of a few arguments:

Pros:

More testing is always better, and this can help increase code coverage

Some internal components might be hard to give specific inputs (edge cases for example) by giving input to the external interface

Clearer testing. If an internal component has a (fixed) bug, a test case for that component makes it clear that the bug was in that specific component

Cons:

Refactoring becomes too painful and time-consuming. To change anything, you need to rewrite the unit tests, even if the users of the external interface are not affected

Some languages and testing frameworks don't allow it

What are your opinions?

答:
Well - it depends :-).  If you're following a BDD (Behaviour Driven Development) or a ATDD (Acceptance Test Driven Development) approach then testing the public interface is fine (as long as you test it exhaustively with varying inputs.  The underlying implementation e.g. private methods isn't actually important.

However say you want part of that algorithm to execute within a certain time frame or along a certain bigO curve (e.g. nlogn) then yes testing the individual parts matter.  Some would call this more of a traditional TDD/Unit Test approach.

As with everything, YMMV

Title: Unit testing internal components


Body:
Macro rules of thumb? Besides cross-language stuff like source-control or consistent naming styles?

Try to use a Front Controller model if you can. It makes things much much simpler in the long-run. It sidesteps a lot of grief when it comes to relative paths and environmental setup.

Avoid defining top-level functions/variables/constants. They just don't scale. Strongly prefer using classes to "host" anything, even if it ends up being a static method or a class-constant.

Design you classes to take advantage of class autoloading. This typically means that class Foo_Bar_Baz is defined in file Foo/Bar/Baz.php, taking advantage of direct text replacements. However, if you have a better method of taking a classname and determining what file to include, go ahead.

Avoid creating files which contain both class/method/constant definitions and also top-level procedural code that executes when the file is included or required.

Take advantage of IDEs which allow you to annotate your PHP code and provide autocompletion.

When you're building a web-page, remember that sometimes code that comes near the end will want to change a header, or add a <script> tag. Architecturally, try to defer generating HTML for as long as possible. (Interpreter-level output buffering is a helpful half-measure.)

Do everything in UTF-8 from the very beginning, or you're gonna have a bad time.

And dangerous stuff for use only when the tradeoff is worth it:

Careful usage of &references will allow you to make in-place changes to an array, which can be enormously helpful when trying to modify huge nested arrays. (Always unset() them afterwards.) Of course, those same huge arrays are a code-smell, and you should consider replacing them with classes which self-document and enforce structure.

Variable Variables can be useful in small, contained areas, but using them widely is an invitation to problems when refactoring later on.


问:
What is the Best Practice for creating a secure login in a client - server appllication?
It's been a while I have been thinking on what could be the best scenario for creating a secure login in a client-server application running on internet or any other networks ! So I became with the idea to ask this question on programmers and I hope that this question will make awareness of new aspects of threads and security here by some kind of brain storming , I am really interested in good and new anseawres . Thanks in advance for your participation .</p>

答:
Clean EVERYTHING that is inputted by the user (and even what is not). Make sure you hash/encrypt your sensitive data (i.e. passwords) -- I suggest using a salt with your password encryption.

I also suggest making it mandatory for passwords to be longer than 4 characters and have to include a number or two at least, so you don't get John Doe with the password cat ..

Edit
I'm not sure what language your developing in but this may be handy to get an idea on what to do .. http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL


答: Don't reinvent the wheel, especially when it comes to security. If at all possible, use tried-and-tested secure login packages. There are a lot of them out there depending on what platform you are targeting.</p>

Title: What is the Best Practice for creating a secure login in a client - server appllication?

Body: It's been a while I have been thinking on what could be the best scenario for creating a secure login in a client-server application running on internet or any other networks ! So I became with the idea to ask this question on programmers and I hope that this question will make awareness of new aspects of threads and security here by some kind of brain storming , I am really interested in good and new anseawres . Thanks in advance for your participation .</p>


答:
It depends

There are many different factors that go into designing your interface. The goal of this interface is to get out of the way of the caller, so that they can go about their business without worrying about the details of data persistence and retrieval (which are many).

That being said, one good place to start is to research the work of others who have come before you. Your application doesn't seem like it's doing anything groundbreaking, so don't reinvent too much of the wheel.

ORMs

EntityFramework

NHibernate

RollYourOwn

Other ways to approach the problem of interfacting .NET code and databases include, but are not limited to, LINQ to SQL, CQRS, Repository Pattern, any and all of which could be used in rolling your own variety of ORM

As a bonus, RavenDB can serve as an example of a persistence library that serves up a fairly robust C# API.

All that being said, I STRONGLY recommend against rolling your own persistence layer. Use an ORM that is widely used and vetted, and you'll save yourself A TON of pain.


问:
Can the following Domain Entity contain logic for creating/deleting other entities?
a) As far as I understand it, in most cases Domain Model DM doesn't contain code for creating/deleting domain entities, but instead it is the job of layers ( ie service layer or UI layer ) on top of DM to create/delete domain entities?

b) Domain entities are modelled after real world entities. Assuming particular real world entity being abstracted does have the functionality of creating/deleting other real world entities, then I assume the domain entity abstracting this real world entity could also contain logic for creating/deleting other entities?

```<code>class RobotDestroyerCreator
{
         ...
         void heavyThinking()
         {
                  ...
                  if(...)
                        unitOfWork.registerDelete(robot);
                  ...

                  if(...)
                  {
                         var robotNew = new Robot(...);
                         unitOfWork.registerNew(robotNew);
                  {
                  ...
          }
}
</code>```

Thank you

答:
a) DDD doesn't specify that domain objects shouldn't create domain objects. A domain object can very well create another domain object. An aggregate is responsible for enforcing a consistency boundary around a cluster of entities and value objects. As such, it could very well have behaviors which create entities. For example, the stereotypical sales order aggregate can create instances of order line entities (or value objects, depending on implementation). The important thing is to ensure that domain and entities are created or deleted in well defined places. Take a look at this article which evaluates aggregate creation in a domain model.

b) The mapping between a real world entity and the corresponding abstraction in code is never isomorphic. Abstractions in code are bound by technical constraints that cannot be overlooked. Code isn't meant to be an isomorphism of reality, it is only meant exhibit functional characteristics which fulfill sets of requirements. The similarity between reality and code is an aspect that we strive for to streamline the development process. In other words, if a real world entity creates something, it doesn't immediately translate to the corresponding abstraction in code, though it may - there is no hard rule.


答:
(Generic, language independent answer)

Often in DB abstraction classes you see two methods - Query() and Execute().  Query() returns results, Execute() returns success/failure.

This allows for

```<code>results = db.Query('select....', parms)
while (row = results.whatever())
{
...
}
</code>```

and

```<code>if (db.Query( 'update...', parms))
{
  //do something else
}
</code>```

I dont see the need to split up the Execute() method into Insert() and Update() methods unless you're trying to make a query builder and are using your db layer to actually construct the sql.

Body:
(Generic, language independent answer)

Often in DB abstraction classes you see two methods - Query() and Execute().  Query() returns results, Execute() returns success/failure.

This allows for

results = db.Query('select....', parms)
while (row = results.whatever())
{
...
}

and

if (db.Query( 'update...', parms))
{
  //do something else
}

I dont see the need to split up the Execute() method into Insert() and Update() methods unless you're trying to make a query builder and are using your db layer to actually construct the sql.


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
I like to ask, "What is the biggest challenge you are currently facing?"

This question serves multiple purposes.

Does the interviewer know what's going on in the company?

Can they admit that they don't have all the answers?

Does it sound like something I can help with?

Do they have a direction, or just chaos?


答:
Since you mentioned you're a .NET programmer, be sure to take a look at Microsoft's Introduction to Membership.

As others have pointed out, it's better to use a package than to roll your own.


问:
How to justify rewriting/revamping legacy software in a business case?
I work for a great little software company which makes good revenue from our main software package.  The problem for me is that it's almost unmaintainable.  It's written in Delphi 7 (has upgraded versions over time) and has been worked on by a lot of developers over the past 20 or so years.

The software lacks any meaningful architecture - there's no object orientation whatsoever, horrible amounts of cyclical dependencies and an over-reliance on global variables to name just a few things.  Another huge thing for me is Delphi 7 does NOT support 64-bit.

The problem here for me is that my management team don't care about technical things, they want to know why they should care.  Obviously that's expected, so what I'm asking here is for some guidance, or tales, or pitfalls about this kind of thing.

There's a few things I would love to include, namely for me, the length of time taken to debug/write a feature in "legacy" code, versus coherent, well structured OO code.  Does anyone know of any blog posts or the like where this is talked about?  For us in the company this is a huge reason.  Despite being decent developers we feel like writing a new feature is just piling more rubbish on top.  On top of that, even for me who has a decent level of understanding of the code, changing things is infuriating - a small change can have a ridiculous domino effect.

Anyone have any experiences they'd like to share?

答:
As always when it comes to business minded people, present your case as a profit/loss analysis. Your analysis should answer these three questions:

What additional revenue can be generated by your proposed rebuild? (e.g. 64-bit support could be translated to more targeted platforms)

What revenue loss does your rebuild curb? (e.g. Having to spend less time and resources in maintenance and adding new features)

Is the cost of your rebuild justified by enough change in the above two items?


问:
Efficient Data Structure for holding a graph
Problem Link - http://opc.iarcs.org.in/index.php/problems/NUMTRIPLE

In my opinion, the problem can be solved by a data structure, that shows how each number is connected to another, and via recursion find the smallest possible value. But my question is, what data structure (most efficient) can hold/represent such data? Also, is there a better (faster) way of solving this problem.

Thanks

答: The problem is equivalent to the shortest-path problem in a graph, where the vertices are given by the first and third number of each of your triples, an edge is given by a triple "connecting" two vertices, and the weight of the edge is given by the second number of each triple. It can be efficiently solved, for example, by Dijkstra's algorithm. The Wikipedia article lists some different heap data structures for graphs which may be appropriate for this algorithm as long as the graph is "sparse".</p>


答:
Your software is maintainable. That is why you are working on it. In fact, the revenue they get from selling and supporting that software probably supports your loaded salary. If I was managing something that works, I would leave it alone. If you had a house with a convoluted plumbing architecture, would you pay a plumber to clean up the architecture even though it works perfectly well right now? Probably not.

As a software developer, I understand why you want a good architecture, object-orientation, et cetera, so you don't have to sell me, or any software developer.

I would bet that software product is in "milk-the-cow" mode. They are just trying to get as much profit out of it as possible from existing customers before it dies. If that is not true, then what are the architectural scenarios coming down the pipe? More of the same data? New data? Platform or tool deprecation? High performance algorithms? Expanding customer base? New features? New platforms? Mobile? If there are no new business conditions which will drive you to change the architecture, then the architecture will not change? If your architectural is at the critical point where the next change will cause an incredibly expensive fix, then you'll have to wait for that to happen before they are willing to pay for a change.

The upside of this gig is that they probably can't fire you, because Delphi skills are relatively hard to find. And there is job security when you are supporting a profitable product.

Title: How to justify rewriting/revamping legacy software in a business case?

Body:
I work for a great little software company which makes good revenue from our main software package.  The problem for me is that it's almost unmaintainable.  It's written in Delphi 7 (has upgraded versions over time) and has been worked on by a lot of developers over the past 20 or so years.

The software lacks any meaningful architecture - there's no object orientation whatsoever, horrible amounts of cyclical dependencies and an over-reliance on global variables to name just a few things.  Another huge thing for me is Delphi 7 does NOT support 64-bit.

The problem here for me is that my management team don't care about technical things, they want to know why they should care.  Obviously that's expected, so what I'm asking here is for some guidance, or tales, or pitfalls about this kind of thing.

There's a few things I would love to include, namely for me, the length of time taken to debug/write a feature in "legacy" code, versus coherent, well structured OO code.  Does anyone know of any blog posts or the like where this is talked about?  For us in the company this is a huge reason.  Despite being decent developers we feel like writing a new feature is just piling more rubbish on top.  On top of that, even for me who has a decent level of understanding of the code, changing things is infuriating - a small change can have a ridiculous domino effect.

Anyone have any experiences they'd like to share?


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I live and work in the Netherlands, but all the code we write is in English. Here are some reasons I can think of why we code in English:

The .NET framework we work with is in English. It's always better to follow conventions of the framework you're working with and I believe this includes the language.

Dutch is a horrible language for describing technical concepts. English has words that can accurately describe something technical, e.g. a piece of software, but many of these words have no Dutch equivalent. The word "interact" is an example of this; there's no commonly used Dutch word that conveys the same message.

A small percentage of the company doesn't speak Dutch (yet).

The only reason I can think of why you would not code in English, is in the context of domain-driven design. Practicing DDD includes defining a ubiquitous language with your client. If your client demands the use of non-English terms, it would be unwise to translate these terms to English in your code; it defeats the purpose of the ubiquitous language.


问:
Is a code review which uses only code comments a good idea?

Preconditions

Team uses DVCS

IDE supports comments parsing (like TODO and etc.)

Tools like CodeCollaborator are expensive for budget

Tools like gerrit are too complex for install or not usable

Workflow

Author publishes somewhere on central repo feature branch

Reviewer fetch it and start review

In case of some question/issue reviewer create comment with special label, like "REV". Such label MUST not be in production code -- only on review stage:

```<code>$somevar = 123;
// REV Why do echo this here?
echo $somevar;
</code>```

When reviewer finish post comments -- it just commits with stupid message "comments" and pushes back

Author pulls feature branch back and answer comments in similar way or improve code and push it back

When "REV" comments have gone we can think, that review has successfully finished.

Author interactively rebases feature branch, squashes it to remove those "comment" commits and now is ready to merge feature to develop or make any action that usualy could be after successful internal review

IDE support

I know, that custom comment tags are possible in eclipse & netbeans. Sure it also should be in blablaStorm family.

Questions

Do you think this methodology is viable?

Do you know something similar?

What can be improved in it?

答: Others have talked about of the limitations of this approach.  You mentioned that tools like gerrit were hard to install - I suggest you take a look at phabricator (http://www.phabricator.com).  This is the code review system that Facebook has used for years, and was recently open sourced.  It's not hard to install, has excellent workflows, and solves all of the issues mentioned in the other comments.</p>


答:
a) A domain entity may occasionally create or delete other entities. However, it will typically do so by adding to or removing from one of its internal collections if the entity to add/remove is one of its child entities from the same aggregate (in which case your ORM will most likely be able to track changes to the collection and persist them automatically), or by calling a Repository if the entity to create/delete is an Aggregate root. It hardly seems appropriate for a domain object to know about the unit of work and the current state of objects in the user transaction - this is a job for the Application layer.

You should also be careful not to place too complex object creation logic in an entity - assembling complex objects from various parts rather belongs to a Factory.

b) There's elegance indeed in code that mirrors how real-world concepts play out - it's smooth, very readable and easily understandable. Besides, it's true that DDD encourages us to name our code constructs after real world concepts of the domain.

However, it also tells us that the model and ubiquitous language should be the result of a domain expert/developer collaboration. It's not like you could just pour the domain on a keyboard and watch your domain objects write themselves magically. Abstraction is not just translation from real to code with nouns becoming classes and verbs becoming methods, it's more than that. Some kind of transformation process is needed where the business needs and technical needs meet. During that process, some objects or relationships between objects that existed in the real world will be preserved, others won't - because they are not conveniently representable in code, or because they defeat good software practices such as separation of concerns, cohesion, low coupling, etc. New domain objects will also appear, maybe ones that don't have a materialization in the real world domain.

So the computerized version of a real-world domain problem or activity is a different animal, there's no rule allowing you to tell in advance if there's going to be a class for this business actor or a method for that business concept. All you can be sure about is that their names will probably be found somewhere in the code.

Title: Can the following Domain Entity contain logic for creating/deleting other entities?

Body:
a) As far as I understand it, in most cases Domain Model DM doesn't contain code for creating/deleting domain entities, but instead it is the job of layers ( ie service layer or UI layer ) on top of DM to create/delete domain entities?

b) Domain entities are modelled after real world entities. Assuming particular real world entity being abstracted does have the functionality of creating/deleting other real world entities, then I assume the domain entity abstracting this real world entity could also contain logic for creating/deleting other entities?

```<code>class RobotDestroyerCreator
{
         ...
         void heavyThinking()
         {
                  ...
                  if(...)
                        unitOfWork.registerDelete(robot);
                  ...

                  if(...)
                  {
                         var robotNew = new Robot(...);
                         unitOfWork.registerNew(robotNew);
                  {
                  ...
          }
}
</code>```

Thank you


问:
Compiling vs using pre-built binaries performance?
Will performance be better (quicker) if I manually compile the source for a software component for the actual machine that it will be used on, compared to if the source was compiled on another platform perhaps for many different architectures? I got some good results compiling source that I downloaded and I wonder whether this was due to compiling it instead of downloading a pre-compiled binary which is often the case with software updates.</p>

答: In many (if not most) cases, yes. This because the compiler can produce native code optimized for that particular CPU and environment. The code is more "targeted".</p>


答:
Compiling from sources gives you an advantage of setting the compiler flags the way you want for your specific platform. Downloading a package that has been compiled with the same exact settings as yours would offer no difference, but changing the settings from the defaults can get you big improvements.

For example, if the binaries offered for download were compiled for debugging (intentionally or by mistake), turning on more aggressive optimization will improve performance in nearly all situations. On the other hand, if the compiled code is optimized to the max, you would not see any difference.

Title: Compiling vs using pre-built binaries performance?

Body: Will performance be better (quicker) if I manually compile the source for a software component for the actual machine that it will be used on, compared to if the source was compiled on another platform perhaps for many different architectures? I got some good results compiling source that I downloaded and I wonder whether this was due to compiling it instead of downloading a pre-compiled binary which is often the case with software updates.</p>


问:
What is the recommended MongoDB schema for this quiz-engine scenario?
I'm working on a quiz engine for learning a foreign language.  The engine shows users four images simultaneously and then plays an audio file.  The user has to match the audio to the correct image.  Below is my MongoDB document structure.  Each document consists of an image file reference and an array of references to audio files that match that image.  To generate a quiz instance I select four documents at random, show the images and then play one audio file from the four documents at random.

The next step in my application development is to decide on the best document schema for storing user guesses.  There are several requirements to consider:

I need to be able to report statistics at a user level.  For example, total correct answers, total guesses, mean accuracy, etc)

I need to be able to query images based on the user's learning progress.  For example, select 4 documents where guess count is >10 and accuracy is <=0.50.

The schema needs to be optimized for fast quiz generation.

The schema must not cause future scaling issues vis a vis document size.  Assume 1mm users who make an average of 1000 guesses.

Given all of this as background information, what would be the recommended schema? For example, would you store each guess in the Image document or perhaps in a User document (not shown) or a new document collection created for logging guesses? Would you recommend logging the raw guess data or would you pre-compute statistics by incrementing counters within the relevant document?

Schema for Image Collection:

```<code>_id "505bcc7a45c978be24000005"

date    2012-09-21 02:10:02 UTC
imageFileName   "BD3E134A-C7B3-4405-9004-ED573DF477FE-29879-0000395CF1091601"
random  0.26997075392864645
user    "2A8761E4-C13A-470E-A759-91432D61B6AF-25982-0000352D853511AF"
audioFiles
[
0
{
audioFileName   "C3669719-9F0A-4EB5-A791-2C00486665ED-30305-000039A3FDA7DCD2"
user    "2A8761E4-C13A-470E-A759-91432D61B6AF-25982-0000352D853511AF"
audioLanguage   "English"
date    2012-09-22 01:15:04 UTC
}
1
{
audioFileName   "C3669719-9F0A-4EB5-A791-2C00486665ED-30305-000039A3FDA7DCD2"
user    "2A8761E4-C13A-470E-A759-91432D61B6AF-25982-0000352D853511AF"
audioLanguage   "Spanish"
date    2012-09-22 01:17:04 UTC
}
]
</code>```

答:
I would store each guess as a separate document in a user guesses collection. The structure of each document would be as follows:

```<code>Guess
- userId
- selectedImageId
- correctImageId
</code>```

You may also store more information about the corresponding quick, such as the shown images and played audio. To generate statistics, you will need to run Map/Reduce over this collection. For example, to get stats of total and correct guesses, your Map/Reduce output document structure would be:

```<code>UserStats
- userId
- guesses
- correct
</code>```

The map function may look like this:

```<code>function() {
    emit(this.userId, { guesses: 1, correct: this.selectedImageId === this.correctImageId ? 1 : 0 });
}
</code>```

And the reduce function:

```<code>function(key, values) {
  var result = { userId = key, guesses: 0, correct: 0 };
  values.forEach(function(value) {
    result.guesses += value.guesses;
    result.correct += value.correct;
  });
  return result;
}
</code>```

Note, on MongoDB, Map/Reduce is not run automatically as source collections are updated, so you will need to implement that on your own.

Body:
I would store each guess as a separate document in a user guesses collection. The structure of each document would be as follows:

Guess
- userId
- selectedImageId
- correctImageId

You may also store more information about the corresponding quick, such as the shown images and played audio. To generate statistics, you will need to run Map/Reduce over this collection. For example, to get stats of total and correct guesses, your Map/Reduce output document structure would be:

UserStats
- userId
- guesses
- correct

The map function may look like this:

function() {
    emit(this.userId, { guesses: 1, correct: this.selectedImageId === this.correctImageId ? 1 : 0 });
}

And the reduce function:

function(key, values) {
  var result = { userId = key, guesses: 0, correct: 0 };
  values.forEach(function(value) {
    result.guesses += value.guesses;
    result.correct += value.correct;
  });
  return result;
}

Note, on MongoDB, Map/Reduce is not run automatically as source collections are updated, so you will need to implement that on your own.