问:
Approach to Authenticate Clients to TCP Server
I'm writing a Server/Client application where clients will connect to the server. What I want to do, is make sure that the client connecting to the server is actually using my protocol and I can "trust" the data being sent from the client to the server.

What I thought about doing is creating a sort of hash on the client's machine that follows a particular algorithm. What I did in a previous version was took their IP address, the client version, and a few other attributes of the client and sent it as a calculated hash to the server, who then took their IP, and the version of the protocol the client claimed to be using, and calculated that number to see if they matched. This works ok until you get clients that connect from within a router environment where their internal IP is different from their external IP. My fix for this was to pass the client's internal IP used to calculate this hash with the authentication protocol. My fear is this approach is not secure enough. Since I'm passing the data used to create the "auth hash".

Here's an example of what I'm talking about:

```<code>Client IP: 192.168.1.10, Version: 2.4.5.2
hash = 2*4*5*1 * (1+9+2) * (1+6+8) * (1) * (1+0)
Client Connects to Server
client sends: auth hash ip version
Server calculates that info, and accepts or denies the hash.
</code>```

Before I go and come up with another algorithm to prove a client can provide data a server (or use this existing algorithm), I was wondering if there are any existing, proven, and secure systems out there for generating a hash that both sides can generate with general knowledge. The server won't know about the client until the very first connection is established.

The protocol's intent is to manage a network of clients who will be contributing data to the server periodically.

New clients will be added simply by connecting the client to the server and "registering" with the server. So a client connects to the server for the first time, and registers their info (mac address or some other kind of unique computer identifier), then when they connect again, the server will recognize that client as a previous person and associate them with their data in the database.

Edit:
The approach I ended up going was this:

I ended up using an approach similar to what OpenSSH does, but reverse. Since when a client connects, I'm not sure I can trust the client.

If it is the first time a client is connecting, it will provide me with a public key and a unique identifier (In this case, I will be using a computer's service tag since the computers I'm going to be dealing with are all Dells). The server stores the id and public key in the database then sends the client a secret question encrypted using the public key. The client will then need to respond with the decrypted answer. Before a client can be accepted by the server, I may end up doing a unique id registration on the server manually before connecting the client for the first time, this way not any sly person can just generate public keys and emulate what a client does with a "new unique id".

Thanks for the help! I hope this helps someone down the line. Feel free to tear apart the security flaws of this approach :)

答:
You can't really do authentication without sharing anything before hand. If you can have any sort of shared secret (i.e a key), you can use challenge-response authentication using an appropriate message digest algorithm.

On the topic of protocol compatibility, I would separate the concerns. You can use a traditional handshake to verify that the customer is speaking the same protocol/version the server uses (or a compatible one), but authentication is best dealt with separately.

An alternative with an acceptable tradeoff in many distributed systems is trusting the first connection from a specific client, sharing a key and then validating all subsequent connections from the same client using that. This is what OpenSSH does when connecting to a new server (prompts you whether you want to connect to an unknown host, and then store the fingerprint of that host and validate it on subsequent connections). You can find a more detailed explanation of the SSH "known hosts" mechanism on the WinSCP wiki.

Puppet uses a variant of this where they have a signed (trusted) SSL certificate on each client. When first connecting an agent with the server, the agent will issue a certificate signing request for the server that you then have to manually sign and give to the agent. This has added security but can become annoying quickly if you need to set up lots of clients, or do it without anyone interacting with the system. This is why there is a configuration option that changes the behavior to be like SSH's (trust everyone that you haven't seen before, validate identities only for known hosts). This is described in more detail at the PuppetLabs website.

In the end, what you have is an issue of trust. The question remains: how can you trust a connection from a client? The answer to this isn't technical in nature - accepting any new connection by an unknown host and trusting it blindly might work for some systems, but not for all. It really depends on the tradeoffs of the actual system you are implementing, and the capabilities granted to the client by the server.


问:
Managing Personal Projects As Solo Developer - Getting out of depth and failing projects
I need some advice on project management.

I start a project, and often times it will a large project for a solo developer. Usually its a web project. I handle everything from the UI, to the JS, PHP, server management etc. Half way in I feel out of my depth. I lose where I am, so I spend a couple of days away from the project to avoid the stress and before you know it, it becomes another unfinished project.

I try to use frameworks and code libraries to make my developments easier on myself. Sometimes I will complete a project so it "works" and then go back and handle errors, design the UI properly and stuff. But without fail I will always end up out of my depth.

I've though about outsourcing tasks such as the UI, and the behaviour, and focusing just on the PHP - which I feel is my strong point. But then pride kicks in, and I don't feel at one with a project I haven't completed myself. Does this make sense?

I am sure there are many others who have felt like this either at home, or at work, and I would love some advice on managing my projects better.

答:
But then pride kicks in, and I don't feel at one with a project I
  haven't completed myself. Does this make sense?

What's you motivation for these projects? Fun?  Learning? Then maybe it makes sense, tho you could argue you'd learn working with others. Actually making a finished thing or business goals? Then it absolutely does not make sense. Find a way to get over it.

ContentLicense: CC BY-SA 3.0


问:
User Story vs Requirement
User Story captures what the user wants to do with the system at a high level. I understand that the user story would further drive a number low level requirements. Is user story same as high level requirement for the system?</p>

答:
I believe that everyone will implement and label everything differently depending on past experience and whatever language works for that company which gets the job done is not worth arguing over.

However, IMO, A User Story follows the Agile's approach of "a customers in the building or the customer is immediately available"  approach, where documentation isn't necessarily needed because the details are in the customers head and readily available so a formal SRS may not be required. Now a "Task" of a "User story" is how a developer is going to build the user stories in digestible.

An example user story might be:

As an admin user I want to view my clients data listed in a grid

and a "task" might be:

Create a Grid which lists the data to be displayed

Enable Sorting on the grid which will sort the column selected

Now each of the tasks is estimated and completed in its respective sprint.

From a "traditional" perspective, where "the customer is hard to get a hold of, we need to write this down so that they can confirm we've got it right before we start planning / coding" approach, the Software Requirement Specification is going to be the ideas that were in the customers head and elicited and then written down and formalized and then baselined and managed.

In this case, a "functional requirement" is the nitty-gritty detail of that SRS, and a part of the larger Idea. So in my opinion,  a user story could be seen as a (portion of the) formal "Requirement", and the task of that user story is a (or one of the many) functional-requirement.

In the example user story, the formal "Requirement" would be a lengthy document with flow charts and generally is going to be documentation-centric, as opposed to the more "Agile" approach which is customer-centric.

The difference being, the formal "Requirement" is going to be along the lines of some 10 page document outlining the administration section of the app which indicates some listings will be needed, some role based security, etc.. and then some of the functional requirements will be "the listing grids shall enable sorting", "the user information shall be listed in a grid", etc..

and i do believe these days the terms are all mixed and mingled.. which doesnt matter at all

Title: User Story vs Requirement


问:
Loose typing not applied to objects
I have very little experience working with classes and object. I work in a loosely typed language, PHP.

I was working with a SimpleXML object and ran into a problem where I was trying to do math with an element of that object like $results->ProductDetail->{'Net'.$i};

If I echoed that value, I'd get 0.53 but when I tried to do math with it, it was converted to 0

Is there a reason that a loosely typed language would not recognize that as a float and handle it as such? Why would "echo" handle it as a string but the math fail to convert it?

Example:

```<code>$xml='<?xml version="1.0" encoding="UTF-8" ?>';
$xml.='<Test>
  <Item>
    <Price>0.53</Price>
  </Item>
</Test>';

$result=simplexml_load_string($xml);

var_dump($result->Item->Price);
echo '<br>';
echo $result->Item->Price;
echo '<br>';
echo 1+$result->Item->Price;
echo '<br>';
echo 1+(float)$result->Item->Price;
</code>```

Output:

```<code>object(SimpleXMLElement)#4 (1) { [0]=> string(4) "0.53" }
0.53
1
1.53
</code>```

No object version:

```<code>$no='.53';
echo 1+$no;
</code>```

Output:

```<code>1.53
</code>```

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

Side note:
PHP strpos() does not properly convert an integer needle $i into a string.

```<code>$x=101; $i=1; if(strpos($x,"$i")===FALSE){echo $i." missing";}
</code>```

and

```<code>$x=101; $i=1; if(strpos($x,$i)===FALSE){echo $i." missing";}
</code>```

give different results.
I don't want to become a php hater, but I'm beginning to lose that loving feeling.

答:
```<code>echo $result->Item->Price;
</code>```

That will output a string variable.

```<code>echo 1+$result->Item->Price;
</code>```

That will convert the string "0.53" to integer. PHP does not round up. So it becomes 0 and 1+0=1.

```<code>echo 1+(float)$result->Item->Price;
</code>```

That works because you're telling PHP to cast to a float. PHP will then auto convert the 1 from an int to float.

Alternatively, you can also do this.

```<code>echo 1.0+$result->Item->Price;
</code>```

That will tell PHP to convert the string to a float as well.

This is all part of PHP's type juggling.

http://us2.php.net/manual/en/language.types.type-juggling.php

Your issues are specific to string type conversion.

http://us2.php.net/manual/en/language.types.string.php#language.types.string.conversion

One of the reasons PHP can do these things is because the + operator is always mathematical. Where in other languages it performs string concatenation. Since + always performs addition PHP attempts to convert string types to numeric types to honor the + operation.

UPDATE: Problems specific to SimpleXMLElement

There is a known bug in PHP when using the extension SimpleXML. PHP will cast strings that represent float values to int instead of float. The automatic type juggling is not working correctly.

Here is a bug report for the issue: https://bugs.php.net/bug.php?id=54973

For now I recommend casting to (float) whenever you use SimpleXML and expect a float value. That should not break anything when the fix is pushed out in the future.

Title: Loose typing not applied to objects

Body:
echo $result->Item->Price;

That will output a string variable.

echo 1+$result->Item->Price;

That will convert the string "0.53" to integer. PHP does not round up. So it becomes 0 and 1+0=1.

echo 1+(float)$result->Item->Price;

That works because you're telling PHP to cast to a float. PHP will then auto convert the 1 from an int to float.

Alternatively, you can also do this.

echo 1.0+$result->Item->Price;

That will tell PHP to convert the string to a float as well.

This is all part of PHP's type juggling.

http://us2.php.net/manual/en/language.types.type-juggling.php

Your issues are specific to string type conversion.

http://us2.php.net/manual/en/language.types.string.php#language.types.string.conversion

One of the reasons PHP can do these things is because the + operator is always mathematical. Where in other languages it performs string concatenation. Since + always performs addition PHP attempts to convert string types to numeric types to honor the + operation.

UPDATE: Problems specific to SimpleXMLElement

There is a known bug in PHP when using the extension SimpleXML. PHP will cast strings that represent float values to int instead of float. The automatic type juggling is not working correctly.

Here is a bug report for the issue: https://bugs.php.net/bug.php?id=54973

For now I recommend casting to (float) whenever you use SimpleXML and expect a float value. That should not break anything when the fix is pushed out in the future.


问:
When would I use pseudocode instead of flowchart?
I'm a student working with various techniques of programming, and I've come across pseudocode and flowchart. I know that these are both used in order to think through the problem before actually programming, but I have a few questions with this.

When would I use pseudocode to plan out and when would I use flowcharts? Or is it better to do both before actually programming. Particularly for a small arcade sort of game in JAVA since that is my next project.

I've noticed that pseudocode is very similar to the actual code rather than flowcharts. Would this make pseudocoding better because you essentially copy/paste the pseudocode into your program (of course, you have to change it to fit the language. I understand that part).

Is it practical to use both of these while programming? Particularly the same game mentioned earlier.
Thanks.

答:
You could use a flowchart if you're getting really confused by if statements and you're trying to understand that.  Or if you're trying to understand a loop, see the effect of counters. If you're learning it can help a lot.

It can feel a bit restrictive 'cos you have to put brief statements into boxes. And if your program is very linear and your loops and ifs are trivial, then I see no use for it.

Pseudocode is useful for designing a program.without the distraction of having to get the syntax right, and without the long-windedness that some languages can involve.  The fact that it's quicker to write also makes it easier to redesign code. And you can be as concise as your mind desires, it's pleasant to write, requires less mental effort on getting it to work (as no or much less debugging), and more ability to focus on the big picture and design.

So, useful for yourself.

They can also be used to communicating to others.


问:
What is a byte stream actually?
Can anyone explain me what byte stream actually contains? Does it contain bytes (hex data) or binary data or english letters only? I am also confused about the term "raw data". If someone asked me to "reverse the 4 byte data", then what should I assume the data is hex code or binary code?</p>

答:
A byte stream is an ordered sequence of bytes. There is a first byte, which has no predecessor. Its successor is the second byte, and so on.  Nowadays, a byte is widely understood to consist of eight bits. If we want to be more precise, we use the term octet stream and octet. There still exist computers with bytes that aren't eight bits wide.

Hexadecimal is a way of writing numbers, and serves as a printed representation for binary data. Hexadecimal is actually text. For instance, the hexadecimal value FE might represent a byte: the bits 11111110 which have the decimal value 255. However FE is actually a character string consisting of the characters F and E, which requires two bytes in the US-ASCII or ISO-646 character set!  These two bytes is what FE is, and the single byte with value 254 is what the FE represents, as a printed notation.

If a communication channel, or file handle or some such device is described as carrying a byte stream, and no other information is given, it almost certainly does not mean that bytes are represented as hexadecimal text, so that each abstract byte in the stream requires two physical bytes.

And raw data simply means bits which are not interpreted to have any structure beyond just "array of bits". Raw data usually has a structure and represents something, but when we are looking at it as raw data, we are either ignoring the interpretation for the moment (for instance, we are looking at the raw representation of a data type to verify its correctness down to the bit level detail), or the interpretation is not available (we have some data, but we do not understand the structure of the data and what it represents).

Title: What is a byte stream actually?


问:
Advice on designing web application with a 40+ year lifetime
Scenario

Currently, I am apart of a health care project whose main requirement is to capture data with unknown attributes using user generated forms by health care providers. The second requirement is that data integrity is key and that the application will be used for 40+ years. We are currently migrating the client's data from the past 40 years from various sources (Paper, Excel, Access, etc...) to the database. Future requirements are:

Workflow management of forms

Schedule management of forms

Security/Role based management

Reporting engine

Mobile/Tablet support

Situation

Only 6 months in, the current (contracted) architect/senior programmer has taken the "fast" approach and has designed a poor system. The database is not normalized, the code is coupled, the tiers have no dedicated purpose and data is starting to go missing since he has designed some beans to perform  "deletes" on the database. The code base is extremely bloated and there are jobs just to synchronize data since the database is not normalized. His approach has been to rely on backup jobs to restore missing data and doesn't seem to believe in re-factoring.

Having presented my findings to the PM, the architect will be removed when his contract ends. I have been given the task to re-architect this application. My team consists of me and one junior programmer. We have no other resources. We have been granted a 6-month requirement freeze in which we can focus on re-building this system.

I suggested using a CMS system like Drupal, but for policy reasons at the client's organization, the system must be built from scratch.

This is the first time that I will be designing a system with a 40+ lifespan. I have only worked on projects with 3-5 year lifespans, so this situation is very new, yet exciting.

Questions

What design considerations will make the system more "future proof"?

What questions should be asked to the client/PM to make the system more "future proof"?

答:
Leaving aside the issues of the unreasonable expectations of your client and focusing on the design issues, I wouldn't go as far as 40 years, but the problem you seem to have, of long-term evolvability, is precisely what REST was created for. By that I really mean REST as an architecture style, not the buzzword driven development that's so commonly associated with the term these days.

To some extent, people get REST wrong because I failed to include enough detail on media type design within my dissertation. That’s because I ran out of time, not because I thought it was any less important than the other aspects of REST. Likewise, I suspect a lot of people get it wrong because they read only the Wikipedia entry on the subject, which is not based on authoritative sources.

However, I think most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result. As architectural styles go, REST is very simple.

REST is software design on the scale of decades: every detail is intended to promote software longevity and independent evolution.

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724

You mentioned you intend to use a RESTful interface. That comment by itself suggests you should do some serious research into that and try to understand what REST really is about. You're probably associating it merely with the mapping of HTTP methods to CRUD operations that most people think REST is, but it has nothing to do with that.

Think of REST as a formalization of the architecture of the web itself. In one way or the other, there are many parts of the web written a decade ago or more that are still available and can be used with a client made today, so we got something right in that department. It will be a lot of work, I guarantee you, because doing REST right is hard, but the long-term benefits are worth it.


问:
Service layer coupling
I am working on writing a service layer for an order system in php. It's the typical scenario, you have an Order that can have multiple Line Items. So lets say a request is received to store a line item with pictures and comments. I might receive a json request such as

```<code>{
    'type': 'Bike',
    'color': 'Red',
    'commentIds': [3193,3194]
    'attachmentIds': [123,413]
}
</code>```

My idea was to have a Service_LineItem_Bike class that knows how to take the json data and store an entity for a bike.

My question is, the Service_LineItem class now needs to fetch comments and file attachments, and store the relationships. Service_LineItem seems like it should interact with a Service_Comment and a Service_FileUpload. Should instances of these two other services be instantiated and passed to the Service_LineItem constructor,or set by getters and setters?  Dependency injection seems like the right solution, allowing a service access to a 'service fetching helper' seems wrong, and this should stay at the application level.

I am using Doctrine 2 as a ORM, and I can technically write a dql query inside Service_LineItem to fetch the comments and file uploads necessary for the association, but this seems like it would have a tighter coupling, rather then leaving this up to the right service object.

答:
When one is concerned with tight coupling, it is useful to remember the SOLID principles. In this case, you have a single command that has too many responsibilities: creating a bike, adding comments to it, and attaching pictures to it. Let's break it down:

Create (red) bike line item.

Comment on line item.

Attach picture to line item.

Create a separate method for each of these behaviors and forget all those abstractions (this is php after all ;). Call the appropriate method from the UI via Ajax when the user does something.

I'm guessing comments and attachments are wholly optional, so doing it this way would therefore not put your data into an invalid state.

Title: Service layer coupling


问:
category theory based language
It may sound naive, but is there any programming language, or research thereof, based entirely on category theory?

I mean this as opposed to embedding CT concepts as an additional feature (like for Haskell or scala).

Would it be too abstract or too complex as an approach, or are there any known reasons that makes it impossible or impractical?

I have only a relative understanding of the theory as related to programming, so please give me some explanation if the question doesn't makes sense at all

EDIT

What I mean is to define a language where categories are first class concepts, instead of let's say types.

E.g. haskell is defined in terms of types and functions over those. Does it makes sense to design a language where fundamental entities are categories and arrows?

From there you would, for example, define algebraic operations on numbers as individual "intances" of the proper algebraic category (ring, monoid, group...) instead of starting from standard integer/float operations and defining the corresponding categorical typeclass.

Does it makes sense?

答:
Category theory provides a tool. It wouldn't entirely make sense to decide "Oh hey, I'm going to make my programming language form a category" so much as one builds a kernel, and notices that it forms a category, and from there begins applying the free abstractions/theorems that come with it.

A perfect example of this is simply typed lambda calculus. This forms a closed cartesian category where types are objects and functions are arrows. Now, because of this, we can start to apply common abstractions, like endofunctors, adjoints, sub-categories, and similar. In fact, this is exactly what happened in Haskell where the type system is rooted in STLC's.

So I'd say what happens with Haskell is a great example of applying category theory to build abstractions. Many libraries in Haskell, mtl, pipes, lens, void, comonads are all very very useful abstractions that come from noticing that something is a category, and consequently generalizing and applying concepts.

The same thing happens on the research side of things. People have this concept that they notice has a parallel in category theory land, and extrapolate from there. For example, many problems in domain theory are greatly simplified by limits in category theory, and implicit coercions are nicely modeled by category theory.

So I'd say you're thinking of this wrong, don't think of category theory as the thing you build from, it's a bit too abstract for that, it's more that you use parallels between your problem and category theory for free theorems and abstractions in your problem.

Title: category theory based language


问:
Languages supporting unicode logic operators
Are there any programming languages that support the use of unicode logic operators? For example, many programming languages use "!=" as the "does not equal"
operator, but in mathematics the symbol is "≠".
Since unicode is now more standardized, why don't programming languages support their use as logical operators? Many of the symbols are on my keyboard, I just hit the alt button.

答:
Yes some languages do. Why not more? Probably because it's a pain to type. I use all the languages I linked above and I rarely use unicode syntax, it's not on my keyboard and it adds about 0 value to my code.

I'm also aware of the fact that unicode is standardized, but not always implemented well. Emacs had problems with it until quite recently, many languages still are bad at unicode which makes it a pain to parse/autogenerate.

That being said, when I do any literate programming or typeset code in anyway, I do use unicode, but there it's with a simple script to do textual substitutions.


问:
Is there a way to develop desktop software using PHP?
I have to develop a real estate marketing CRM software for my client - where the application is installed on desktop but can also be accessed from web.

2 reasons why they want the application to run from desktop :

So that it can work with/without internet connection

They don't want their complete data to be online

They want to access few of the data like property listing & inquiries (managed from desktop application) from their website through secure login & password.

The data that is entered in desktop application should be automatically synchronized with the website application. I was wondering if there is a way to develop this kind of software using PHP & MySQL.  If yes, it will be great if anyone can provide me the referral link.Else please suggest, which language should I use.

答:
Nightrain - PHP Desktop Packager might be what you are looking for. Nightrain does not include MySQL but you can install it on the user's computer or you can just update your application to use SQLite Database. For your these particular requirements switching to SQLite database might be better.

Here's what you have to do:

Download Nightrain from: http://www.nightrain.naetech.com/

Copy your application to the /www folder

Run the nightrain executable to launch your application, test it out or do whatever adjustments you have to


问:
model association or controller?
I'm trying to create a rails app that allows users to submit information about their pets.  I've come to a point where my knowledge is limited and I don't know enough about what/how this could be done so I'm hoping this will be relatively easy to answer.

At the moment I have a model called Pet, this model currently stores basic information like name, picture etc but it also holds more specific data like type, breed, date of birth etc.  What I would like to be able to do is create a page that can match various records without having to be manually categorized if that makes sense so a users pet could be matched to other pets with the same breed, age etc.

I've read about nested models as I understand this information could be submitted to 2 models in one form but I am not sure whether this could be done directly in a separate controller which would only be visible to users with pets in these matched "groups" if that makes sense.

So in essence is it best practice to use 1 table to store all the information and just use a controller to match pets based on rows having the same values or would it be far simpler to have a form with a nested model and link 2 tables together?

The main feature needs to be matching without a user having to create a group or categorize pets so the second model would need to add id's to an array instead of just creating more and more rows.

答:
I've used both one table and two tables.  The nice thing about two tables is you can perform additional queries on the details of the pets table and, say pet_details - plus, it keeps the tables smaller and easier to manage.

With a nested model, you wouldn't necessarily create a new controller unless you wanted to directly manipulate the data through the web or an API for your nested model.  The parent model Pet would handle all the manipulation of that data.  TL;DR - it basically just keeps it more organized.

OwnerDisplayName: andybritton

Title: model association or controller?

OwnerDisplayName: CDub


问:
Should my colleagues review each others code from source control system?
So that's my story: one of my colleagues uses to review all the code, hosted to revision system. I'm not speaking about adequate review of changes in parts that he belongs to. He watches the code file to file, line to line. Every new file and every modified. I feel just like being spied on!

My guess is that if code was already hosted to control system, you should trust it as workable at least. My question is, maybe I'm just too paranoiac and practice of reviewing each others code is good?

P.S: We're team of only three developers, and I fear that if there will be more of us, colleague just won't have time to review all the the code we'll write.

答:
During 6-7 months I was doing the same. Not to spy, but to control the quality. Every single line of the code for an actively developed application, committed to the central repository, 2 main languages, a few another languages, huge makefiles for 4 platforms.

It is very bad practice. Some day I found out that I cannot capture everything due to the robustness. The another argument against this is the subjectivity - everybody may get wrong.

It is better when developers review each other's codes and there is someone experienced to make final decisions and define directions.

ContentLicense: CC BY-SA 2.5


问:
Why don't languages include implication as a logical operator?
It might be a strange question, but why there is no implication as a logical operator in many languages (Java, C, C++, Python Haskell - although as last one have user defined operators its trivial to add it)? I find logical implication much clearer to write (particularly in asserts or assert-like expressions) then negation with or:</p>

```<code>encrypt(buf, key, mode, iv = null) {
    assert (mode != ECB --> iv != null);
    assert (mode == ECB || iv != null);
    assert (implies(mode != ECB, iv != null)); // User-defined function
}
</code>```

答:
Eiffel has an "implies" operator and it is very nice for writting pre- and postconditions.
It makes code more readable, unfortunately that was never a fundamental intension for C like language and too few people used eiffel so the beauty of "implies" as operator is not well known.</p>


答:
Sounds kind of crude, but just export your data as a Spreadsheet. And let them play with the spreadsheet on their desktops. You could go mad and have the web server upload a modified spreadsheet and apply any updates to the central DB.

Obviously this is very error prone and clunky, BUT, so is any other offline replication solution. At least the users will be aware of the obvious problems. Any other solution will have the same underlying problems but a slicker interface will give a false sense of security.

Title: Is there a way to develop desktop software using PHP?

Body:
I have to develop a real estate marketing CRM software for my client - where the application is installed on desktop but can also be accessed from web.

2 reasons why they want the application to run from desktop :

So that it can work with/without internet connection

They don't want their complete data to be online

They want to access few of the data like property listing & inquiries (managed from desktop application) from their website through secure login & password.

The data that is entered in desktop application should be automatically synchronized with the website application. I was wondering if there is a way to develop this kind of software using PHP & MySQL.  If yes, it will be great if anyone can provide me the referral link.Else please suggest, which language should I use.


问:
Dependency injection: At what point am I allowed to create a new object?
I am refactoring a PHP application, and I am trying to do has much dependency injection (DI) as possible.

I feel like I've got a good grasp of how it works, and I can certainly see my classes becoming a lot leaner and more robust.

I'm refactoring so that I can inject a dependency rather than create a new object within the class, but at some point I am going to have to create some objects, that is, use the dreaded new keyword.

The problem I have now run into is at what point can I actually create new objects? It's looking like I'll end up at a top level class, creating loads of new objects as there is no where else to go. This feels wrong.

I've read some blogs that use factory classes to create all the objects, and then you inject the factory into other classes. You can then call the factory methods, and the factory creates the new object for you.

My concern with doing this is now my factory classes are going to be a new free-for-all! I guess this may be OK as they are factory classes, but are there some rules to stick to when using a factory pattern and DI, or am I going way off the mark here?

答:
After quite a bit of googling around for this, it seems like (as mentioned in a comment above) the top level class I was talking about is called the Composition Root.

It does indeed seem to be the accepted solution to add the creation of all objects within this Composition Root (or referencing an IoC container from here).

My original concern with this was that this top level class would end up being a bit of a mess. This is true to some extent, but the pros out weigh the cons. For example I can see the readability, testability and maintainability of all my other classes has improved.

The top level class may be a bit messy, littered with new and set_property() but I have to say I actually prefer having all this code in one place, rather than scattered about all over the other classes

Another useful page discussing performance hits of this method here


答:
It would be healthy if the entire team does code reviews instead of one person. Ideally everyone would invite someone to review their code after completion. It's helpful to keep it informal (keep managers away) and let the reviewer talk you through his/her findings.
Ideally the reviewer only gives feedback and doesn't do code changes, of course you could pair on it a little.

It really helps to have coding standards to avoid review discussions being about white space and code style constantly. Having some static code analysis on a build machine can be helpful in keeping some discussions out also.

About the time aspect, the theory is that it will save you time. The later faults are found the more expensive they get, fail fast principle. Peer code review can catch quite a bit of problems.

Title: Should my colleagues review each others code from source control system?

Body:
So that's my story: one of my colleagues uses to review all the code, hosted to revision system. I'm not speaking about adequate review of changes in parts that he belongs to. He watches the code file to file, line to line. Every new file and every modified. I feel just like being spied on!

My guess is that if code was already hosted to control system, you should trust it as workable at least. My question is, maybe I'm just too paranoiac and practice of reviewing each others code is good?

P.S: We're team of only three developers, and I fear that if there will be more of us, colleague just won't have time to review all the the code we'll write.


问:
Unit-testing code that relies on untestable 3rd party code
Sometimes, especially when working with third party code, I write unit-test specific code in my production code. This happens when third party code uses singletons, relies on constants, accesses the file-system/a resource I don't want to access in a test situation, or overuses inheritance. The form my unit-test specific code takes is usually the following:

```<code>if (accessing or importing a certain resource fails)
    I assume this is a test case and load a mock object
</code>```

Is this poor form, and if it is, what is normally done when writing tests for code that uses untestable third party code?

答:
I normally add a layer of abstraction for a third party component.

Say I have a static class called User:

```<code>public static class User
{
   public static void Login(string username, string password)
   {
      // Logic
   }
}
</code>```

Imagine that User is a third party component for authentication.

I would then create an interface that would represent behaviour of my static class:

```<code>public interface IUser
{
   void Login(string username, string password);
}
</code>```

I would then create a default implementation that would talk to the static class:

```<code>public class UserDefault: IUser
{
   public void Login(string username, string password)
   {
       User.Login(username, password);
   }
}
</code>```

User is a third party component and I don't need to unit test its logic. What I might want to do in my unit test is verify that I've called User.Login("admin","Foo") only once.

In my unit test I can now create a mock object based on IUser and set expectations on that mock.

Body:
I normally add a layer of abstraction for a third party component.

Say I have a static class called User:

public static class User
{
   public static void Login(string username, string password)
   {
      // Logic
   }
}

Imagine that User is a third party component for authentication.

I would then create an interface that would represent behaviour of my static class:

public interface IUser
{
   void Login(string username, string password);
}

I would then create a default implementation that would talk to the static class:

public class UserDefault: IUser
{
   public void Login(string username, string password)
   {
       User.Login(username, password);
   }
}

User is a third party component and I don't need to unit test its logic. What I might want to do in my unit test is verify that I've called User.Login("admin","Foo") only once.

In my unit test I can now create a mock object based on IUser and set expectations on that mock.


问:
Why do we use to talk about addresses and memory of variable in C?
Why do we use to talk about addresses and memory of variable in C, where in other languages (like in Java, .Net etc) we do not talk about variable address and memory in a program, we will directly use the variables.

But in C Language we are listening the word address and memory.

How to explain this?

I hope C is high level language designed over the assembly language. So C is a thin layer over assembly language (in assembly language we will use memory locations to store a variable and track a variable). But in other languages these addresses and memory related things are wrapped in that specific language, so that we will not listen these words.

答:
Contrary to what anyone would say, knowing how memory works is important to know for any language, regardless of whether or not a specific language requires you to know it.  For low level languages like C, memory addresses are very important to know because dedicating space to arrays or complex data structures requires a physical act of asking the operating system for a memory space of the appropriate size and you, the programmer, must be able to know how many bytes are needed.  C offers helpful methods in this regard such as sizeof, but it doesn't pretend to hide it from you.

C++ only recently has moved towards removal of responsibility for programmers to free up memory allocated by having smart pointers.  C# and Java do a fairly good of hiding it, but they are still there.  For example in Java, if you compare two objects with ==, you are comparing their pointers.  You may not know the pointer values, but you must understand that if two objects return true using == operator, then they share the same space in memory.  If you did not understand this concept, you might do things like comparing Strings with ==, which may give you what you expect but maybe not.  Since "mickey mouse" == "mickey mouse" may or may not share the same memory address depending on how it is implemented in the virtual machine, Java programmers should never perform such checks using ==, but rather with .equals() instead, unless of course actually checking if they share the same memory is what you want.

Of course this is just one example.  With increases in memory and advances in technology, memory management is going to become less important with time.  However I assure you that the one day that your program is consuming as much memory as possible and your boss is bearing down on you to fix it, how memory is managed becomes very relevant very fast.  :)


问:
Building a regex builder
I am a beginner in programming in general and web development in particular. I am especially bad at regular expressions. Recently I was involved in building a couple of cPanel plugins(Perl-CGI) and that's when I realized how bad I am in regex. As a result, I have decided to build an online regex builder - this will help me to learn regex and help other struggling with regex.

I have checked out GSkinner, Rubular and a couple of others like regexpal. It seemed to be a little difficult to use, hence i thought of writing another one.

I do not know which tool is best suited for the job. should I write it in Perl or Python? My skill level is between beginner and intermediate in both those languages. What would be a good starting point - building it for the CLI or for the browser?

I plan to get a string as an input, ask if the user want to search or search and replace, enter the search string (and the replace string where applicable) and then generate a regex. Would this be the right way to go?

答:
Let me give you some advice.  When you're trying to learn a new language or library, it is an excellent idea to try making programs using that language or library, however learn one at a time.  If you are new to Python, Perl, web development, and regular expressions and you want to make a program using all of these technologies, you're going to have a bad time.

Start with learning Perl or Python (not both).  Once you feel fairly confident, you can add regular expressions into the mix.  Write a program which, given a pattern, it will search for that pattern in the file you provide.

Once you have these down should you write a simple html containing a form which when given a name, will take you another page in which it is written "Hello, <name>!"

And finally, once you understand these should you attempt web development.  That is a whole new ball game, and even if you are familiar with the technologies surrounding it, there are many new concepts to learn that it is still quite difficult.

I'm not familiar with web development in Perl or Python, so I don't know which libraries to tell you to learn.  However if you decided to learn Java, I could point you to a few helpful libraries.

Hope that helps!

Title: Building a regex builder


问:
Data structure supporting the following operations
I'm looking for a data structure for working with a set of data which is most efficient to do the following :

Check whether an item has been categorized or not. (The categorized and uncategorized set are disjoint sets).

Get the category of an item.

Get all the items in a particular category.

Get all the uncategorized items.

Remove a particular item from the data set.

I was thinking of having a Dictionary<String, Set<String>> to hold all the items in a given category, but that doesn't solve 2.

答:
You tried to model “Category has-many Item”. However, your requirements state that the relationship is bidirectional. I would therefore start with “Item has-one-or-none Category”. Requirements 1,2,5 can be fulfilled with the following design:

enum Category { FOO, BAR }

class Item {
  private Category category;

  // Req 1
  public boolean  isCategorized()           { return category != null; }
  // Req 2
  public Category getCategory()             { return category; }
  // Req 5
  public void     removeCategory()          { category = null; }
}
```

<p>This representation of categories is not sufficient, because requirements 3 and 4 are not fulfilled. For that, we need a reference back from each Category to each Item.</p>

<pre class="lang-java prettyprint-override"><code>enum Category {
  NONE, FOO, BAR;

  private Set<Item> items = new HashSet<Item>();

  // Reqs 3, 4
  public Iterable<Item> items() { return items; }

  // only to be called by Item
  boolean add   (Item item) { return items.add(item);    }
  boolean remove(Item item) { return items.remove(item); }
}

class Item {
  private Category category;

  public Item(Category cat) { setCategory(cat != null ? cat : Category.NONE); }

  // Req 1
  public boolean isCategorized() { return !category.equals(Category.NONE); }
  // Req 2
  public Category getCategory()  { return category; }
  // Req 5
  public void removeCategory() {
    setCategory(Category.EMPTY)
  }

  private void setCategory(Category cat) {
    if (category != null && !category.remove(this)) throw SomeException ...;
    if (!cat.add(this)) throw SomeException ...;
    category = cat;
  }
}
</code>```

Notice that Item is solely responsible for maintaining referential integrity. Because every Item has a non-null category where it is registered, we can obtain all “uncategorized” items via Category.NONE.items().

Body:
You tried to model “Category has-many Item”. However, your requirements state that the relationship is bidirectional. I would therefore start with “Item has-one-or-none Category”. Requirements 1,2,5 can be fulfilled with the following design:

enum Category { FOO, BAR }

class Item {
  private Category category;

  // Req 1
  public boolean  isCategorized()           { return category != null; }
  // Req 2
  public Category getCategory()             { return category; }
  // Req 5
  public void     removeCategory()          { category = null; }
}

This representation of categories is not sufficient, because requirements 3 and 4 are not fulfilled. For that, we need a reference back from each Category to each Item.

enum Category {
  NONE, FOO, BAR;

  private Set<Item> items = new HashSet<Item>();

  // Reqs 3, 4
  public Iterable<Item> items() { return items; }

  // only to be called by Item
  boolean add   (Item item) { return items.add(item);    }
  boolean remove(Item item) { return items.remove(item); }
}

class Item {
  private Category category;

  public Item(Category cat) { setCategory(cat != null ? cat : Category.NONE); }

  // Req 1
  public boolean isCategorized() { return !category.equals(Category.NONE); }
  // Req 2
  public Category getCategory()  { return category; }
  // Req 5
  public void removeCategory() {
    setCategory(Category.EMPTY)
  }

  private void setCategory(Category cat) {
    if (category != null && !category.remove(this)) throw SomeException ...;
    if (!cat.add(this)) throw SomeException ...;
    category = cat;
  }
}

Notice that Item is solely responsible for maintaining referential integrity. Because every Item has a non-null category where it is registered, we can obtain all “uncategorized” items via Category.NONE.items().


问:
Making a project open source on behalf of my organization
I am working on a tool which has been developed  for the use in my organization. Recently the management decided to make this open source. This will be the first open source contribution from my company and by me .

How can I make a project open source which will also show that this is from this organization?
Is just naming it as orgName_toolName sufficient or is there any other practice that is followed?

I am planning to make this available in Github.

答:
To release a project under an open-source license, you should take these steps:

Select an open source license that has acceptable terms for your organisation. You can find a list of open source licenses at http://opensource.org/licenses

Make sure that each file of the project has the appropriate copyright notice for the license you selected and that your organisation is indicated as the copyright holder.

Add any additional copyright related files, as required by the selected license, to your project

Publish the project on the internet, using a service of your choice. Github is a good one.


问:
Best algorithm/practice when creating a search mechanism for your database?
I have been designing a database where it is very important to provide users with a good search mechanism. So I was wondering what some of the best practices are for using keywords to search over multiple database tables and return the relevent records?

Some other things I am curious about:

The users location, if they provide an address

The speed of the algorithm

Additional Information:
I am using C# and LINQ-To-SQL.

答:
To get a better search, the following solutions can be implemented :

Make proper indexing of the column depending upon the search
conditions. Also keep in mind that the number of indexes must be
optimum, other wise it will overburden the database.

Define the primary keys for the column in the table.

If the search is too frequent then try to define the full text search option at the time of creating the database.


问:
PHP - Internal APIs/Libraries - What makes sense?
I've been having a discussion lately with some colleagues about the best way to approach a new project, and thought it'd be interesting to get some external thoughts thrown into the mix.

Basically, we're redeveloping a fairly large site (written in PHP) and have differing opinions on how the platform should be setup.

Requirements:

The platform will need to support multiple internal websites, as well as external (non-PHP) projects which at the moment consist of a mobile app and a toolbar. We have no plans/need in the foreseeable future to open up an API externally (for use in products other than our own).

My opinion:

We should have a library of well documented native model classes which can be shared between projects. These models will represent everything in our database and can take advantage of object orientated features such as inheritance, traits, magic methods, etc. etc. As well as employing ORM.

We can then add an API layer on top of these models which can basically accept requests and route them to the appropriate methods, translating the response so that it can be used platform independently. This routing for each method can be setup as and when it's required.

Their opinion:

We should have a single HTTP API which is used by all projects (internal PHP ones or otherwise).

My thoughts:

To me, there are a number of issues with using the sole HTTP API approach:

It will be very expensive performance wise. One page request will result in several additional http requests (which although local, are still ones that Apache will need to handle).

You'll lose all of the best features PHP has for OO development. From simple inheritance, to employing the likes of ORM which can save you writing a lot of code.

For internal projects, the actual process makes me cringe. To get a users name, for example, a request would go out of our box, over the LAN, back in, then run through a script which calls a method, JSON encodes the output and feeds that back. That would then need to be JSON decoded, and be presented as an array ready to use.

Working with arrays, as appose to objects, makes me sad in a modern PHP framework.

Their thoughts (and my responses):

Having one method of doing thing keeps things simple. - You'd only do things differently if you were using a different language anyway.

It will become robust. - Seeing as the API will run off the library of models, I think my option would be just as robust.

What do you think?

I'd be really interested to hear the thoughts of others on this, especially as opinions on both sides are not founded on any past experience.

答:
It will be very expensive performance wise. One page request will
  result in several additional http requests (which although local, are
  still ones that Apache will need to handle).

For internal calls, I agree, but not all APIs are RESTful, and not all do simple CRUD work (though that's the most common use-case for them).

You'll lose all of the best features PHP has for OO development. From
  simple inheritance, to employing the likes of ORM which can save you
  writing a lot of code.

Why? You can still use all of those things in an API. Where do you think the API server gets its data? An API doesn't necessarily access a database directly. It almost sounds as if you're only looking at this from the API consumer's point of view. Even that's flawed, really, because what the consumer gets can be one or more objects, too.

In an MVC architecture, an API isn't much different than any other MVC application. You have your views - the JSON response. You have your Controllers, and your Models. You get all of the same benefits of OOP available to you. The only major difference is how you're presenting the data (and possibly, how much data you're presenting at a time).

For internal projects, the actual process makes me cringe. To get a
  users name, for example, a request would go out of our box, over the
  LAN, back in, then run through a script which calls a method, JSON
  encodes the output and feeds that back. That would then need to be
  JSON decoded, and be presented as an array ready to use.

When communicating between languages, you have to convert to something that everything else understands. In most modern software systems, this is JSON. When communicating between applications of the same language, then you have a choice of either libraries or again communicating in JSON.

Working with arrays, as appose to objects, makes me sad in a modern
  PHP framework.

Who says you have to work with arrays with PHP's JSON methods? json_decode converts to an object by default (if you want an array, you have to set the assoc flag), and if you don't have a framework that already does it, you can write a helper function "to_json" function that converts a PHP object to an associative array. Or, if you're using 5.4 or greater, you can implement JsonSerializable to convert the object to be encoded.

You mentioned that one of your plans was to write a mobile application and a toolbar that will access this new system. If you don't have an API, then how do you plan to communicate with those offsite applications? You don't want either of those interfaces to store everything and do some of the really heavy lifting of your application, so at some point, you're going to need to have an API anyway.

As for your internal applications, it largely depends on the exact implementations of what you already have. If you're dealing with a number of different languages, then going your route means you have to maintain that many different code bases for the same thing. Whereas, if you go the API route for them, too, you have a single codebase to maintain, at the cost of having to connect to it as though they were external entities (which can be very small, if you build it right; think about how many APIs you likely already use, and how seamless most of them are). Keep in mind, too, that the API route allows you to move those other applications off-site should the need ever arise. Going the library route likely means a major code change is in store if you need to move it offsite.


问:
Are trivial protected getters blatant overkill?
Something I really have not thought about before (AS3 syntax):

```<code>private var m_obj:Object;
protected function get obj():Object
{
    return m_obj;
}

private var m_str:String;
protected function get str():String
{
    return m_str;
}
</code>```

At least subclasses won't be able to set m_obj or m_str (though they could still modify m_obj).

My question: Is this just blatant overkill?

This Programmer's question:
When or why should one use getters/setters for class properties instead of simply making them public properties?
has been suggested as a duplicate.

That question is different because it only addresses public vs. private properties and whether a property should be wrapped with getters & setters.  For my question, I'm focusing on protected variables and how inheriting classes would interact with those variables.

So the alternative implementation would be:

```<code>protected var m_obj:Object; //more accessible than a private variable with a protected getter
protected var m_str:String; //more accessible than a private variable with a protected getter
</code>```

My question is similar because I am talking about using trivial protected getters to block subclasses from writing to the variables, but to allow them all other access.

In languages like AS3, this will even allow them to make any changes to mutable object variables, as long as the references themselves are not modified.

答:
No matter if you use getters or field access, any experienced reviewer will find out the issue in your design and complain that your objects expose data instead of behavior.

Note that appealing to "protected" won't help, because the purpose of inheritance is to allow subclasses adjust / tune behavior of the parent (LSP), not to justify indiscriminate messing with parent data. As Bertrand Meyer puts it,

Neither the Open-Closed principle nor redefinition in inheritance is a way to address design flaws... (The only potential exception for this rule is the case of flawed software which you are not at liberty to modify.)

"Getters are evil" reasoning applies irrespectively on whether you spell get explicitly or mask it behind the field access.

see this article or this article by Alan Holub...

You shouldn't use accessor methods (getters and setters) unless absolutely necessary because these methods expose information about how a class is implemented and as a consequence make your code harder to maintain. Sometimes get/set methods are unavoidable, but an experienced OO designer could probably eliminate 99 percent of the accessors currently in your code without much difficulty.

Getter/setter methods often make their way in code because the coder was thinking procedurally. The best way to break out of that procedural mindset is to think in terms of a conversation between objects that have well-defined responsibilities...

If you are seriously concerned about the issue, first thing to consider is redesign of the code to get rid of both getters and non-private field access, instead of playing fruitless mind games picking which way is least inappropriate.

Worth stressing once again, hiding troublesome design behind "protected" smokescreen won't make the problem go away - inheritance does not justify tricks like that. Paraphrasing your question, strive to design things in a way that avoids having inheriting classes interact with those variables at all - neither via getters nor via field access. Tell, don't ask:

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.

Spending time and effort on deciding which way to prefer to get information, against classical principle recommending to avoid this altogether, now that sounds like a blatant overkill to me.


问:
Compatibility of Enum Vs. string constants
I was recently told that using Enum:

```<code>public enum TaskEndState { Error, Completed, Running }
</code>```

may have compatibility/serialization issues, and thus sometimes it's better to use const string:

```<code>public const string TASK_END_STATE = "END_STATE";
public const string TASK_END_STATE_ERROR = "TASK_END_STATE_ERROR";
public const string TASK_END_STATE_COMPLETE = "TASK_END_STATE_COMPLETE";
public const string TASK_END_STATE_RUNNING = "TASK_END_STATE_RUNNING";
</code>```

Can you find practical use case where it may happen, is there any guidelines where Enum's should be avoided?

Edit:
My production environment has multiple WFC services (different versions of the same product). A later version may/or may not include some new properties as Task end state (this is just an example). If we try to deserialize a new Enum value in an older version of a specific service, it may not work.

答:
For compatibility management, enum vs string is a red herring -- either your app has some understanding of "data document" schema version or not. If it does, then this is a rather mundane implementation detail. If you don't you've got the same problem either way.

How I'd handle this with WCF is make the public-facing layer a thin wrapper that is feeding data documents with some notation of version into internals that can handle it properly. Loads of ways to get to "handle it properly" and alot of that depends on specifics of your app so I can't give an educated answer to that question here.


问:
How can I tell if I am overusing multi-threading?
I currently feel like I am over-using multi-threading.

I have 3 types of data, A, B and C.

Each A can be converted to multiple Bs and each B can be converted to multiple Cs.

I am only interested in treating Cs.

I could write this fairly easily with a couple of conversion functions. But I caught myself implementing it with threads, three queues (queue_a, queue_b and queue_c). There are two threads doing the different conversions, and one worker:

ConverterA reads from queue_a and writes to queue_b

ConverterB reads from queue_b and writes to queue_c

Worker handles each element from queue_c

The conversions are fairly mundane, and I don't know if this model is too convoluted. But it seems extremely robust to me. Each "converter" can start working even before data has arrived on the queues, and at any time in the code I can just "submit" new As or Bs and it will trigger the conversion pipeline which in turn will trigger a job by the worker thread.

Even the resulting code looks simpler. But I still am unsure if I am abusing threads for something simple.

答:
It is almost always simpler to think sequentially, and then later modify that logic to work better using threads.  And, as the expression goes, "If it ain't broken, don't fix it."  Most programmers don't use threads simply because there is no need to use them.

If you feel more comfortable using them, more power to you.  However, know that if threads do not offer a speed boost by eliminating bottlenecks, they are almost certainly slowing down your program.

Also consider that systems which dedicate only one CPU to a process will simulate multiple threads by one single thread in order to save resources (this does not happen often with modern computers, though smart phone applications are still very much subjected to this abuse).  In this case, even if you're eliminating bottlenecks through the use of threads, it will actually be slower than if you didn't use threads at all.

And, perhaps the most subtle reason to use caution to use threads, but certainly not the least important, threads have a tendency to do what you don't expect.  Yes, if you're taking precautions, you should be okay.  Yes, if your threads don't write to variables shared between threads, you should be okay.  That said, thread-related bugs are very hard to find.  Since I'm of the idea that a programmer cannot ever completely eliminate the possibility to create bugs in code and therefore a programmer should take measures to protect against possible bugs rather than focus on completely eliminating them, you should definitely apply this idea to hard-to-find thread bugs as well.  In other words, know that despite your very best efforts, using threads in code will almost certainly create some very serious bugs sooner or later which you wouldn't have otherwise without using threads.

So should you use threads anyway?  Well, a healthy knowledge of threads is certainly not a bad thing, especially if you become good at it.  However, the movement of late has been towards single-threaded languages such as node.js.  One of the main advantages of having a single thread is that it is easy to scale and certain optimizations can be made if you know that the instructions are expected to be run sequentially (even if optimizations may mean that instructions which can be run in parallel can be run asynchronously).

That said, I say do what is most comfortable for you.  In my experience, writing a program that you understand has higher priority than making it work faster.  Just be sure to use threads when you think it helps you write the program, and not because you want it to work faster, since you shouldn't be worrying so much about performance as you are writing the program (optimization is important, but it can also wait).


问:
Why "OOP" and not simply "Object Programming"?
Why do we say "Object-oriented programming" and not simply "Object programming"? Why do we speak of orientation in just this case, and not "Functionally-oriented programming" and so?</p>

答:
Because Alan Kay said so.

More specifically, there were languages before Smalltalk that had objects or object-like structures but Smalltalk was the first language designed specifically to use objects as its primary computation method.

This is probably a good place to comment on the difference between what we thought of as OOP-style and the superficial encapsulation called “abstact data types” that was just starting to be investigated in academic circles. Our early “LISP-pair” definition is an example of an abstract data type because it preserves the “field access” and “field rebinding” that is the hallmark of a data structure. Considerable work in the 60s was concerned with generalizing such strcutures [DSP *]. The “official” computer science world started to regard Simula as a possible vehicle for defining abstract data types (even by one of its inventors [Dahl 1970]), and it formed much of the later backbone of ADA. This led to the ubiquitous stack data-type example in hundreds of papers. To put it mildly, we were quite amazed at this, since to us, what Simula had whispered was something much stringer than simply reimplementing a weak and ad hoc idea. What I got from Simula was that you could now replace bindings and assignment with goals. The last thing you wanted any programmer to do is mess with internal state even if presented figuratively. Instead, the objects should be presented as site of higher level behaviors more appropriate for use as dynamic components.

The most telling part of this passage is the idea of a "goal". Orientation implies a goal thus, Object-Oriented Programming rather than Object Programming. He also mentions Problem-Oriented and Expression-Oriented programming in passing. I suspect it is more than OOP got buzzworded and Function-Oriented didn't.


答:
Functional is an adjective, we don't say Function Programming. But there isn't a nice corresponding word for Object** so we use Object Oriented to form an adjective.

Also, functionally-oriented programming is ill-formed, you'd want Function Oriented Programming, which works, but why bother with such verbosity when we already have "functional".

** Objectionable and Objective don't really work.

Title: Why "OOP" and not simply "Object Programming"?

Body: Why do we say "Object-oriented programming" and not simply "Object programming"? Why do we speak of orientation in just this case, and not "Functionally-oriented programming" and so?</p>


答:
There is no right answer for this question.  It boils down to how explicit you want the contract to be.

On one hand, you could send this data simply as an xsd:string element named TaskEndState.  Here, the contract take any string in the message.  Validation will have to be performed in code to verify the string sent in the message matches a known value in the code.  New codes can be added without changing the contract.  This is a less explicit contract.  This type of contract is more flexible to change, but validation is no longer being performed exclusively at the schema level as some validation will have to occur inside the code.

On the other hand, you could define a restriction (enumeration) on the xsd:string element that will only take in values defined.  Validation will occur at the schema level only.  New codes can be added, but that changes the contract.  This is the explicit contract.  This type of contract is less flexible to change, but validation is still performed in one place, at the schema level.  In some cases this is desireable because schema validation is performed in centralized locations and the general consensus is that message validation is seprated from actual message processing.  But, since the contract has changed, callers will have to re-test and validate that the additional restrictions did not break anything.

In general, I usually go with enums because I like my contracts to be explicit as possible.  But, there are no absolutes.

In your case, if new strings are not added that often, I'd go with the enum.  If TaskEndState data is very volatile (changes constantly) I would go with the generic string.

There are some good articles online one how to handle the restrictions.  Here is one such link:

http://www.xml.com/pub/a/2003/02/05/wxs-enum.html?page=1

Title: Compatibility of Enum Vs. string constants

Body:
I was recently told that using Enum:

```<code>public enum TaskEndState { Error, Completed, Running }
</code>```

may have compatibility/serialization issues, and thus sometimes it's better to use const string:

```<code>public const string TASK_END_STATE = "END_STATE";
public const string TASK_END_STATE_ERROR = "TASK_END_STATE_ERROR";
public const string TASK_END_STATE_COMPLETE = "TASK_END_STATE_COMPLETE";
public const string TASK_END_STATE_RUNNING = "TASK_END_STATE_RUNNING";
</code>```

Can you find practical use case where it may happen, is there any guidelines where Enum's should be avoided?

Edit:
My production environment has multiple WFC services (different versions of the same product). A later version may/or may not include some new properties as Task end state (this is just an example). If we try to deserialize a new Enum value in an older version of a specific service, it may not work.


答:
You don't say how exactly are you serializing the Enum, which is important here. I'm going to assume that you serialize it as the underlying integral value. In that case, your current code indeed has a versioning issue, if you add a new value into the middle of the Enum.

For example, in your current code, Error is 0, Completed is 1 and Running is 2. Now imagine you changed the code to:

```<code>public enum TaskEndState { Error, Timeout, Completed, Running }
</code>```

Suddenly, what you saved as Running (old 2) will be read as Completed (new 2), which is not correct.

The best way to deal with this is to explicitly specify the numeric values for each enum member and never change them. You can add new values laster, but they have to have a new integer value. For example, the original:

```<code>public enum TaskEndState { Error = 0, Completed = 1, Running = 2 }
</code>```

And the modified version:

```<code>public enum TaskEndState { Error = 0, Timeout = 3, Completed = 1, Running = 2 }
</code>```

Body:
You don't say how exactly are you serializing the Enum, which is important here. I'm going to assume that you serialize it as the underlying integral value. In that case, your current code indeed has a versioning issue, if you add a new value into the middle of the Enum.

For example, in your current code, Error is 0, Completed is 1 and Running is 2. Now imagine you changed the code to:

public enum TaskEndState { Error, Timeout, Completed, Running }

Suddenly, what you saved as Running (old 2) will be read as Completed (new 2), which is not correct.

The best way to deal with this is to explicitly specify the numeric values for each enum member and never change them. You can add new values laster, but they have to have a new integer value. For example, the original:

public enum TaskEndState { Error = 0, Completed = 1, Running = 2 }

And the modified version:

public enum TaskEndState { Error = 0, Timeout = 3, Completed = 1, Running = 2 }


问:
Should I fork for a major re-write that uses a small amount of the original code?
I'm writing a library. It's a completely rewritten version of another one, to suit my needs (PCL compatibility, mainly). However, the API will be completely rewritten, as I'll need to change a lot of stuff around for PCL compliance. Also, as it is a rewrite, I won't be able to just start from the library and just change it bit by bit, as I typically see with forks. I tried that, but it just didn't work.

So what should I do? Should I fork here or should I make a new library?

答:
"It's a completely rewritten version of another one [...]"

Strictly speaking, something completely rewritten isn't considered a version; at least not in computing where we take "version" somewhat formally. For example, it is misleading an incorrect to call Linux a "version of Unix". The word widely accepted for this is "clone".

Something rewritten also cannot possibly be a fork, even if it resembles the original to the point of being a clone (such as by having similar or identical interfaces).

Since you've tried modifying the original and it didn't work, and then embarked on a rewrite, that bridge has already been burned: the rewrite isn't a version, and so it cannot be considered a fork. It isn't even a clone, because the interfaces are different!

It's a new library which covers a similar area of functionality as the old.

If the library internals are complicated and worth reusing, and the new interfaces can be easily adapted, to use the existing internals, then a case can be made for extending the library: keep the old interfaces in place (perhaps providing a way to remove them at compile time to save space). If that approach was feasible for this library, then you wouldn't be doing a complete rewrite, though.


问:
How can architects work with self-organizing Scrum teams?
An organization with a number of agile Scrum teams also has a small group of people appointed as "enterprise architects". The EA group acts as control and gatekeeper for quality and adherence to decisions. This leads to overlaps between the team decision and EA decisions.

For instance, the team might want to use library X or want to use REST instead of SOAP, but the EA does not approve of that.

Now, this can lead to frustration when team decisions are overruled. Taken far enough, it can potentially lead to a situation where the EA people "grabs" all power and the team ends up feeling demotivated and not very agile at all.

The Scrum guides has this to say about it:

Self-organizing: No one (not even the Scrum Master) tells the
  Development Team  how to turn Product Backlog into Increments of
  potentially releasable functionality.

Is that reasonable? Should the EA team be disbanded? Should the teams refuse or simply comply?

答:
Martin, I think you may have a misconception about how a self-organizing team functions in its environment.

You quoted the Scrum Guide: "No one (not even the Scrum Master) tells the Development Team how to turn Product Backlog into Increments of potentially releasable functionality."

This is not a license for the Scrum team to do whatever it wants (so long as it delivers) without regard to the technology and business needs of the company as a whole, and the needs of the other teams.

Sure stakeholders can abuse their influence. That is one of the challenges of collaboration, and it's certainly not limited to the EA. But collaboration doesn't end at the boundary of the team.


问:
What layer to introduce human readable error messages?
One of the things that I have never been happy with on any project I have worked on over the years and have really not been able to resolve myself is exactly at what tier in an application should human readable error information be retrieved for display to a user.

A common approach that has worked well has been to return strongly typed/concrete "result objects" from the methods on the public surface of the business tier/API. A method on the interface may be:

```<code>public ClearUserAccountsResult ClearUserAccounts(ClearUserAccountsParam param);
</code>```

And the result class implementation:

```<code>public class ClearUserAccountsResult : IResult
{
    public readonly List<Account> ClearedAccounts{get; set;}

    public readonly bool Success {get; set;}    // Implements IResult
    public readonly string Message{get; set;}   // Implements IResult, human readable

    // Constructor implemented here to set readonly properties...
}
</code>```

This works great when the API needs to be exposed over WCF as the result object can be serialized. Again this is only done on the public surface of the API/business tier. The error message can also be looked up from the database, which means it can be changed and localized.

However, it has always been suspect to me, this idea of returning human readable information from the business tier like this, partly because what constitutes the public surface of the API may change over time...and it may be the case that the API will need to be reused by other API components in the future that do not need the human readable string messages (and looking them up from a database would be an expensive waste).

I am thinking a better approach is to keep the business objects free from such result objects and keep them simple and then retrieve human readable error strings somewhere closer to the UI layer or only in the UI itself, but I have two problems here:

1) The UI may be a remote client (Winforms/WPF/Silverlight) or an ASP.NET web application hosted on another server. In these cases the UI will have to fetch the error strings from the server.

2) Often there are multiple legitimate modes of failure. If the business tier becomes so vague and generic in the way it returns errors there may not be enough information exposed publicly to tell what the error actually was: i.e: if a method has 3 modes of legitimate failure but returns a boolean to indicate failure, you cannot work out what the appropriate message to display to the user should be.

I have thought about using failure enums as a substitute, they can indicate a specific error that can be tested for and coded against. This is sometimes useful within the business tier itself as a way of passing via method returns the specifics of a failure rather than just a boolean, but it is not so good for serialization scenarios.

Is there a well worn pattern for this? What do people think?

Thanks.

答:
A common approach that has worked well has been to return strongly typed/concrete "result objects" from the methods on the public surface of the business tier/API.

That tightly couples your views to your data models. Causing the client to break when those objects are changed. You should treat your clients as an engine to render templates, and send only data for those templates to the client. That data should be as generic as possible to meet the needs of the templates.

This works great when the API needs to be exposed over WCF as the result object can be serialized.

Serialized yes, but think of it not as a response object but as data values for your view template. The view should be a logic-less rendering of that data. How logic-less the views are depends on how connected you want the clients to the backend, but the less logic the better.

1) The UI may be a remote client (Winforms/WPF/Silverlight) or an ASP.NET web application hosted on another server. In these cases the UI will have to fetch the error strings from the server.

I would send the message along with the response from the server to the client. Why send a response code and then have the client query what the code means? That is not the job of the client. The client should do as little work as possible to render the view for the user.

2) Often there are multiple legitimate modes of failure. If the business tier becomes so vague and generic in the way it returns errors there may not be enough information exposed publicly to tell what the error actually was: i.e: if a method has 3 modes of legitimate failure but returns a boolean to indicate failure, you cannot work out what the appropriate message to display to the user should be.

You are missing something here. There should be a middle piece between the data models and the client view. Often referred to as the controller. That middle piece will query the data models to do work, receive back a response code, take that code and look up a human readable message and then push that to the client for viewing.

Is there a well worn pattern for this?

It's called Model View Controller (MVC) pattern.

http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

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

There is also something called MVVM (Model View ViewModel).

http://en.wikipedia.org/wiki/Model_View_ViewModel

I've found that you sometimes have to implement MVC on the server, and MVVM on a client.


答:
C's original purpose was to implement an operating system (Unix);  part of an operating system's job is to manage memory resources, thus the language needed to expose memory addresses and operations on those addresses to the programmer.

The designers of Java and C# decided not to expose address types and operations to the programmer for a number of reasons: security, simpler memory model (at least from the programmers point of view), garbage collection, etc.  But note that plenty of older languages (Fortran, Cobol, old-school BASIC, etc.) don't expose addresses either, at least not directly.

And, to clear up a popular misconception, C is not merely a thin layer over assembly; it's every bit as high-level a language as Java, it just provides low-level abstractions.  Part of this is to satisfy the mandate that C be easy to implement.  Making the programmer have to deal with his or her own memory management simplifies the language quite a bit.  This is why C doesn't provide a set of standard container types, or a real string type that grows and shrinks as necessary.  By keeping the language and the toolkit simple, C compilers can target a wide variety of platforms that other languages don't.

Title: Why do we use to talk about addresses and memory of variable in C?

Body:
Why do we use to talk about addresses and memory of variable in C, where in other languages (like in Java, .Net etc) we do not talk about variable address and memory in a program, we will directly use the variables.

But in C Language we are listening the word address and memory.

How to explain this?

I hope C is high level language designed over the assembly language. So C is a thin layer over assembly language (in assembly language we will use memory locations to store a variable and track a variable). But in other languages these addresses and memory related things are wrapped in that specific language, so that we will not listen these words.


问:
Making Agile and DevOps methodology compatible with PCI requirements
Would like to hear from those working in a PCI compliance environment and is practicing agile development and devops methodology, how you maintain compliance with PCI requirements.

Specifically, what do you do to address:

separation of duties between development/test and production

alignment of continuous integration / deployment and change control

alignment of agile stories to requirement documentation

答:
Lay down some rules and make sure you document compliance with them.

For example:

Tests must be performed by someone other than the person who coded the solution.

User Acceptance Tests need to be performed by the customer (or a delagate).

Developers do not have access to the production environment.

An Operations person/group is responsible for deploying to the production environment.

When a sprint ends, all accepted code is versioned. The stories completed for that sprint are documented as being part of that version.
Generally, we have sprints deal with everything through user acceptance testing, and then authorize a deployment to Prod (or not) at the sprint review.  The Operations team should then be able to deploy the approved version.

You'll need several environments in order to handle this.  I prefer 5:

Dev

SIT (System and Integration Testing)

UAT (User Acceptance Testing)

Production

Prod Fix (for fixing urgent Production issues)

User Stories are the general requirements.  If you have more detailed requirements, have a matrix indicating in which User Story the detailed requirement is addressed.


答:
I would suggest that you build a well defined API with clearly defined set of error results for each exposed method for the following concerns:

an API should not be designed around the consumer.  It should define clear behavior and clear failure codes.  Your caller could be a UI, a service or another API.  The caller should decide what to do about the failure and whether any presentation is even needed.

The consumer might need more or less "message" depending on its own scenario.  Pushing the presentation back to the consumer allows maximum flexibility in presentation.

Any localization or language concerns should be addressed by the consumer not the API.

Title: What layer to introduce human readable error messages?

Body:
One of the things that I have never been happy with on any project I have worked on over the years and have really not been able to resolve myself is exactly at what tier in an application should human readable error information be retrieved for display to a user.

A common approach that has worked well has been to return strongly typed/concrete "result objects" from the methods on the public surface of the business tier/API. A method on the interface may be:

```<code>public ClearUserAccountsResult ClearUserAccounts(ClearUserAccountsParam param);
</code>```

And the result class implementation:

```<code>public class ClearUserAccountsResult : IResult
{
    public readonly List<Account> ClearedAccounts{get; set;}

    public readonly bool Success {get; set;}    // Implements IResult
    public readonly string Message{get; set;}   // Implements IResult, human readable

    // Constructor implemented here to set readonly properties...
}
</code>```

This works great when the API needs to be exposed over WCF as the result object can be serialized. Again this is only done on the public surface of the API/business tier. The error message can also be looked up from the database, which means it can be changed and localized.

However, it has always been suspect to me, this idea of returning human readable information from the business tier like this, partly because what constitutes the public surface of the API may change over time...and it may be the case that the API will need to be reused by other API components in the future that do not need the human readable string messages (and looking them up from a database would be an expensive waste).

I am thinking a better approach is to keep the business objects free from such result objects and keep them simple and then retrieve human readable error strings somewhere closer to the UI layer or only in the UI itself, but I have two problems here:

1) The UI may be a remote client (Winforms/WPF/Silverlight) or an ASP.NET web application hosted on another server. In these cases the UI will have to fetch the error strings from the server.

2) Often there are multiple legitimate modes of failure. If the business tier becomes so vague and generic in the way it returns errors there may not be enough information exposed publicly to tell what the error actually was: i.e: if a method has 3 modes of legitimate failure but returns a boolean to indicate failure, you cannot work out what the appropriate message to display to the user should be.

I have thought about using failure enums as a substitute, they can indicate a specific error that can be tested for and coded against. This is sometimes useful within the business tier itself as a way of passing via method returns the specifics of a failure rather than just a boolean, but it is not so good for serialization scenarios.

Is there a well worn pattern for this? What do people think?

Thanks.


问:
Matching users based on a series of questions
I'm trying to figure out a way to match users based on specific personality traits. Each trait will have its own category.

I figure in my user table I'll add a column for each category:

```<code>id    name    cat1    cat2    cat3
1     Sean    ?       ?       ?
2     Other   ?       ?       ?
</code>```

Let's say I ask each user 3 questions in each category. For each question, you can answer one of the following: No, Maybe, Yes How would I calculate one number based off the answers in those 3 questions that would hold a value I can compare other users to?

I was thinking having some sort of weight. Like:

```<code>No    -> 0
Maybe -> 1
Yes   -> 2
</code>```

Then doing some sort of meaningful calculation. I want to end up with something like this so I can query the users and find who matches close:

```<code>id    name    cat1    cat2    cat3
1     Sean    4       5       1
2     Other   1       2       5
</code>```

In the situation above, the users don't really match. I'd want to match with someone with a +1 or -1 of my score in each category.

I'm not a math guy so I'm just looking for some ideas to get me started.

答:
I'd use Euclidean Distance, but that's just me.

If you had only 2 categories you could call them X and Y.  Then your problem would be simply a matter of computing the distance between two points.

If you had 3 categories, (X, Y, Z) then you'd need to calculate the distance in 3 dimensions.

According to Wikipedia the general formula is

A match is "close" if the distance between the two is small.

You should be able to compute distance as

```<code>dist = sqrt( (user1.cat1 - user2.cat1)^2 + (user1.cat2 - user2.cat2)^2 ...)
</code>```

Body:
I'd use Euclidean Distance, but that's just me.

If you had only 2 categories you could call them X and Y.  Then your problem would be simply a matter of computing the distance between two points.

If you had 3 categories, (X, Y, Z) then you'd need to calculate the distance in 3 dimensions.

According to Wikipedia the general formula is

A match is "close" if the distance between the two is small.

You should be able to compute distance as

dist = sqrt( (user1.cat1 - user2.cat1)^2 + (user1.cat2 - user2.cat2)^2 ...)


问:
Why does appending to a List in Scala have O(n) time complexity?
I just read that the execution time of the append operation for a List (:+) grows linearly with the size of the List.

Appending to a List seems like a pretty common operation. Why should the idiomatic way to do this be prepending the components and then reversing the list? It can't also be a design failure as implementation could be changed at any point.

From my point of view, both prepending and appending should be O(1).

Is there any legitimate reason for this?

答:
I'll expand my comment a bit. The List[T] data structure, from scala.collection.immutable is optimized to work the way an immutable list in a more purely functional programming language works. It has very fast prepend times, and it is assumed that you will be working on the head for almost all of your access.

Immutable lists get to have very fast prepend times due to the fact that they model their linked lists as a series of "cons cells". The cell defines a single value, and a pointer to the next cell (classic singly-linked-list style):

```<code>Cell [Value| -> Nil]
</code>```

When you prepend to a list, you're really just making a single new cell, with the rest of the existing list being pointed to:

```<code>Cell [NewValue| -> [Cell[Value| -> Nil]]
</code>```

Because the list is immutable, you're safe to do this without any actual copying. There's no danger of the old list changing and causing all the values in your new list to become invalid. However, you lose the ability to have a mutable pointer to the end of your list as a compromise.

This lends itself very well to recursively working on lists. Let's say you defined your own version of filter:

def deleteIf[T](list : List[T])(f : T => Boolean): List[T] = list match {
  case Nil => Nil
  case (x::xs) => f(x) match {
    case true => deleteIf(xs)(f)
    case false => x :: deleteIf(xs)(f)
  }
}
```

That's a recursive function that works from the head of the list exclusively, and takes advantage of pattern matching via the :: extractor. This is something you see a lot of in languages like Haskell.

If you really want fast appends, Scala provides a lot of mutable and immutable data structures to choose from. On the mutable side, you might look into ListBuffer. Alternatively, Vector from scala.collection.immutable has a fast append time.

ContentLicense: CC BY-SA 4.0

Body:
I'll expand my comment a bit. The List[T] data structure, from scala.collection.immutable is optimized to work the way an immutable list in a more purely functional programming language works. It has very fast prepend times, and it is assumed that you will be working on the head for almost all of your access.

Immutable lists get to have very fast prepend times due to the fact that they model their linked lists as a series of "cons cells". The cell defines a single value, and a pointer to the next cell (classic singly-linked-list style):

Cell [Value| -> Nil]

When you prepend to a list, you're really just making a single new cell, with the rest of the existing list being pointed to:

Cell [NewValue| -> [Cell[Value| -> Nil]]

Because the list is immutable, you're safe to do this without any actual copying. There's no danger of the old list changing and causing all the values in your new list to become invalid. However, you lose the ability to have a mutable pointer to the end of your list as a compromise.

This lends itself very well to recursively working on lists. Let's say you defined your own version of filter:

def deleteIf[T](list : List[T])(f : T => Boolean): List[T] = list match {
  case Nil => Nil
  case (x::xs) => f(x) match {
    case true => deleteIf(xs)(f)
    case false => x :: deleteIf(xs)(f)
  }
}

That's a recursive function that works from the head of the list exclusively, and takes advantage of pattern matching via the :: extractor. This is something you see a lot of in languages like Haskell.

If you really want fast appends, Scala provides a lot of mutable and immutable data structures to choose from. On the mutable side, you might look into ListBuffer. Alternatively, Vector from scala.collection.immutable has a fast append time.