答:
I have no idea if this is what the authors had in mind, but...

If a set of methods are required to be executed in order passing parameter from one to the next, there's two possibilities...

Static typing enforces the correct ordering due to the parameters required and return values.

Static typing cannot enforce the ordering, perhaps because the same types recur in several places but the values aren't interchangeable.

In my view, the second case is pretty bad because either there's some run-time enforcement of the sequence (tracking state within the object) or there's no error checking at all. As far as possible, I'd prefer my coding errors to be detected at compile-time.

The first case is actually almost as bad for the same reason. OK, you can't get the sequence wrong without getting a compile-time error. But you can leave the sequence incomplete. Or call the same method twice, discarding the results from the first call. There's lots of ways to creatively do things wrong that static checks won't detect.

Of course if you're OK with run-time state checking within the class, that's fine. But why return data back to the caller only to require it back again a few calls later? Why not keep that with the state you're already tracking?

Also, what are the alternatives? One is to use a single call, which might mean supplying a huge list of parameters to that call, which is another code smell. To avoid that, perhaps you'd group those parameters - provide a parameter block to a single call.

Rather than an old C-style parameter block, you'd probably prefer a class. But once the data is provided to that class via method calls, you're back where you started - lots of methods vs. one with many parameters, and possibly needing to sequence the methods.

Title: Why sequential cohesion for operations in a method is not a good idea?

Body:
I read from the seminal  Code Complete book that method statements that require to be executed in order passing parameter from one to the next is a code smell and is an example of a sequential cohesion. Why is this not a good idea?

A contrived example of a sequential cohesion:

```<code>public Part createPart(input) {
        PartOne partOne = computePartOne(input);
        PartTwo partTwo = computePartTwo(partOne);
        PartThree partThree = computePartThree(partTwo);
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(partOne).add(partTwo).add(partThree).build();
    }
</code>```

Here is the exert:

Several other kinds of cohesion are normally considered to be less than ideal:

Sequential cohesion exists when a routine contains operations that
  must be performed in a specific order, that share data from step to
  step, and that don't make up a complete function when done together.

An example of sequential cohesion is a routine that, given a birth
  date, calculates an employee's age and time to retirement. If the
  routine calculates the age and then uses that result to calculate the
  employee's time to retirement, it has sequential cohesion. If the
  routine calculates the age and then calculates the time to retirement
  in a completely separate computation that happens to use the same
  birth-date data, it has only communicational cohesion.

How would you make the routine functionally cohesive? You'd create
  separate routines to compute an employee's age given a birth date and
  compute time to retirement given a birth date. The time-to-retirement
  routine could call the age routine. They'd both have functional
  cohesion. Other routines could call either routine or both routines.


问:
Managing Alerts in Web Application Using RESTful API
I have designed a RESTful API and I am now working on creating a web application to use the service.

One thing I am struggling with is how to manage alerts in the web application (similar to the alerts stackoverflow gives in your profile for a new answer, response etc).

Basically the web application is a workflow between a user and his clients. Certain tasks have to be completed in order, and the web application alerts both the user and his clients of any actions. The user also gets alerted to any client actions that are outstanding.

The way I have my architecture setup at the moment is that the API has no knowledge of alerts. It simply stores the resources that are retrieved by the web application. To work out if an alert needs to be displayed, the web application looks at all the resources, and based on a set of rules, decides what alerts need to be displayed.

The problem I have is that I'm not sure this is a very efficient way to do things. There are a number of different alerts that can be displayed, and they depend on different API resources which will all need to be retrieved when a user or client logs in.

My question: Is this the best way to achieve what I want, or are there other methods which are better to use and will help decrease web application load time and api calls?

答:
You are the best person to answer your own question.

Are alerts integral part of the system? Let's say tomorrow you write a mobile app that interacts with your server. Is it reasonable to assume that it will need alerts too? Or are alerts specific to the web site use case?
If the answer to the first question is yes, then you probably want to have the server handle alerts. This way when you get to write your moobile app, you don't need to replicate the alerts code you wrote for the web site.
But if alerts are specific to the web site use case, you can and should leave the logic in the web site in order to keep the server's api clean and focused.

ContentLicense: CC BY-SA 3.0


问:
Knowledge Transfer and software development
I have been working on an application alone for several years.

I am now asked to transfer knowledge to a few other developers, which I think is a good idea because it will allow us to share the workload.

The problem is that I have never been involved in such a process.  My manager is asking what I need to facilitate this process.  Are there any formal processes/tools/techniques that relate to knowledge transfer and software development that I could look at?

答:
Here are techniques I use that work for our environment and may work for yours:

Pair program / live code in the area of knowledge/code you are transferring if it is for an individual or perhaps a small group

Prepare valid diagram of the code base's architecture and update what architectural documentation you currently have

Have an overview of your applications technical layout memorized or readily available so that you can walk through the entirety of it with a whiteboard in an hour

Know and more heavily document the problem areas. These are the tough parts of code you struggled with (and may still struggle with) that you now anyone else will also likely have issues

Prepare a wiki where you can have light documentation and any information readily available so that you have a living repository of information handy for the new developers

Brush up on all the code and areas of the code base that you likely forgot (anything 3 months old perhaps?)

Be patient when explaining the code!

These are just some idea I have used. The one that I think really helps the most is being able to think through a whiteboard presentation that you can condense into an hour. The reason I say this is it forces you to know the larger pieces of the code/architecture and it will almost by default highlight some of the difficult to understand areas. Once you prepare that it becomes the starting point for initial knowledge transfer discussions with new developers. You will need this as a place to start.

From there you can go into the tasty bits of the code and flesh those area discussions out. For example we have a tough Data Replication area of code between ERPs and this can be difficult to understand so we have a series of presentations and discussions prepared to go down with new developers. Both self directed information and detailed live presentation.

In the end nothing beats out sitting with the developer and working with them in the tough areas. The tough areas will be different depending on the developer you are working with so this live coding and walk through often highlights those areas as you do it and allows you to adjust on the fly.

Code is itself the best documentation if you have been clear and consistent in following a good standard. With adequate documentation and a gentle nudge to the right areas in the code base most good developers will pick up on what you were doing or trying to do and formulate their own questions for you to answer. This is where brushing up on the foundational aspects of your architecture and code will help you be better prepared too.

In the end enjoy the process and have fun and be patient. Patience is key. Along with patience you should let your management know that they to will need to be patient. Knowledge transfer takes some time and in your case more so in that you have been the only developer on the application for years. There is a lot of knowledge to share so make sure they know this is not an overnight or even over a month only endeavor.


问:
A Web application as a REST API client: how to handle resource identifiers
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?

答:
Let's face it, there is no magic solution.
Have you read Richardson Maturity Model? It divides REST architecture maturity into 3 levels: Resources, HTTP verbs and hypermedia controls.

I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self"

This is hypermedia controls. Do you REALLY need it?
This approach has some very good benefits (you can read about them here). But there is no such thing as free meals and you will have to work hard (e.g. your second solution) if you want to get them.

It is a question of balance - do you want to sacrifice performance (and make your code more complicated) but get a system that is more flexible? Or do you prefer to keep things faster and simpler but pay later when you introduce changes to your api/model?

As someone who developed a similar system (business logic tier, web tier and web clients) I chose the second option. Since my group developed all the tiers, we decided it is better to have a bit of coupling (by letting the web tier know about entity ids and building api urls) and in return get code which is more simple. Backward compatibility was also not relevant in our case.

If the web application was developed by a 3rd party or if backward compatibility was an issue, we might have chosen differently because then there was great value in being able to change the url structure without changing the web application. Enough to justify complicating the code.

Does it all mean that RESTful APIs cannot serve as backends for web applications?

I think it means that you don't have to create a perfect REST implementation.
You can go with your second solution, or expose entity id's or maybe pass api urls. It's OK as long you understand the implications and trade-offs.

Body:
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    <a href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?


问:
PHP OOP: Should every object contain all the data?
I'm trying to learn PHP OOP "properly", and I was wondering, should the constructor grab all the information in the database and store it in the object?

To use an example I'm trying to create using PHP OOP, an internet comic website (much like XKCD's), would have two classes:

Catalogue (list and order of all the episodes)

Episode (data relating to that particular episode)

So, in this situation, should the Catalogue object get an array of all the episodeIDs (presumably this would be gotten in the constructor)? And if so, does that mean I have to update both the Object's array and the Database's array? And if so, what's the most common way of implementing this (presumably very common) action?

答:
I am a huge fan of the way Magento has abstracted their database layers into multiple levels and collection model relationships.

This may not answer the question directly but could open the door to thinking about data base objects a bit differently.

The way you would call a single customer is something like:

```<code> $customer = Mage::getModel('customer')->load('20');
</code>```

Where the getModel method instantiates a class that is magically loaded from an XML definition file. In this case let's say that it is called Mage_Core_Model_Customer.

Your basic model almost always extends from a parent class which handles database abstraction and that class extends from a generic object class which sets up magic getters and setters for all model classes. So if anything extends from the database abstraction it also picks up the getter and setter methods.

In doing load('20') you are specifying that you would like to load the database object with the key id being 20.

Now specifically on your question. Magento also uses relational mapping between each entity and their seed object. For example a customer can have many addresses. Their address is not naturally returned back as a part of the object, however if you wanted to get a particular attribute not included in the seed table you would do something like this:

```<code>$collection = $customer->getCollection()
    ->addAttributeToSelect('address1')
    ->addAttributeToSelect('address2');
$collection->load();
</code>```

A collection is basically just a list of database objects.

This becomes a well designed solution because the objects are not coupled to each other as a single entity. Instead, you can filter each association separately.

Please no comments about how none of the code here would work in Magento. This was for illustration

Body:
I am a huge fan of the way Magento has abstracted their database layers into multiple levels and collection model relationships.

This may not answer the question directly but could open the door to thinking about data base objects a bit differently.

The way you would call a single customer is something like:

 $customer = Mage::getModel('customer')->load('20');

Where the getModel method instantiates a class that is magically loaded from an XML definition file. In this case let's say that it is called Mage_Core_Model_Customer.

Your basic model almost always extends from a parent class which handles database abstraction and that class extends from a generic object class which sets up magic getters and setters for all model classes. So if anything extends from the database abstraction it also picks up the getter and setter methods.

In doing load('20') you are specifying that you would like to load the database object with the key id being 20.

Now specifically on your question. Magento also uses relational mapping between each entity and their seed object. For example a customer can have many addresses. Their address is not naturally returned back as a part of the object, however if you wanted to get a particular attribute not included in the seed table you would do something like this:

$collection = $customer->getCollection()
    ->addAttributeToSelect('address1')
    ->addAttributeToSelect('address2');
$collection->load();

A collection is basically just a list of database objects.

This becomes a well designed solution because the objects are not coupled to each other as a single entity. Instead, you can filter each association separately.

Please no comments about how none of the code here would work in Magento. This was for illustration


问:
How to overcome the fear of building a web application with a recurring payment system?
I'm a Ruby on Rails developer. I'd like to create a web application. I will let users get a payed subscription to use the product. So I will need a recurring billing system (e.g. via paypal).

But there is the fear to fail and make some bad mistakes, because I will handle money from other people.... regardless following the instructions of e.g. Ryan Bates on Railscasts how to implement such a recurring payment system.

What is your advice to overcome this fear of building such a product?

What are the risks I need to calculate when designing such a system?

答:
1) You're right to use a service to do the recurring payments for you so you don't have to worry about security.  Your biggest risk is that you could expose payment data to malicious individuals.  Make secure storage of the credit card data somebody else's problem.

2) Write really good tests.  Don't stop at unit tests, move up to integration, functional and behavioral tests.  It's not enough to test "testCardAccepted."  You also need tests like "Given my card was processed successfully and a year has passed and I have not canceled Then I should see one charge of 9.99 on the test card account." and "Given my card was ... and the expiration date is in the past and there is one month to renewal Then I should see an e-mail asking to update the card information."

3) Do some analysis and design before you start.  See if there's a well established library you can use to do the recurring payments from your merchant.  Understand the problem really well and get a sense of what might be problem areas.  I can't think of a good library, but check to see if the merchant has good quality sample code you can re-use.

4) Make sure you form an LLC or corp with its own, separate bank account for transactions with the merchant.  Check to see if your local laws require you to carry a bond or other insurance, including business licensing.

that all the advice I have for you.


答:
The fact that you use PayPal mitigates the risk from IT to legal and accounting departments. You don't have to process payments in a secure way: PayPal does. You don't have to safely store credit card numbers: PayPal does.

If something goes wrong, it's up to the accounting department to discuss the issue with the client, having PayPal recordings as a proof. In the worst case, the customer will actually pay, but your web application will fail to record (or magically forget) that PayPal processed the payment. In this case, accountants could simply have an override, letting them to indicate to the web app that the payment was effectively done.

Title: How to overcome the fear of building a web application with a recurring payment system?

Body:
I'm a Ruby on Rails developer. I'd like to create a web application. I will let users get a payed subscription to use the product. So I will need a recurring billing system (e.g. via paypal).

But there is the fear to fail and make some bad mistakes, because I will handle money from other people.... regardless following the instructions of e.g. Ryan Bates on Railscasts how to implement such a recurring payment system.

What is your advice to overcome this fear of building such a product?

What are the risks I need to calculate when designing such a system?


问:
mvc pattern on procedural php
First off, I do not have anything against OO programming (I'd be mad if i believed so). But I was thinking on some sort of procedural MVC pattern with PHP; let me explain better.

As we all know, variable scopes, unless they are taken from $_SESSION (, database, redis, etc.) are never global and only refer to a singular execution of a script. For example:

```<code>class Car {
  this->name = "foo";
  function setName($name) { ... }
  function getName() { return $this->name; }
}
</code>```

Where obviously in a more common situation, this data will be taken from the DB, otherwise any object car, per execution, would have the same name.

Now, is it not possible to apply MVC pattern on procedural code for simplicity purpose? Imagine a really simple social network like application; I could have a structure like this

```<code>*views
  -profileview.php
  -messageview.php
  -loginview.php
  -notloggedin.php
*models
  -user.php
  -message.php
- profile.php
- messages.php
- login.php
</code>```

where profile, messages and login.php work as controllers and route to the right view; and user and message.php work as the classes, that contain all the functions that are eventually needed by the controllers, such as getUserById($id), postMessage($id, $meesage), etc.

I have simplified it a lot but I think you can sort of understand my point.

What would you think of such implementation on the long run, and why?

答:
I won't argue with Stephen, even though I could. ;)

Basically, if you want to go with MVC on your own, you'll need at least a request dispatcher and probably a view resolver along with some configuration facilities.

As procedural PHP has no real support for types, coupling problems will probably be a PITA.

In a most basic scenario you could just have a request mapping like

```<code>$mapping = array(
    "show_profile" => "profile.php:showProfile",
    "edit_profile" => "profile.php:editProfile",
    "etc" => "whatever.php:doEtc"
);
</code>```

and then just retrieve the correct setting and explode it to $fileToInclude and $functionToCall. There you'll have your controller-problem sorted out (passing some generalized $request parameter to them or so).

As for a very simple run, your controller could do whatever it should and then explicitly inlcude the view file or return some data so that the view resolver can be invoked with the identifier (e.g. file path or mapping key) of the view to render and the data to display.

There are serveral approaches, and the above one is not even close to an elegant solution (heck, we're talking about procedural code :D) but this is the most simple clean-ish variation I can think of; you can extend on it as you please.

Keep in mind that you want to keep your code as decopuled and maintainable as possible.
(A hard way would be to create a framework with which you could use arbitrary code as controller with arbitrary functions and parameters; the easiest one is simply a matter of some explicit includes)

PS.: I'd suggest using existing frameworks for that matter, but the only publicly available PHP frameworks that are viable are all OO and mixing up OOP with procedural code would be a terrible practice; even worse than reinventing your wheels. Actually, if you don't have to stay procedural at all cost, you better switch to OO.

Good luck with your project!

Title: mvc pattern on procedural php

Body:
I won't argue with Stephen, even though I could. ;)

Basically, if you want to go with MVC on your own, you'll need at least a request dispatcher and probably a view resolver along with some configuration facilities.

As procedural PHP has no real support for types, coupling problems will probably be a PITA.

In a most basic scenario you could just have a request mapping like

$mapping = array(
    "show_profile" => "profile.php:showProfile",
    "edit_profile" => "profile.php:editProfile",
    "etc" => "whatever.php:doEtc"
);

and then just retrieve the correct setting and explode it to $fileToInclude and $functionToCall. There you'll have your controller-problem sorted out (passing some generalized $request parameter to them or so).

As for a very simple run, your controller could do whatever it should and then explicitly inlcude the view file or return some data so that the view resolver can be invoked with the identifier (e.g. file path or mapping key) of the view to render and the data to display.

There are serveral approaches, and the above one is not even close to an elegant solution (heck, we're talking about procedural code :D) but this is the most simple clean-ish variation I can think of; you can extend on it as you please.

Keep in mind that you want to keep your code as decopuled and maintainable as possible.
(A hard way would be to create a framework with which you could use arbitrary code as controller with arbitrary functions and parameters; the easiest one is simply a matter of some explicit includes)

PS.: I'd suggest using existing frameworks for that matter, but the only publicly available PHP frameworks that are viable are all OO and mixing up OOP with procedural code would be a terrible practice; even worse than reinventing your wheels. Actually, if you don't have to stay procedural at all cost, you better switch to OO.

Good luck with your project!


问:
When can one call themselves a "Rubyist"?
I was wondering what that term even meant. Is it something to do with one's amount of knowledge about the Ruby language or just the plain idea of using it. When can one call themselves a "Rubyist"?</p>

答:
A {insert language here}ist (or -ite, or -er) is a person who programs in that language.  It is an informal way of saying a "{insert language here} programmer."  There are no qualifications for when one can call themselves by such an informal title.

Claiming such a title for oneself would imply some set of:

more than passing familiarity with the language

able to code in that language quickly and efficiently

familiar with the idioms of the language

However, as mentioned - there are no standards, certificates or qualifications for when one calls themselves a rubyist.  More often than not, these are titles applied by one's coworkers on someone else in the team akin to nicknames.


问:
How do I showcase my work experience in programming?
I'm a student of web development languages like PHP, Ruby, and Python. Currently I'm working on some school projects but I'm trying to work on some weekend projects which I can use to showcase for potential employers, what's the best way to set this up? Specifically, are there any tips you have for a new programmer because I don't want opinions on how this or that should or shouldn't be set up. If possible please give real examples.

Edit: what about Git? Is this a good place to show my projects?

答: In my opinion, the only way you can prove that you are able to code in a language is to show the code you write. And so therefore setting up a GitHub account and pushing some project (your school projects maybe?) would be a very smart option. This way people see what you make and what you are able to make. Also, GitHub is free for public projects.

ContentLicense: CC BY-SA 2.5


问:
Best practices to avoid fake profiles?
When offering to create a profile (for example, login+pwd) for a web service, what are the best practices one should implement to avoid mass spamming/creation of fake profiles? I am thinking about email confirmation, captchas, etc... any other ideas that work in practice?</p>

答:
A very good idea to avoid mass profile making without adding a captcha (let's admit it, even when you know they are for the good, captchas can be just annoying) is to make a hidden <input> element.

You check if this element is filled up: then it usually means it was a bot: in this case you give the bot a false success message and just throw the data in the bin. In case it was not filled in (because no human would go look in your source code for hidden inputs), you process the data and register the user.

Title: Best practices to avoid fake profiles?


答: Some services require you to enter a verification code sent to your phone by text. Its quite effective at stopping bots but does take some effort on your part to set up though.</p>

Title: Best practices to avoid fake profiles?

Body: When offering to create a profile (for example, login+pwd) for a web service, what are the best practices one should implement to avoid mass spamming/creation of fake profiles? I am thinking about email confirmation, captchas, etc... any other ideas that work in practice?</p>


问:
What is proper etiquette for releasing a complete rewrite of an existing project?
I'm new to the opensource world. The project I'm working on resides on Github. (Just for reference) The project I'm working on is a plug-in for the Plex Media Server. I plan to submit my plug-in to Plex so that it will be included in their "app store". Now to my question.

When I first started out, I found an older semi-abandoned plugin that did some of what I wanted but not very well. I started by contributing to that repo. I was immediately made a collaborator with full rights to the repo since the current owner said he was too busy to mess with it anymore. However, as I started to dig deeper into the code I realized that it was futile. The existing code base was terrible and there was no efficient way to fix it. I ended up just starting from scratch. The only code I used in my new plugin was the code I committed initially.

Now the project is ready to be released. However I am unsure as to how to go about doing this. I see my options as follows:

Create a new repo and just forget about the existing one. I'm not sure if I should even mention the previous repo and or its contributors. I didn't use any of that code/resources and have created an entirely new code base. While the plugin does some of the same things the old one did, it does it in an entirely new way and more efficient way.

I fork the existing repo, delete the existing code, and commit my new code. I'm really new to Git, so I'm not sure if this is even possible.

I commit my changes to the existing repo and see how the current contributors have to say.

Of the three options, I'm strongly leaning towards the first. BUT! I'm new to open source and I want to make sure I'm doing things according to proper etiquette. I don't want to have my first project blow up in my face and become a disaster. Option two doesn't sound bad but I'm not sure if I'm supposed to do that. I'm not sure how the history and diffs would work. We're only talking about 500 - 1000 lines of code at most. So it's not a huge code base.

Thanks for any input you can provide!

答:
Since it's all new code, I would tend to go with #1 because the commit history of the old project is really irrelevant. But it would be nice to add something to the README along the lines of, "Based on an idea from ....".

I'm a big fan of acknowledging where we (or our algorithms) came from. If you look back into the mists of history, you'll see that we are all standing on the shoulders of those that came before—all of us. For example, I developed and marketed a similarity search engine back in the 1980's, and it seemed pretty radical to some people (Boolean was King back then). But the heart of the algorithm I was using was based on work started by Gerard Salton at Cornell 20 years before me.


问:
How can one best avoid writing bloated GUI code?
I find whenever I work with GUI code, the code tends to bloat faster then other kinds of code. It also seems harder to refactor. Whereas in other kinds of code I can refactor pretty easily -- I find I can decompose a larger class into smaller pieces of functionality -- with most GUI frameworks I'm often bound to a framework that requires my widget/control/whatever class to implement a lot more things more directly in the widget/control/whatever. Sometimes this is due to needing to either (a) inherit off of some base widget/control/thing or (b) need access to protected methods.

I typically also have to, for example, respond to a large variety of inputs via signals/events/whatever from the framework to implement all the modes of interacting with the user. I might need in one GUI widget/control to handle a large variety of input/output that might include:

a right click/context menu

reacting to selections from the context menu -- which may be many

a special way to paint the GUI

react to keyboard input

buttons, checkboxes,

etc etc

... all the while manage the classes under the GUI representing business logic.

A simple straight-forward GUI can have its code grow pretty quickly, even when seperating out buisiness logic and using MVC, I find GUI code is a big magnet for change.

Is there any way to manage GUI code in a sane way and avoid letting it become a broken window? Or is a mass of random event handlers/overridden methods really the best we can do for GUI code?

答:
Apply Object-Oriented Design to your code, and for UI development:

Separate presentation and model
Use a MV-whatever library/framework, or write your own, to help separate view/controller logic from data model.
All communication with the backend should be done inside the model, and the model state should always be in-sync with the backend.

Decoupling
If object A knows about object B, then A can call methods on B, but B should not know about A. Instead A can listen to events from B. It makes sure there is no circular dependency.
If your app has lots of events between components, then create an EventBus, or leverage an event-driven framework like Twitter Flight.

Partial vs full render If your view is a table or list of items, your may be tempted to create methods like "add", "remove" to insert/delete one item into/from the collection. Your code could easily bloat when you have to support sorting and pagination. So my advice is: simply re-render the whole view even when there is a partial change. What about performance? well if your collection is big, then your should do pagination anyway. Web developer: make sure your event handlers are delegated to the view's root element which does not change.

View model When your view's state becomes too complicated to maintain, for example, a Table view has to keep track of the row data, column data, sort order, currently checked rows (if it supports multi-check), etc, you should probably create a ViewModel object for those states. Your View object should call setters on the ViewModel if something changes on the UI (eg: user checks a row); and it should respond to ViewModel's change event by updating the UI. Usually you should avoid updating the UI if the change event is triggers by UI.

Here is a small but non-trivial app to help illustrate some of my points. You can find the code and view/model interaction diagram here: https://github.com/vanfrankie/pushpopbox


问:
Storing in-text metadata in a discrete data structure
I am developing an application which will need to store inline, intext metadata. What I mean by that is the following: let's say we have a long text, and we want to store some metadata connected with a specific word, or sentence of the text.

What would be the best way to store this information?

My first thought was to include in the text some kind of Markdown syntax that would then be parsed on retrieving. Something looking like this:

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam __nonummy nibh__[@note this sounds really funny latin]
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</code>```

This would introduce two problems I can think of:

A relatively small one, is that if said syntax happen to be fortuitously on the said text, it can mess with the parsing.

The most important one is that this doesn't maintain this metadata separate from the text itself.

I would like to have a discrete data structure to hold this data, such a different DB Table in which these metadatas are stored, so that I could use them in discrete ways: querying, statistics, sorting, and so on.

EDIT: Since the answerer deleted his answer, I think it might be good to add his suggestion here, since it was a workable suggestion that expanded on this first concept. The poster suggested to use a similar syntax, but to link the metadata to the PRIMARY KEY of the metadata database table.

Something that would look like this:

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam __nonummy nibh__[15432]
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</code>```

Where 15432 would be the ID of a table row containing the necessary, queriable information, as per example below.

My second thought was to store information of this kind in a DB Table looking like this:

```<code>TABLE: metadata

ID    TEXT_ID    TYPE    OFFSET_START    OFFSET_END    CONTENT
1     lipsum     note    68              79            this sounds really funny latin
</code>```

In this way the metadata would have a unique id, a text_id as a foreign key connected to table storing the texts and it would connect the data with the text itself by using a simple character offset range.

This would do the trick of keeping the data separated from the metadata, but a problem that I can immediately see with this approach is that the text would be fundamentally not editable. Or, if I wanted to implement the editing of the text after the assignation of metadata, I would basically have to calculate characters additions, or removal compared to the previous version, and check whether each of this modifications adds or remove characters before or after each of the associated metadata.

Which, to me, sounds like a really unelegant approach.

Do you have any pointers or suggestions for how I could approach the problem?

Edit 2: some XML problems

Adding another case which would make quite necessary for this separation of data and metadata to happen.

Let's say I want to make it possible for different users to have different metadata sets of the same text, with or without the possibility of each user actually displaying the other user metadata.

Any solution of the markdown kind (or HTML, or XML) would be difficult to implement at this point. The only solution in this case that I could think about would be to have yet another DB Table which would contain the single user version of the original text, connecting to the original text table by the use of a FOREIGN KEY.

Not sure if this is very elegant either.

XML has a hierarchical data model: any element which happens to be within the borders of another element is considered as its child, which is most often not the case in the data model I'm looking for; in XML any children element must be closed before the parent tag can be closed, allowing for no overlapping of elements.

Example:

<note content="the beginning of the famous placeholder"> Lorem ipsum
  dolor sit <comment content="I like the sound of amet/elit"> amet </note>,
  consectetuer adipiscing elit </comment> , <note content="adversative?"> sed
  diam <note content="funny latin"> nonummy </note> nibh </note> euismod
  tincidunt ut laoreet dolore magna aliquam erat volutpat.

Here we have two different problems:

Different elements overlapping: The first comment starts within the first note, but ends after the end of the first note, i.e. it's not its child.

Same elements overlapping: The last note and the boldfaced note overlap; however, since they are the same kind of element, the parser would close the lastly opened element at the first closure, and the first opened element at the last closure, which, in this circumstance, is not what is intended.

答:
I think the suggestion from the previous answerer, the one you mentions on you question) is a very good one.

It would behave the same way we post links on the StackExchange sites, but the info data would be on another table. The benefits are, you have the data separated, and therefore queryable and indexable. On edit the text, you can check for deleted metadata IDs and clean the metadata table.

The only small problem like you said is the parsing, but you can deal with it pretty easily.


问:
I'm trying to create a visual representation of something, but I don't know what words to use, so I'll try to describe it
My project team is making a site that will use reddit style voting to track users' opinions on various issues, and use the data to create a "heat map". I say heat map in quotes because I'm not sure that it's the correct term - I don't have the  math to express it properly.

The idea is you'll be able to see, on a 2 dimensional graph, how your opinons compare to those of other voters in your municipality, and to politicians currently running for office. This will help voters make more informed decisions about voting.

I'm not sure how to code this or even what to start googling for. Can anyone suggest a direction?

** I'll change the title to something more useful when I have more information, sorry

答:
Perhaps some research is in order.

Are these other opinions continuous (a curve over the range), or discrete (a scattering of dots)? A heat map is a way to present discrete values in a way that appears continuous, but it depends on large numbers of values.

It sounds like you could benefit from some basic theory:

http://www.edwardtufte.com/tufte/books_vdqi


答:
I think you should consider using an SMS or email verification method in addition to a CAPTCHA. You should also consider logging IP addresses who create accounts and if someone attempts to register another account with in a time window you should deny it or ask for further verification.

Another approach you could take would be to have moderators and make sure there are no spam-type accounts.

You could also watch the user behaviour to identify spam accounts:
- Is the form filled in very quickly for signup
- Does any interaction appear to be preprogrammed

You need to find the right mix of preventative measures to prevent legitimate users from being harmed.

Title: Best practices to avoid fake profiles?


问:
Space between negative sign and variable name
I tried doing a Google search, as well as searching this Stack Exchange site but could not find a question relating directly to this.

The PEP 8 -- Style Guide for Python Code has lots of good style recommendations, however I don't think they mention anything about whether a space between a minus or negative sign (-) and a variable name would be more or less readable.

Question

It's a (very) minor issue, but which is considered more readable?

false_positive = -true_positive

false_positive = - true_positive

Motivation

I ask not to be trivial, but because in my past math courses I often find myself not noticing the negative sign in important equations, such as the equation for computing entropy:

I often don't notice the - sign before the summation, so making it stand out would be desirable.

答:
I've run across this before, and I used

```<code>var false_positive = 0 - true_positive
</code>```

to make sure the intent is clear. That is the more readable form.

Body:
I've run across this before, and I used

var false_positive = 0 - true_positive

to make sure the intent is clear. That is the more readable form.


问:
How is CoffeeScript influenced by Haskell?
I've been using CoffeeScript for a while now. On Wikipedia, it is said that CoffeeScript is influenced by Haskell. But after I check out the syntax of Haskell, I have found little resemblance from CoffeeScript.

Which aspect of CoffeeScript is influenced by Haskell?

答:
For me, the main difference is in function calls. In CoffeScript:

```<code>fun(bar(a, b, c))
</code>```

or:

```<code>fun bar a, b, c
</code>```

In Haskell:

```<code>fun $ bar a b c
</code>```

or:

```<code>fun . bar $ a b c
</code>```

Why oh why those commas between arguments.

Also the difference between quicksort (x:xs) = and quicksort = ([x, xs...]) -> is obvious, and confusing, because -> means something else in Haskell.

OwnerDisplayName: lightblade

Body:
For me, the main difference is in function calls. In CoffeScript:

fun(bar(a, b, c))

or:

fun bar a, b, c

In Haskell:

fun $ bar a b c

or:

fun . bar $ a b c

Why oh why those commas between arguments.

Also the difference between quicksort (x:xs) = and quicksort = ([x, xs...]) -> is obvious, and confusing, because -> means something else in Haskell.


问:
What is the functional-programming alternative to an interface?
If I want to program in a "functional" style, with what would I replace an interface?

```<code>interface IFace
{
   string Name { get; set; }
   int Id { get; }
}
class Foo : IFace { ... }
</code>```

Maybe a Tuple<>?

```<code>Tuple<Func<string> /*get_Name*/, Action<String> /*set_Name*/, Func<int> /*get_Id*/> Foo;
</code>```

The only reason I'm using an interface in the first place is because I want always want certain properties/methods available.

Edit: Some more detail about what I'm thinking/attempting.

Say, I've got a method which takes three functions:

```<code>static class Blarf
{
   public static void DoSomething(Func<string> getName, Action<string> setName, Func<int> getId);
}
</code>```

With an instance of Bar I can use this method:

```<code>class Bar
{
   public string GetName();
   public void SetName(string value);

   public int GetId();
}
...
var bar = new Bar();
Blarf.DoSomething(bar.GetName, bar.SetName, bar.GetId);
</code>```

But that's a bit of a pain as I have to mention bar three times in a single call.  Plus, I don't really intend for callers to supply functions from different instances

```<code>Blarf.DoSomething(bar1.GetName, bar2.SetName, bar3.GetId); // NO!
</code>```

In C#, an interface is one way to deal with this; but that seems like a very object-oriented approach.  I'm wondering if there's a more functional solution: 1) pass the group of functions together, and 2) ensure the functions are properly related to each other.

答:
Don't treat functional programming as a thin veneer over imperative programming; there's much more than just a syntactic difference.

In this case, you have a GetID method, which implies uniqueness of objects. This is not a good approach to writing functional programs. Perhaps you could tell us the problem you are trying to solve and we could give you more meaningful advice.


答:
You want to take a look at the concept of "databinding". This is a way connect UI elements to abstract model elements in a declarative way such that the model elements are automatically synchronized with the contents of the UI. There are many benefits of this approach, for example not having to write event handlers yourself to synchronize data.

There is databinding support for many UI frameworks, for example .NET and Eclipse/JFace.

Title: How can one best avoid writing bloated GUI code?

Body:
I find whenever I work with GUI code, the code tends to bloat faster then other kinds of code. It also seems harder to refactor. Whereas in other kinds of code I can refactor pretty easily -- I find I can decompose a larger class into smaller pieces of functionality -- with most GUI frameworks I'm often bound to a framework that requires my widget/control/whatever class to implement a lot more things more directly in the widget/control/whatever. Sometimes this is due to needing to either (a) inherit off of some base widget/control/thing or (b) need access to protected methods.

I typically also have to, for example, respond to a large variety of inputs via signals/events/whatever from the framework to implement all the modes of interacting with the user. I might need in one GUI widget/control to handle a large variety of input/output that might include:

a right click/context menu

reacting to selections from the context menu -- which may be many

a special way to paint the GUI

react to keyboard input

buttons, checkboxes,

etc etc

... all the while manage the classes under the GUI representing business logic.

A simple straight-forward GUI can have its code grow pretty quickly, even when seperating out buisiness logic and using MVC, I find GUI code is a big magnet for change.

Is there any way to manage GUI code in a sane way and avoid letting it become a broken window? Or is a mass of random event handlers/overridden methods really the best we can do for GUI code?


问:
Why do most issue tracking systems have only single status field?
Most issue tracking systems have only single status field.

Typical Status: New -> Fixed

When code is pushed to repository with commit message "Fixed issue #1234", the issue #1234 is automatically mark as "Fixed".

I have the below idea but no system can fulfill.

The question is: Am I right or just not finding the suitable tool?

Programming status

I think this is problematic because only the programmer says he has fixed an issue.

QA / release status

It is not possible to know if QA team has verified or not. There is no place for QA team to mark the status.

Also, even for open source projects, the end-user may not want to compile from source.

The end-user is only interested in whether he can get a release version.

If the new release is not ready to ship, from the point of view of the user, it is nothing "Fixed".

Feedback status

It is also useful if the user can set the "feedback status" to "Fixed" after testing the released version or source code, rather than leaving a comment "Thanks, it works!".

Status fields are searchable.

答:
Trackers have only one status field because a bug can only be fixed or not. There is no in between. If there are multiple fields, that would be the same as when a developer says "it works for me", where obviously it doesn't.

This enforce the fact that only one person/dept decide if a bug is fixed or not, be it the dev team, the QA or the reporter. In some tracker, like FogBugz, only the reporter can mark a bug as fixed.

The "progress" indicator is another field, which aim is to know where on the "path to the holy fix" is the bug. However (and especially in the software development), it's often a poor indicator, as raw debugging can be really long in the case of a Hindenbug. Also there can be some travel forth and back between QA and dev teams meaning that, like a tennis match, the score goes on and on, until one of the team leads by 2 points.


答:
In my opinion: The first one of your distinctions is sensible, the second isn't.

Obviously programmers must be able to bump the status of an issue, because they are the only ones who can actually do something about the root cause. But you are quite right that making a code change and actually solving the user's problem can be very different things, so it's useful to have a distinction between "fix proposed/implemented/hypothesized" and "fix accepted/verified/confirmed", and to have the second one available to QA. This is usually done (and in fact I would consider it a strong disincentive to work any where this distinction isn't made).

The second one is problematic. Obviously the actual user is the only one who can confirm with finality that a problem is indeed solved; but waiting for the actual user to confirm anything can get horribly slow and tedious. Customers can decline to answer, be unwilling to talk to tech people, etc. etc. Also, as you point out, customers can only see fixes that have made it to a public release. All this can make it impossible to maintain a scalable workflow. Therefore verifying that fixes are in the hands of customers is an issue of release management as much as of development work, and an issue tracker on its own isn't the right tool to solve this.

In short: the different status values that an issue can have are rather more complicated than just "open" vs. "closed", but I think that the ones you should use form a nice one-dimensional succession of states. Therefore adding multiple fields just to express "reported but not reproduced" or "fixed but not shipped" is unnecessary complexity.

Title: Why do most issue tracking systems have only single status field?

Body:
Most issue tracking systems have only single status field.

Typical Status: New -> Fixed

When code is pushed to repository with commit message "Fixed issue #1234", the issue #1234 is automatically mark as "Fixed".

I have the below idea but no system can fulfill.

The question is: Am I right or just not finding the suitable tool?

Programming status

I think this is problematic because only the programmer says he has fixed an issue.

QA / release status

It is not possible to know if QA team has verified or not. There is no place for QA team to mark the status.

Also, even for open source projects, the end-user may not want to compile from source.

The end-user is only interested in whether he can get a release version.

If the new release is not ready to ship, from the point of view of the user, it is nothing "Fixed".

Feedback status

It is also useful if the user can set the "feedback status" to "Fixed" after testing the released version or source code, rather than leaving a comment "Thanks, it works!".

Status fields are searchable.


问:
free as in free beer
Some years ago (more precisely in 1998) the confusion english-speaking people start making with the term free when applied to software led some members of the free software foundation to create a new term: open source ( http://www.gnu.org/philosophy/free-software-for-freedom.html )

The great concern was that people was misunderstanding free as in free of speech, with free as in free beer (see wikipedia: http://en.wikipedia.org/wiki/Free_and_open_source_software ).

The free here relates to the the liberty of using and sharing your software, in a way that goes against proprietary "copyright" (and patented) software. It was first introduced by Richard Stallman, in 1986. The core is the set of freedoms:

Freedom 0: The freedom to run the program for any purpose.

Freedom 1: The freedom to study how the program works, and change it to make it do what you wish.

Freedom 2: The freedom to redistribute copies so you can help your neighbor.

Freedom 3: The freedom to improve the program, and release your improvements (and modified versions in general) to the public, so that the whole community benefits.

Well, we all know about that (at least those who is following this discussion since ever).

In my opinion, the term open-source clarified us. But it was already assured by Freedom 1.

In other languages (like spanish or portugese, for instance), we can say free as libre or livre. And the other meaning of free, as in free beer, as gratis. So, for others, there was never a confusion (actually, only when reading english articles about it).

Freedom number 2 guarantees my right to redistribute copies at will. I understand that as I don't need to pay the owner any royalties for every copy I give away to my friends or students. And of course, we will agree with that. This, ultimately means, that I can give free (gratis) copies, or also I can charge for copies (support, media, etc.).

Now, If something can be given away for free (gratis), then it is free (gratis). No matter if someone, or some enterprise, wants to sell, you still have ways (sites, downloads, friends, etc.) to get it for free (gratis).

So, in my non-english point of view, we have 3 different things here. The most important, undoubtedly, is the free (freedom, liberty, libre, livre, so you can all the stuff you want) quality of the software. The other, is being open-source (so you can  see the code inside). The last one IS another GREAT quality, that is, there EXIST free (gratis, non-chargeable) software.

Being free (gratis) does not mean it is forced free (gratis). You can have people who sells, who pays, and who gets/sends for free. Still, it is a quality.

What I don't understand is why, after so many years, people from FSF are still cautious to say that there is free (gratis) software also. Yes, free as in free beer. If it is a quality why hide it? Just to prevent confusion? Well, let me tell you the news: confusion was already made since the beginning. I was alive and interested in the subject when it started, and I remember lots of discussions about this free being free of charge, or free of restrictions.

After lots of consulting, lawyers helped to write the first "license" in terms that could be used in court, introduced the term "copyleft", and made it "clear" that free is not about price.

At that time, because of the novelty, ok, I agree to emphasize this half-part of the free. But now we are over it. Isn't it time to tell people that we ALSO have free as in free of charge.

Three qualities is better than two: livre/gratis/open.

So, why don't we tell people that free software can be just free?

Edited:

More objectively: 1- Is a free (freedom) software necessarily free (gratis)? 2- Is a free (gratis) software necessarily free (freedom).

The first one is the important question, as the second is just there to hold fast typers (we all know the answer).

Another question raised from the discussion: Is free (gratis) a quality? (I assumed that as taken for granted in the question introduction)

答:
The last one IS another GREAT quality, that is, there EXIST free
  (gratis, non-chargeable) software.

What I don't understand is why, after so many years, people from FSF are still cautious to say that
  there is free (gratis) software also. Yes, free as in free beer. If it
  is a quality why hide it? Just to prevent confusion?

The problem with just "Gratis" software is that any software where you don't have to pay to use it is gratis (free). Regardless of what draconian license there might be. And ofcourse with the grand success of free software, the aiblity to label software as free is worth a lot.

OwnerDisplayName: Dr Beco

Title: free as in free beer


问:
How to structure an application which reads UPC barcodes
I have no previous experience on creating a project for a seller which will use barcode reader. I am trying to put together a small project but I cannot figure out how the pieces should glue together.

I will create a sample with Motorola Scanner SDK to read barcodes and from that point, I have couple of questions:

How UPC barcodes work in general? AFAIK, a barcode stores the manufacturer and product info but no price data.

Should I store price information inside a database which corresponds to barcode data?

I would really appreciate if you can guide me here.

答: It is able to integrate such a upc barcode reader into the project to scan and decode the UPC barcodes. UPC barcodes only encode 12 or 6 numeric digits, so information of products couldn't be stored in this barcode symbol.</p>


问:
Reinventing the wheel, or the technology that drives it?
I recently asked a question on StackOverflow that was related to string splitting and pattern matching in .NET.

Some beady eyed developers that viewed the question said: "It looks like you're trying to parse a JSON string...why don't you just use JSON.NET or JavaScriptSerializer".

The conversation went off at on a tangent, (and was voted down, most likely because they could not see the point of writing some functionality, which has already been done.)

I have my reasons for writing this functionality...my implementation so far is slick, and super-fast (though suffers a little with string splitting, hence the StackOverflow question).

I think the point these developers were trying to make was, "why reinvent the wheel?"

I might equally argue: "Why bother developing NHibernate, when Microsoft have built a perfectly good Entity Framework?", or "Why bother building Windows 8, when Windows 7 is a perfectly suitable desktop operating system?" The same principle applies, does it not?

When an automobile company designs a new car, they are not re-inventing the wheel; rather, they are improving on the technology that drives it. Similarly, my JSON parser is a nice, neat and fast implementation (although, as states above, suffers a little on string splitting), therefore, when my parser is ready, should I be shunned for writing something that has already been done, or praised for doing it better?

EDIT: Consider the following Q/A : Is reinventing the wheel really all that bad?

答:
There are 2 reasons why this happens:

Someone thinks they can do it better. This is case of NHibernate vs Entity Framework. They were created by different (groups of) people to solve same problems. They both approached the problem from different side, thinking they will be better at solving it. Every time someone does this, they need to be sure, they are able to create something better than what exists. If your JSON parser you wrote in a week cannot do everything existing JSON parsers do and something more, then it is worthless. Or if this JSON parser does it in way that you need but other JSON parsers cannot provide. But JSON parsing is relatively simple and it is hard to believe you would need something other parsers don't provide. Only reason why you would create it is to learn how to write JSON parsers.

The problems change. This is case of Windows 8 vs Windows 7. Win 8 was created for new age, where touch, app stores, locked down platforms and small devices have future, instead of old heavy desktops, keyboard and mouse. This doesn't seem to be your problem, because JSON is still one of the top choices for data serialization. Of course it would be worth it if you came up with a storage format that would be somehow better than JSON. And I hardly doubt that.


答:
Kilian has a good point that 3. is unnecessary in that it is a release management / deployment aspect, rather than the software development one. Usually there is a field like Fix Version which can be amended by the release team later when it is decided which release to include the fix in. Also he is right that the DEV team should not have the final say whether an issue is fixed or not.

For the back-and-forth communication between the DEV and the QA team the right field to use is the Assigned To. When the QA team finally confirms that the issue is fixed, they can set the status to fixed.

This workflow should be supported by most issue tracking tools (I use JIRA these days).


答:
Don't confuse having more than two values in a field (active / fixed) with having multiple fields. Of course QA gets a say as to whether the bug is fixed or not. And perhaps the end user can accept a feature. But that info can still all be in a single field with values like:

```<code>proposed / approved / active / coded / tested / deployed / acccepted
</code>```

With multiple fields (one for the business decision to do it, one for the developer's opinion, one for QA's opinion, etc) you could end up with a situation where the developer status is still "working on it" and the QA status is "tested and ready to deploy". Then you would need process or code to make sure one status was never out of sync with the others. Having a single field makes conflicts like that impossible.

Body:
Don't confuse having more than two values in a field (active / fixed) with having multiple fields. Of course QA gets a say as to whether the bug is fixed or not. And perhaps the end user can accept a feature. But that info can still all be in a single field with values like:

proposed / approved / active / coded / tested / deployed / acccepted

With multiple fields (one for the business decision to do it, one for the developer's opinion, one for QA's opinion, etc) you could end up with a situation where the developer status is still "working on it" and the QA status is "tested and ready to deploy". Then you would need process or code to make sure one status was never out of sync with the others. Having a single field makes conflicts like that impossible.


问:
Project Proposal templates/requirements
When drafting a project proposal, do you use any standard template?

What features/information should be included? What is nice to have included? What sort of boiler plate information should I shove in?

Do you find any design pattern or concept particularly helpful?

答:
The US Department of Defense put a lot of work into developing a full set of Data Item Descriptions (templates) to go with DOD-STD-2167A, and later for MIL-STD-498.

There's an old saying: "Navy Regulations are written in blood."  If you read the DIDs carefully, you are likely to come away with the realization that every line of them is written in the blood of program managers whose projects died a horrible death because they neglected the item in that line.

You could do worse that look into these.

Title: Project Proposal templates/requirements


问:
Why most use Cygwin and not Uwin?
Most academic researchers I know target just *nix, and rely on Cygwin to make their applications available on Windows. I have tried many of these projects and always found them too unstable for serious use when running on Cygwin.

Uwin looks like a promising alternative to Cygwin. I haven't tried it yet, but I found several comments that it is faster and more stable. However, I haven't seen any use of Uwin to support running *nix apps on Windows.

What are the social and/or technical reasons behind Uwin's lack of popularity?

答:
First reason: UWIN was not originally open source;
Second reason: Uwin executables requires a running service to be installed on the target OS, while cygwin uses a pure dynamic library.</p>

Title: Why most use Cygwin and not Uwin?


问:
How to synchronize configuration for Findbugs between build server/Maven and several programmers
Here's a common scenario for developers who want to integrate static analysis in their workflow. Any suggestions on how to get this working with a minimum of pain?

The situation is similar to the one discussed here:
http://enterprise-it-solutions.blogspot.dk/2011/02/maven-configure-checkstyle-pmd-eclipse.html

The dev system uses a centralized build server based on Maven and Hudson. The developers use Eclipse and Java, and use a standard tool (git, svn or baazar) for source control

The developers need a local version of the static analysis tool to avoid having to deal with a dozen quality issues at once when they want to check in a change.

The build server (Maven + Hudson) has a Findbugs configuration that defines "Current standard for quality".

For each programmer, there should also be a standard configuration for Findbugs that is at least as restrictive as the server-side configuration, and perhaps even identical to it.

The programmer should be able to change his local configuration, because - let's face it - he's gonna do that anyway at least once, yet it should be relatively easy to reset to standard. Changes should only flow from the server to the developers, not the other direction.

答:
looks like you've reached a great stage in the evolution in your CI builds.  What you're probably after next is Sonar.

Localised configurations can be shared out of say a GitHub repo which can contain IDE or Maven plugin shared config. However, these types of checks actually slow local developers down a great deal, it's generally a reasonable trade-off for Sonar to pickup on those things and report back to the developer.


问:
Effective template system
I'm building a content management system, and need advice on which theming structure should I adopt. A few options (This is not a complete list):

Wordpress style:

the controller decides what template to load based on the user request, like: home page / article archive / single article page etc.

each of these templates are unrelated to other templates, and must exist within the theme

the theme developer decides if (s)he want to use inner-templates (like "sidebar", "sidebar item"), and includes them manually where (s)he thinks are needed.

Drupal style:

the controller gives control to the theme developer only to inner-templates; if they don't exist it falls back internally to some default templates (I find this very restrictive)

Funky style:

the controller only loads a "index.php" template and provides the theme developer conditional tags, which he can use to include inner-templates if (s)he wants.

Among these styles, or others what style of template system allows for fast development and a more concise design and implementation.

答:
You might classify this as either an example of your "Funky" style or as a discrete fourth style:

4. Smarty style:

Include plain-text markers (usually delimited by curly braces) for replaceable items in the template; interpret the entire template at run time, replacing markers with content. The process aims to be more designer friendly since programming constructs are not directly embedded. Whether you use Python or PHP or other server language, you'll parse and replace the placeholders the same way, so the template is relatively benign and reusable in that sense. Conversely, you generally give up being able to pass parameters to embedded functions.

However, you've asked a deeper question that I've also had to wrestle with, and have thoughts to offer: "What style of template system allows for fast development and a more concise design and implementation."

Since your are developing your own CMS, you have the freedom to define your own interfaces to the template system rather than adapting your interfaces to an existing system. You might consider:

Do you want to provide an API to other systems that will bypass your templates? In this case, at the point where you would ordinarily call your template, all of your content needs to be available as fully resolved endpoints for the remote API requests. As a result, your templates will generally be executable HTML files with variable calls that instance that same content into the appropriate places in the template.

Most API-driven applications will request the main content (title, author, body, page meta) but typically not the same inner-template parts like the sidebar or footer widgets as the web-based user experience. This is a good design approach for any CMS that provides fairly narrative or static content--that is, the content area of the web page can be easily pre-built as a chunk of content prior to being instanced into the template or sent as an API response. Templated content of this form tends to use category names as the labels for the primary tabs, since the main role of the web interface is to provide hierarchical drill-down into rich CMS content (encyclopedic or reading-oriented sites for example). The single index is fine in this case because there is no functional change from view to view, just content updates. Lends itself to front-controller type routing that ties into the content categories/hierarchies.

Does the CMS provide more of an application-based behavior? If the top-level navigation is instead switching from home page to forum to blog to admin, etc., then the "content" is probably very different in each template, and probably a series of functions/queries with headings rather than static content.

Here, you may either have a separate template wrapping each distinctive type of main content (forum vs blog vs static home page), or a single template with a function in the body that switches the instanced content. Either way, you can still serve that content as endpoints for API requests. This general CMS approach lends itself to page-controller type routing if using separate, type-dependent page templates, particularly if the template shell itself may need to be somewhat different for each content type. On the other hand, if you can implement the content switching via the single embedded function (which may need to control sidebar content if it contains context-dependent widgets), then you can still use the single index template approach which will give you more consistent look and feel experience for users. Either page controller or front controller routing can provide the resolution for that content switching--you are just using a common template with a parameterized content switch instead of a parameterized page with its own fixed content type.

If you can make a clean interface between the content that the CMS prepares in response to a query and the template system (or API call) that uses it, then you will have an additional advantage: By simply changing the name of the template directory, your same-named templates in the new directory will render the same content nearly equivalently. I think this is the single most important payoff of designing that content:template:api interface clearly--you end up with a richer outer template environment like Wordpress enjoys, your context-dependent regions like the sidebar and the footer can make use of inner templates for instancing content into the outer template like Drupal, and you can define the replacement mechanism as either a programming call or a parsed locator as your application requires. I'm able to take any free or commercial template and retrofit it with my CMS interfaces in fairly short order to support very different thematic styles. Most of the work ends up defining separate views between different themes that have their own inner styles for non-primary content (such as sidebar widgets or for the lists/tables used to represent collections; the main content usually just pours into its reserved area without intermediate processing).

Hoping this make sense for the CMS you are designing!

Title: Effective template system


问:
Designing a function with many optional components
I'm trying to figure out a good practice for designing a function with (many) optional components.

For a specific example, say I am interested in designing a feature extractor function that takes as input a document and returns a list of features extracted from the document.

Question

If there are many optional components, what kind of approach would be considered good practice and scalable?

Below are a couple options I have been able to think of, though there may be other approaches that I have not considered.

Approach 1: class based

```<code>class FeatureExtractor(object):
    """Extract features from text for use in classification."""
    def __init__(self, term_frequency=False, consider_negation=False,
                 pos_tags=False):
        self.term_frequency = term_frequency
        self.consider_negation = consider_negation
        self.pos_tags = pos_tags
        # Could be many more ...

    def extract(self, document):
        """Extract features from a document."""
        features = []
        if self.term_frequency:
            features.extend(self.extract_term_frequency(document))
        if self.consider_negation:
            features.extend(self.extract_negation(document))
        if self.pos_tags:
            features.extend(self.extract_pos_tags(document))
        return features

    def extract_term_frequency(self, document):
        pass

    def extract_negation(self, document):
        pass

    def extract_pos_tags(self, document):
        pass

extractor = FeatureExtractor(term_frequency=True, consider_negation=True,
                             pos_tags=True)
extractor.extract(document)
</code>```

Approach 2: function arguments

```<code>def extract(document, *functions):
    """Extract features from a document."""
    features = []
    for function in functions:
            features.extend(function(document))
    return features

def extract_term_frequency(document):
    pass

def extract_negation(document):
    pass

def extract_pos_tags(document):
    pass

extract(document, extract_term_frequency, extract_negation, extract_pos_tags)
</code>```

Approach 3: class with mixins or multiple inheritance

Something of a combination of the first and second approach, though I'm not sure how this would be done.

Any ideas on a direction to head would be greatly appreciated!

答:
With what you are showing there I prefer the function arguments because there is less code involved to go wrong. I would still use some kind of class to join them together.

However, if I were implementing a system like this I would be much less tied to the implementation. I'm not sure what you mean by "features extracted from a document" but let's imagine that the document was the specification for a car and mentions that it has alloy wheels, runs on petrol or diesel and so on. If I wanted to extract that data, depending on whether I wanted to approach things from a feature-first or document-first direction I would be thinking of creating a collection of the features I was interested in or a collection of the features that I could extract from the document.

In the first case I might say:

```<code>def featuresILike = { "alloy wheels":"/alloy wheels/", "v8 engine":"/V8/" } and so on.
</code>```

Then I can just run through the document looking for matches to those patterns and adding the related key to this documents feature metadata if I find it.

In the second case I might look for the pattern indicating a list of features, and then try to extract all the features listed in a particular document into the metadata. That way I can just query against all of them as necessary.

The conceptual difference with this type of approach is that I am aiming to treat data as data and then use my code to extract it. Every time I write a "hasAlloyWheels()" type function what I'm really doing is making my data into code. Sometimes you might need to do that, but if you can extract that information into configuration or narrow down your code so it only happens in a couple of places, you're going to end up with something that is both more reusable and easier to maintain.

Body:
With what you are showing there I prefer the function arguments because there is less code involved to go wrong. I would still use some kind of class to join them together.

However, if I were implementing a system like this I would be much less tied to the implementation. I'm not sure what you mean by "features extracted from a document" but let's imagine that the document was the specification for a car and mentions that it has alloy wheels, runs on petrol or diesel and so on. If I wanted to extract that data, depending on whether I wanted to approach things from a feature-first or document-first direction I would be thinking of creating a collection of the features I was interested in or a collection of the features that I could extract from the document.

In the first case I might say:

def featuresILike = { "alloy wheels":"/alloy wheels/", "v8 engine":"/V8/" } and so on.

Then I can just run through the document looking for matches to those patterns and adding the related key to this documents feature metadata if I find it.

In the second case I might look for the pattern indicating a list of features, and then try to extract all the features listed in a particular document into the metadata. That way I can just query against all of them as necessary.

The conceptual difference with this type of approach is that I am aiming to treat data as data and then use my code to extract it. Every time I write a "hasAlloyWheels()" type function what I'm really doing is making my data into code. Sometimes you might need to do that, but if you can extract that information into configuration or narrow down your code so it only happens in a couple of places, you're going to end up with something that is both more reusable and easier to maintain.


答:
I think the central question you should be asking yourself here is "what sort of features are you expecting to extract from a document"?

If you want to be able to add new feature extractor functions with ease, go for the second version, where each feature gets extracted independently and handles the document by itself.

On the other hand, if you know upfront what sort of features you are going to need, using a central extractor that takes advantage of that knowledge to extract things all at once (using parameters to tune the features, ofc)

As for classes vs functions I honestly don't think they are too different one from the other, since in the end they encapsulate things the same way. In Python's case I would recommend using "callables" when possible (so you can use either functions or objects defining __call__ where appropriate) and I would always use functions over classes unless I need to keep track of some extra internal state (Python closures suck due to the local by default scoping)

Title: Designing a function with many optional components

Body:
I'm trying to figure out a good practice for designing a function with (many) optional components.

For a specific example, say I am interested in designing a feature extractor function that takes as input a document and returns a list of features extracted from the document.

Question

If there are many optional components, what kind of approach would be considered good practice and scalable?

Below are a couple options I have been able to think of, though there may be other approaches that I have not considered.

Approach 1: class based

```<code>class FeatureExtractor(object):
    """Extract features from text for use in classification."""
    def __init__(self, term_frequency=False, consider_negation=False,
                 pos_tags=False):
        self.term_frequency = term_frequency
        self.consider_negation = consider_negation
        self.pos_tags = pos_tags
        # Could be many more ...

    def extract(self, document):
        """Extract features from a document."""
        features = []
        if self.term_frequency:
            features.extend(self.extract_term_frequency(document))
        if self.consider_negation:
            features.extend(self.extract_negation(document))
        if self.pos_tags:
            features.extend(self.extract_pos_tags(document))
        return features

    def extract_term_frequency(self, document):
        pass

    def extract_negation(self, document):
        pass

    def extract_pos_tags(self, document):
        pass

extractor = FeatureExtractor(term_frequency=True, consider_negation=True,
                             pos_tags=True)
extractor.extract(document)
</code>```

Approach 2: function arguments

```<code>def extract(document, *functions):
    """Extract features from a document."""
    features = []
    for function in functions:
            features.extend(function(document))
    return features

def extract_term_frequency(document):
    pass

def extract_negation(document):
    pass

def extract_pos_tags(document):
    pass

extract(document, extract_term_frequency, extract_negation, extract_pos_tags)
</code>```

Approach 3: class with mixins or multiple inheritance

Something of a combination of the first and second approach, though I'm not sure how this would be done.

Any ideas on a direction to head would be greatly appreciated!


答:
The basic rule-of-thumb is that in FP programming functions do the same job as objects do in OO-programming. You can call their methods (well, the "call" method anyway) and they respond acording to some encapsulated, internal rules. In particular, every decent FP language out there lets you have "instance variables" in your function with closures / lexical scoping.

var make_OO_style_counter = function(){
   return {
      counter: 0
      increment: function(){
          this.counter += 1
          return this.counter;
      }
   }
};

var make_FP_style_counter = function(){
    var counter = 0;
    return fucntion(){
        counter += 1
        return counter;
    }
};
```

<p>Now the next question is what do you mean by an interface? One approach is using nominal interfaces (it conforms to the interface if it says it does so) - this one usually depends a lot on what language you are using so lets leave it for latter. The other way to define an interface is the structural way, seeing what parameters thing receive and return. This is the sort of interface you tend to see in dynamic, duck-typed languages and it fits very well with all of FP: an interface is just the types of the input parameters to our functions and the types they return so All functions matching the correct types fit the interface!</p>

<p>Therefore, the most straightforward way of representing an object matching an interface is to simply have a group of functions. You usually get around the uglyness of passing the functions separately by packing them in some sort of record:</p>

```var my_blarfable = {
 get_name: function(){ ... },
 set_name: function(){ ... },
 get_id:   function(){ ... }
}

do_something(my_blarfable)
```

<p>Using naked functions or records of functions will go a long way in solving most of your common problems in a "fat-free" manner without tons of boilerplate. If you need something more advanced than that, sometimes languages give you extra features. One example people mentioned is Haskell type classes. Type classes essentially associate a type with one of those records of functions and lets you write things so the dictionaries are implicit and get automatically passed to inner functions as appropriate.</p>

<pre class="lang-hs prettyprint-override"><code>-- Explicit dictionary version
-- no setters because haskell doesn't like mutable state.
data BlargDict = BlargDict {
    blarg_name :: String,
    blarg_id   :: Integer
}

do_something :: BlargDict -> IO()
do_something blarg_dict = do
   print (blarg_name blarg_dict)
   print (blarg_id   blarg_dict)

-- Typeclass version
class Blargable a where
   blag_name :: a -> String
   blag_id   :: a -> String

do_something :: Blargable a => a -> IO
do_something blarg = do
   print (blarg_name blarg)
   print (blarg_id   blarg)
</code>```

One important thing to note about typeclasses however is that the dictionaries are associated with the types, and not with the values (like what happens in the dictionary and OO versions). This means you that the type system doesn't let you mix "types" [1]. If you want a list of "blargables" or a binary function taking to blargables then typeclasses will constrain everything to be the same type while the dictionary approach will let you have blargables of different origins (which version is better depends a lot in what you are doing)

[1] There are advanced ways to do "existential types" but its usually not worth the trouble.

Title: What is the functional-programming alternative to an interface?

Body:
If I want to program in a "functional" style, with what would I replace an interface?

```<code>interface IFace
{
   string Name { get; set; }
   int Id { get; }
}
class Foo : IFace { ... }
</code>```

Maybe a Tuple<>?

```<code>Tuple<Func<string> /*get_Name*/, Action<String> /*set_Name*/, Func<int> /*get_Id*/> Foo;
</code>```

The only reason I'm using an interface in the first place is because I want always want certain properties/methods available.

Edit: Some more detail about what I'm thinking/attempting.

Say, I've got a method which takes three functions:

```<code>static class Blarf
{
   public static void DoSomething(Func<string> getName, Action<string> setName, Func<int> getId);
}
</code>```

With an instance of Bar I can use this method:

```<code>class Bar
{
   public string GetName();
   public void SetName(string value);

   public int GetId();
}
...
var bar = new Bar();
Blarf.DoSomething(bar.GetName, bar.SetName, bar.GetId);
</code>```

But that's a bit of a pain as I have to mention bar three times in a single call.  Plus, I don't really intend for callers to supply functions from different instances

```<code>Blarf.DoSomething(bar1.GetName, bar2.SetName, bar3.GetId); // NO!
</code>```

In C#, an interface is one way to deal with this; but that seems like a very object-oriented approach.  I'm wondering if there's a more functional solution: 1) pass the group of functions together, and 2) ensure the functions are properly related to each other.

Body:
The basic rule-of-thumb is that in FP programming functions do the same job as objects do in OO-programming. You can call their methods (well, the "call" method anyway) and they respond acording to some encapsulated, internal rules. In particular, every decent FP language out there lets you have "instance variables" in your function with closures / lexical scoping.

var make_OO_style_counter = function(){
   return {
      counter: 0
      increment: function(){
          this.counter += 1
          return this.counter;
      }
   }
};

var make_FP_style_counter = function(){
    var counter = 0;
    return fucntion(){
        counter += 1
        return counter;
    }
};

Now the next question is what do you mean by an interface? One approach is using nominal interfaces (it conforms to the interface if it says it does so) - this one usually depends a lot on what language you are using so lets leave it for latter. The other way to define an interface is the structural way, seeing what parameters thing receive and return. This is the sort of interface you tend to see in dynamic, duck-typed languages and it fits very well with all of FP: an interface is just the types of the input parameters to our functions and the types they return so All functions matching the correct types fit the interface!

Therefore, the most straightforward way of representing an object matching an interface is to simply have a group of functions. You usually get around the uglyness of passing the functions separately by packing them in some sort of record:

var my_blarfable = {
 get_name: function(){ ... },
 set_name: function(){ ... },
 get_id:   function(){ ... }
}

do_something(my_blarfable)

Using naked functions or records of functions will go a long way in solving most of your common problems in a "fat-free" manner without tons of boilerplate. If you need something more advanced than that, sometimes languages give you extra features. One example people mentioned is Haskell type classes. Type classes essentially associate a type with one of those records of functions and lets you write things so the dictionaries are implicit and get automatically passed to inner functions as appropriate.

-- Explicit dictionary version
-- no setters because haskell doesn't like mutable state.
data BlargDict = BlargDict {
    blarg_name :: String,
    blarg_id   :: Integer
}

do_something :: BlargDict -> IO()
do_something blarg_dict = do
   print (blarg_name blarg_dict)
   print (blarg_id   blarg_dict)

-- Typeclass version
class Blargable a where
   blag_name :: a -> String
   blag_id   :: a -> String

do_something :: Blargable a => a -> IO
do_something blarg = do
   print (blarg_name blarg)
   print (blarg_id   blarg)

One important thing to note about typeclasses however is that the dictionaries are associated with the types, and not with the values (like what happens in the dictionary and OO versions). This means you that the type system doesn't let you mix "types" [1]. If you want a list of "blargables" or a binary function taking to blargables then typeclasses will constrain everything to be the same type while the dictionary approach will let you have blargables of different origins (which version is better depends a lot in what you are doing)

[1] There are advanced ways to do "existential types" but its usually not worth the trouble.


问:
Is there a device still being sold that requires efficient programming? What is it?
Edit: As a lot of you have pointed out, efficient can mean a lot of things. I guess when I say that the device 'requires efficient programming', I mean that the device does not have lots of memory or a very high CPU clock rate, and therefore needs to be programmed with these limitations in mind.

Original Question: Sometimes, to train themselves, athletes will work in higher altitude places to workout. This is because there is less air, meaning working out is much more difficult. Once athletes have gotten used to exercising in these conditions, they find doing physical work in normal altitude places much easier.

I want to do this same thing, except with software development, and more specifically, game development. I want to find some system with a low amount of RAM (in the kilobytes), low CPU clock speed, and few registers. I figure learning to program games on this kind of system would be very useful in teaching me to write efficient code. Also, it would be very fun :)

The systems that I have thought about programming are the old Nintendo ones; GBA, NES, SNES. But I have learned the hard way that obtaining these, then obtaining the flash cards for them are very difficult, and on the border of being illegal.

So, my question is is there a crummy device that will teach me to write efficient code that is still out there and being sold? I would like it to be a physical device, looking at my programs run on physical machines would be a lot more satisfying then watching it on an emulator, and also, emulators can be buggy.

答:
You're pretty much looking for anything with a microcontroller.  You can roll your own, but you probably want to start with a pre-built board like an Arduino, PICAXE, Basic Stamp, BeagleBone, or even a robotics platform like a quadcopter or roomba.

That being said, there are many different aspects to "efficiency," and embedded development doesn't necessarily cover all of them.  For example, some applications might be able to increase execution speed significantly by using gigabytes of RAM "inefficiently."