答:
This is not a black-and-white question that could receive an answer such as "A is always better" or "Avoid B at all costs", but generally:

The preferred way is exceptions, not status results.

(And for the sake of consistency it is best to avoid converting between the two unless you have a good reason.  Which in this case, I don't see.)

The code fragments that you posted are top-level code.  When writing top-level code, (where it may make sense to try and catch exceptions,) the use of exceptions might seem cumbersome and unnecessarily verbose when compared to the use of status results.  However, you have to consider that top-level code is not the only code that makes up a non-trivial application; this InsertOperator() method may represent (or may be invoked by) a several-level-deep call tree, consisting of hundreds of lines of code, where each and every method invoked must return a status result, and each and every caller must be sure to check this status result and take appropriate action if not successful. Quite often programmers forget that stuff; that's when hard-to-find bugs happen.

With exceptions, code below the top level which does not have any need to deal with an exception does not have to contain a try-catch block, and if it needs to deal with exceptions only for the purpose of leaving things as it found them, it can simply use try-finally instead of try-catch.  This generally results in much simpler, much more structured, much more understandable, and much more maintainable code than the kind of spaghetti code that we used to write back in the days of result codes, before exceptions had been invented.

Of course, as always, there may be good enough reasons to choose result codes instead of exceptions.  As other answers have already indicated, if something is to be happening so often as to practically not be considered an "exceptional situation", then perhaps it should not be expressed as an exception, and the performance penalty associated with throwing an exception might be prohibitive.  But in your case, failing to add a "user" or an "operator" seems a severe enough and exceptional enough situation to warrant precisely that: an exception.

Title: Where to put try-catch statements


问:
C++ HTTP API Design
I have a massive library written in C++ that handles a lot of mathematical operations, using C++ makes it fast and in all honesty, I don't want to re-write the whole functionality.

I am thinking about opening this library up to other, web languages (Such as PHP) and will pass the data between the two using JSON.

The issue, I have not had much experience designing/developing an API in C++ and from thinking about the implementation I have come up with this:

The API can be accessed from a HTTP URL: http://localhost/api/ and pass in different commands into it. For example: getDeter .. Which I know how I will do this using PHP.

The problem that I am having difficult understanding is how will visiting http://localhost/api work in C++? Is there another approach to doing this:

Compiling the C++ into a output file main.out

Have a function in PHP that calls a command ./main.out [command] [arg]

Return the response

I did not want to do this approach as I don't think that it is very clean, but I can't seem to think of an alternative to solving this problem.

P.S. I don't want to really open up the core C++ code and make changes. I would like to do the following (In C++)

```<code>function calculateDeter(std::vector<double> input)
{
    // call library function
    // call another library function

    // return json data

}
</code>```

答:
The technique you are describing is (very roughly) similar to CGI, a way for web servers to call external code of any kind. PHP itself is usually run as a CGI application. If you were to implement it this way, a good place to start would be to look at the FCGI documentation. In short, you could use the FCGI library to write an interface for a web server to call your C++ code.

Another approach would be to embed an HTTP server directly into your application. This is a little simpler, since it removes the need for a separate web server, but leaves you to deal with issues like scalability and security that a full-fledged web server will include out the box. If you went down this route you might use a library like libevent.

ContentLicense: CC BY-SA 3.0

Title: C++ HTTP API Design


问:
Why didn't == operator string value comparison make it to Java?
Every competent Java programmer knows that you need to use String.equals() to compare a string, rather than == because == checks for reference equality.

When I'm dealing with strings, most of the time I'm checking for value equality rather than reference equality. It seems to me that it would be more intuitive if the language allowed string values to be compared by just using ==.

As a comparison, C#'s == operator checks for value equality for strings. And if you really needed to check for reference equality, you can use String.ReferenceEquals.

Another important point is that Strings are immutable, so there is no harm to be done by allowing this feature.

Is there any particular reason why this isn't implemented in Java?

答:
Consistency within the language. Having an operator that acts differently can be surprising to the programmer. Java doesn't allow users to overload operators - therefore reference equality is the only reasonable meaning for == between objects.

Within Java:

Between numeric types, == compares numeric equality

Between boolean types, == compares boolean equality

Between reference types, == compares reference equality

Use .equals(Object o) to compare values

That's it. Simple rule and simple to identify what you want. This is all covered in section 15.21 of the JLS.  It comprises three subsections that are easy to understand, implement, and reason about.

Once you allow overloading of ==, the exact behavior isn't something that you can look to the JLS and put your finger on a specific item and say "that's how it works," the code can become difficult to reason about.  The exact behavior of == may be surprising to a user.  Every time you see it, you have to go back and check to see what it actually means.

Since Java doesn't allow for overloading of operators, one needs a way to have a value equality test that you can override the base definition of. Thus, it was mandated by these design choices.  == in Java tests numeric for numeric types, boolean equality for boolean types, and reference equality for everything else (which can override .equals(Object o) to do whatever they want for value equality).

This is not an issue of "is there a use case for a particular consequence of this design decision" but rather "this is a design decision to facilitate these other things, this is a consequence of it."

String interning, is one such example of this. According to the JLS 3.10.5, all string literals are interned. Other strings are interned if one invokes .intern() on them. That "foo" == "foo" is true is a consequence of design decisions made to minimize the memory footprint taken up by String literals. Beyond that, String interning is something that is at the JVM level that has a little bit of exposure to the user, but in the overwhelming vast majority of cases, should not be something that concerns the programmer (and use cases for programmers wasn't something that was high on the list for the designers when considering this feature).

People will point out that + and += are overloaded for String. However, that is neither here nor there. It remains the case that if == has a value equality meaning for String (and only String), one would need a different method (that only exists in String) for reference equality. Furthermore, this would needlessly complicate methods that take Object and expect == to behave one way and .equals() to behave another requiring users to special case all those methods for String.

The addition of auto boxing/unboxing of primitive wrappers (e.g. java.lang.Integer, etc.) muddles things a bit because comparing an int with an Integer (or vice-versa) with == will indeed compare the integer values of each of those things, but if both variables are of type Integer then using == may give an unexpected answer where the integer values are equal but the references are different, yielding a false comparison.

The consistent contract for == on Objects is that it is reference equality only and that .equals(Object o) exists for all objects which should test for value equality. Complicating this complicates far too many things.

ContentLicense: CC BY-SA 4.0


问:
WCF service design
I am rather new to WCF (or rest, or Json for that matter) and I'd like to have some expert opinions on which methods to define.

Some short introduction to give an idea of what the webservice should expose:
I am building domotica software (software that can control a ZWave network) which has different interfaces (a GUI application, a web server for configuration, and tablets/phones to control the network).

The webservice is the central application that :
- has a controller that can interact with ZWave devices
- exposes a WCF Json service so that clients can query and control on the ZWave network

The easy methods on the WCF interface:

```<code>    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getnodes")]
    public List<Node> GetNodes()
    {
        // ... retrieve all nodes from ZWave Controller
    }

    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getnode/{id}")]
    public Node GetNode(uint id)
    {
        // ... retrieve specific node
    }
</code>```

What I was wondering, is how "specific" the API should be in terms of POST/PUT methods. Clients need to interact with nodes, like set the name, set the room where the node resides in, switch a node on/off, set a dim amount, etc, etc.

I defined one method as follows:

```<code>    [WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, UriTemplate = "setnodename")]
    public void SetNodeName(NodeNewName nodeNewName)
    {
        // .. sets the name of the node, as specified in the passed object
    }
</code>```

This works, however this does cause a lot of different methods AND specific classes (as I specified a short list above of the functionality which would demand for specic methods and classes for each of them).

Is that the way to go? Or should I have one method UpdateNode and a more generic class as parameter which only specifies the properties that need to be updated? Or is there some kind of a guideline that would help me define a solid design for my webservice?

I googled a lot on this topic, and I read some articles about WCF design guidelines, but not really something where they cover this part. (or I am not the best googler on this specific topic, which would make sense as I am new on WCF/REST/Json/etc).

Hope somebody can understand what I am looking for and can help me on my way.

Much appreciated!

答:
This is a tough question to answer definitively, because this space is still relatively young. When it all settles down, then we will know what the answer should have been. :)

Since the kinds of objects and their specific properties are potentially unbounded (depends on what comes to market), I would be tempted to treat each node as essentially a data bucket. The far extreme of this would be something like:

```<code>public void SetNodeProperty(string name, string value)

public void SetNodeProperties(Dictionary<string, string> properties)
</code>```

This really only works if you have no nested object properties (instead of node.Temperature.Minimum, you would need to do node.MinTemperature) and your property values are convertible from strings.

If you have some core data like Name, Room, etc. You can base your object around that, and use tricks to communicate the extra properties back to the server. JsonExtensionData is one way of doing that where any extra properties which are not direct properties on the class are put into a Dictionary<string, object> upon deserialization so you can access them.

```<code>public class Node
{
    public string Name {get;set;}
    ...
    [JsonExtensionData]
    public Dictionary<string, object> ExtraData {get;set;}
}

// API
public void UpdateNode(Node node)
</code>```

Another way would be to take advantage of polymorphism in your API (here is the WCF version) so that anything which implements INode will be deserialized to the proper concrete type on the server (provided the client can give you a type hint when they send the JSON data).

```<code>// something like this required for WCF polymorphic parameters
[ServiceKnownType("GetKnownTypesOfINode", typeof(MyHelperClass))]
public void UpdateNode(INode node)
// node could deserialize as ThermostatNode, LightSourceNode, etc.
//   but will be cast as INode
// client has to send $type property for JSON.NET to deserialize properly
//   the value for $type usually takes the form:
//   'My.Namespace.SubNamespace.Class, My.Assembly'
</code>```

Thirdly, you could deal with the JSON in a purely dynamic way. JSON.NET allows you to deserialize to a dynamic or ExpandoObject to interrogate the posted JSON body. This supports nested properties unlike the string dictionary. I'm pretty sure WCF does not support this since a central theme is providing an interface as a data contract. However, even in Web API, I would likely read the request body manually to avoid having to make a custom model binder or filter or whatever.

Title: WCF service design

Body:
This is a tough question to answer definitively, because this space is still relatively young. When it all settles down, then we will know what the answer should have been. :)

Since the kinds of objects and their specific properties are potentially unbounded (depends on what comes to market), I would be tempted to treat each node as essentially a data bucket. The far extreme of this would be something like:

public void SetNodeProperty(string name, string value)

public void SetNodeProperties(Dictionary<string, string> properties)

This really only works if you have no nested object properties (instead of node.Temperature.Minimum, you would need to do node.MinTemperature) and your property values are convertible from strings.

If you have some core data like Name, Room, etc. You can base your object around that, and use tricks to communicate the extra properties back to the server. JsonExtensionData is one way of doing that where any extra properties which are not direct properties on the class are put into a Dictionary<string, object> upon deserialization so you can access them.

public class Node
{
    public string Name {get;set;}
    ...
    [JsonExtensionData]
    public Dictionary<string, object> ExtraData {get;set;}
}

// API
public void UpdateNode(Node node)

Another way would be to take advantage of polymorphism in your API (here is the WCF version) so that anything which implements INode will be deserialized to the proper concrete type on the server (provided the client can give you a type hint when they send the JSON data).

// something like this required for WCF polymorphic parameters
[ServiceKnownType("GetKnownTypesOfINode", typeof(MyHelperClass))]
public void UpdateNode(INode node)
// node could deserialize as ThermostatNode, LightSourceNode, etc.
//   but will be cast as INode
// client has to send $type property for JSON.NET to deserialize properly
//   the value for $type usually takes the form:
//   'My.Namespace.SubNamespace.Class, My.Assembly'

Thirdly, you could deal with the JSON in a purely dynamic way. JSON.NET allows you to deserialize to a dynamic or ExpandoObject to interrogate the posted JSON body. This supports nested properties unlike the string dictionary. I'm pretty sure WCF does not support this since a central theme is providing an interface as a data contract. However, even in Web API, I would likely read the request body manually to avoid having to make a custom model binder or filter or whatever.


问:
Merging two applications into one
Background:
My bosses want to merge two application that have two separate purposes.

One being for monitoring of equipment and bandwidth for our internal
network operations.

The other is an application to view similar data just less granular
and with less detail. This second application has to also perform
tasks such as generating tokens or creating a splash page that is
meant for the client to use but is generally used by the customer
representatives in the company. It also is used by external clients of properties.

Does it make sense to merge the two applications? Why or why not. I can understand there is an inherent security flaw with introducing this type of architecture. But is it worth the time to merge these two even if I have to re-code some of it in order to merge the code bases? Also many of the queries and back-end calls are different. They are currently completely separate and stand alone applications. I did explain this to my boss and explained that we will be using the same database, he still wants to merge the code bases. I am also asked to create the whole design.

答:
My view is that this comes down to your definition of 'Application'

Lets say you have the following n-tier structure

Database A

Database B

Web Service A

Web Service B

Application C

Where A is your client facing stuff and B is the low level monitoring.

So we are separate at all the layers until we get to application C which merges services A and B to create a combined tool. I think this is fine and 'correct' design. We still have complete separation of concerns in terms of business logic but we present both to a user through a single Website or Application or whatever.

I notice you have tagged your question 'database design' this leads me to think that your structure might be more like

Database C

Tables A

Tables B

Application C

I think this does lead to a problem, as you will have no clear separation of the objects and business logic for the two sets of operations. The danger being these get muddled together and changes in one break, or expose security concerns in the other.

However, would a non-developer using the Application C, know the difference? or is it just an 'implementation detail'?

Title: Merging two applications into one


问:
Change number of publishers/subscribers at runtime
I need to redesign distributed Publish-Subscribe solution in our product.

Problem description

We have several producers (NT service), queues (MSMQ) and consumers (IIS server).
Task handling requires access to the MSSQL DB.

There are two types of tasks in the system:

ad-hoc tasks, pushed to the queue by ongoing flows.

batch tasks, every night each producer creates tons of tasks, mostly for maintenance and non real-time processing.

The requirement is to support tens of thousands tasks per day, and to be able to grow. Solution to the problem should be able to orchestrate task execution rate by several conditions:

Peak-hours - execute small amount of task, doesn't bother the subscribers

Off-hours - full gas

DB load - suppose we have metrics that shows how many tasks we can execute

Additional info:

We thinking to replace MSMQ with distributed queue (maybe KAFKA).

MSSQL is a bottleneck, subscribers tries to access the same tables, it causes timeouts/deadlocks,
but replacement is not an option.

Please advice how to implement the task orchestration.

Should it be on publishers, consumers or separate component?

答:
OK, my reading of your question is that you have messages on MSMQ which say 'do this task', when the worker picks it up that's basically all it says and the worker has to goto the DB to grab information and update stuff.

In my view this is a misinterpretation of the queue worker pattern, you're not really benefiting from having multiple workers and a queue, because at the end of the day the work in done on a single machine.

To make it really scalable, you need to put the full information needed to do the job in the message and understand how the job behaves when other similar jobs are being done at the same time, making it as atomic as possible.

Say you job is to grab some sales data from a transactional DB and compile a report, which means updating another table with some aggregate data. The message should hold the all the input 'sales data' and the output needs to be able to update that aggregate table and have it contain the correct result even it it runs twice, or in the wrong order etc.

In practical terms this may mean you need to break down and re-factor your jobs. You might have :

Job A, copy the days sales into a temp file

Job B, read the temp file and output another file of calculated results

Job C, read the aggregates results and work out if they can be correctly applied to the report tables

DBs are (almost) always the bottleneck, You have to move all the logic out of the DB, no big sprocs or SSIS packages. Just simple crud transactions on known size chunks of data.

A more complicated Queuing system will help with the orchestration of your jobs to a degree, but really it shouldn't be necessary. Your worker machines can run 100% 24/7 because that's all they do and however hard they work they don't affect the performance of the rest of the system


答:
I would have the throttling live on consumer, since your information so far indicates that all consumers should perform similarly, to the same schedule. Any centralized orchestration would have to ask the node what it's usage was, make a basic threshold check, and then turn back around tell the consumer to change itself. No need for the round trip (and commensurate comms code) as this decision is as easily made on the consumer. The consumer can read a shared schedule to know what it's performance profile should be at a given time. A centralized orchestration could be useful if performance profiles needed to change frequently and dynamically for only some nodes. Nothing says that the nodes can't reread the configuration periodically either.

It's an interesting choice to run your consumers on IIS. Do you not have task recovery problems when the worker process recycles unexpectedly? I have not had much success running long-term loads on IIS. However, I assume it is more convenient to deploy that way.

MSMQ is slow, but as you say, it is not your bottleneck. If it were possible, I might suggest that you put a service API in front of your database access so that you could control concurrent access a bit more (maybe even serialize access to avoid locking problems). However, being a legacy app, I assume that queries are executed directly by consumers. Even then I'm not sure it would be enough if you have long-running sprocs. You can, of course, take standard measures like analyzing whether indexes would be helpful to add (or remove).

Title: Change number of publishers/subscribers at runtime

Body:
I need to redesign distributed Publish-Subscribe solution in our product.

Problem description

We have several producers (NT service), queues (MSMQ) and consumers (IIS server).
Task handling requires access to the MSSQL DB.

There are two types of tasks in the system:

ad-hoc tasks, pushed to the queue by ongoing flows.

batch tasks, every night each producer creates tons of tasks, mostly for maintenance and non real-time processing.

The requirement is to support tens of thousands tasks per day, and to be able to grow. Solution to the problem should be able to orchestrate task execution rate by several conditions:

Peak-hours - execute small amount of task, doesn't bother the subscribers

Off-hours - full gas

DB load - suppose we have metrics that shows how many tasks we can execute

Additional info:

We thinking to replace MSMQ with distributed queue (maybe KAFKA).

MSSQL is a bottleneck, subscribers tries to access the same tables, it causes timeouts/deadlocks,
but replacement is not an option.

Please advice how to implement the task orchestration.

Should it be on publishers, consumers or separate component?


答:
I think you should go with the specific methods as much as possible.

By defining in the service interface what is and isn't possible you enable the client to have compile time checks and type safety. (assuming they follow the interface definition!)

If you go for a more fluid, query/update syntax with your own generic objects or language you make it easier for the client to make mistakes, ie, I don't know, attempt to "dim the water tap".

This will produce a runtime error, which you are going to have to transmit back to the client and the client will have to decode and act on. Much harder all round.

Title: WCF service design

Body:
I am rather new to WCF (or rest, or Json for that matter) and I'd like to have some expert opinions on which methods to define.

Some short introduction to give an idea of what the webservice should expose:
I am building domotica software (software that can control a ZWave network) which has different interfaces (a GUI application, a web server for configuration, and tablets/phones to control the network).

The webservice is the central application that :
- has a controller that can interact with ZWave devices
- exposes a WCF Json service so that clients can query and control on the ZWave network

The easy methods on the WCF interface:

```<code>    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getnodes")]
    public List<Node> GetNodes()
    {
        // ... retrieve all nodes from ZWave Controller
    }

    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getnode/{id}")]
    public Node GetNode(uint id)
    {
        // ... retrieve specific node
    }
</code>```

What I was wondering, is how "specific" the API should be in terms of POST/PUT methods. Clients need to interact with nodes, like set the name, set the room where the node resides in, switch a node on/off, set a dim amount, etc, etc.

I defined one method as follows:

```<code>    [WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, UriTemplate = "setnodename")]
    public void SetNodeName(NodeNewName nodeNewName)
    {
        // .. sets the name of the node, as specified in the passed object
    }
</code>```

This works, however this does cause a lot of different methods AND specific classes (as I specified a short list above of the functionality which would demand for specic methods and classes for each of them).

Is that the way to go? Or should I have one method UpdateNode and a more generic class as parameter which only specifies the properties that need to be updated? Or is there some kind of a guideline that would help me define a solid design for my webservice?

I googled a lot on this topic, and I read some articles about WCF design guidelines, but not really something where they cover this part. (or I am not the best googler on this specific topic, which would make sense as I am new on WCF/REST/Json/etc).

Hope somebody can understand what I am looking for and can help me on my way.

Much appreciated!


问:
Which is the preferable design for my Gateway?
I'm writing a Gateway class that extracts information from a HTML document. One of the responsibilities of the class is to traverse a table in the document and extract data from its rows. I'm trying to decide how to best represent a row, and I've come up with two solutions (in semi-pseudo code).

I could represent each row as an associative array:

```<code>class Gateway
{

    private $crawler;

    public function __construct($crawler)
    {
        $this->crawler = $crawler;
    }

    public function getRows()
    {
        $this->crawler->xpath('...')->each(function($node, $i)
        {
            return [
                'someInfo'      => $node->xpath('...'),
                'someOtherInfo' => $node->xpath('...')
            ];
        });
    }

}
</code>```

I could alternatively wrap each row in its own Gateway (however, I don't know if it's good practice to be hard-coding instantiation like this):

```<code>class Gateway
{

    private $crawler;

    public function __construct($crawler)
    {
        $this->crawler = $crawler;
    }

    public function getRows()
    {
        $this->crawler->xpath('...')->each(function($node, $i)
        {
            return new RowGateway($node);
        });
    }

}

class RowGateway
{

    private $crawler;

    public function __construct($crawler)
    {
        $this->crawler = $crawler;
    }

    public function getSomeInfo()
    {
        return $node->xpath('...');
    }

    public function getSomeOtherInfo()
    {
        return $node->xpath('...');
    }

}
</code>```

Which is the preferable approach here? I'm open to other designs, too.

答:
I think that depends on how often RowGateway is going to be used in your application: if many parts of the application need to read that information, then creating a dictionary representation leaves you open to many field names that will need to be manually changed if you change you want to implement that object, and a real class would make more sense. However, if that information is going to be encapsulated by another class, or if the rest of the application is likely to call Gateway->getRows() directly, then you can probably get by with a dictionary as long as the documentation for getRows() clearly describes the dictionary in which each row will be returned.

One other change I'd make is to have RowGateway parse the rows on construction -- otherwise, a malformed row would not throw an error until someone tries to read that row, while I think it would be better to report that when loading the file.


问:
When was block scope for variables introduced to C, and why is it still frowned upon?
In light of the recent OBJ_obj2txt vulnerability in LibreSSL (which was found during the OpenSMTPD audit, and does not affect OpenSSL), it came to my attention that the memory leak issue likely resulted from some earlier code refactoring, where the block scoped variable char *bndec was moved out to be function scoped instead.

I know first-hand that there is this great resistance to block scoped variables within old-school projects like OpenBSD, but what other justification would there be to move the char *bndec declaration?

More broadly, when was block scoping introduced for variables in C?  All I could find is that it was already part of C89.  Is that where it started, or was it also part of an earlier spec?

答:
I believe it's originally there in the first place. The {} are not just part of control structure syntax or function definitions, but they also define a compound statement (block).

It's mentioned in this page: "You can use a block wherever the grammar of PDP-11 C requires a single statement."

So, the compiler did extra work when dealing with them, it's not just used to know where does a block start and end.

Edit to clarify context

From wikipedia, "The development of C started in 1972 on the PDP-11 Unix system".


问:
Vertical alignment: yea or nay?
For instance, non-vertically aligned:

```<code>Name:   Hamt
Version:  0.1.0
Cabal-Version:  >= 1.2
License:  BSD3
Author:  Jason Baker
</code>```

Or vertically aligned:

```<code>Name:           Hamt
Version:        0.1.0
Cabal-Version:  >= 1.2
License:        BSD3
Author:         Jason Baker
</code>```

Which do you prefer and why?

答:
I prefer the first one, but without the tabs (which I guess the blanks are); just one blank space instead. To me that's easier to read when the data is not "similar", as in the given case. It also makes it more difficult (while editing such data) to "misread a row", i.e. when you have three rows with let's say, version numbers. And then while editing one, you accidentally edit another in it's place.

When the data is similar, however, it makes perfect sense to put it in columns as in your second example (only there is it not similar, but you get the point).

ContentLicense: CC BY-SA 2.5

Title: Vertical alignment: yea or nay?


答:
I see two distinct questions here:

Does the combined functionality make sense?

Does the work of converting the two applications to one pass a cost/benefit analysis?

The first question should be purely user-driven.  Does it make sense for users to have these two sets of functions together?  Is it likely that some of them want to see a less granular view, and then switch to the more detailed view? And so on.

The second question has to do with the actual development work involved.  It could be a huge amount of work with little benefit.  Or it could even save work overall, if the combined application is simpler and more maintainable in the future.  Development work to address security concerns should also be considered as part of this (it is unlikely that there are any insurmountable security issues, but it could be a lot of work to make the combined application secure).

We don't have the information to answer these two questions, but it would be helpful for you to consider them separately in deciding how to respond to your boss.

If you don't think the combined software meets #1, your response would be something like I am worried that this won't meet the needs of our users/customers, for these reasons:... It is not an objection about the amount of work, but that the end product is not a desirable goal.

If you see the benefit of combining the applications in the abstract, but think it is too much work, in my opinion the best response is not to say "we shouldn't do this" but try to present an estimate of how much effort the project will take.  It is up to your boss to decide cost/benefit, ultimately, but you can provide information to help with this (and highlight the size of the task).

Also important is why your boss wants you to do this.  If you don't know, you should try to find out more about the reasons.  Maybe there is a good rationale that you aren't aware of.  Or, maybe the reasons aren't very good, but it will help you have a more informed response.

Title: Merging two applications into one

Body:
Background:
My bosses want to merge two application that have two separate purposes.

One being for monitoring of equipment and bandwidth for our internal
network operations.

The other is an application to view similar data just less granular
and with less detail. This second application has to also perform
tasks such as generating tokens or creating a splash page that is
meant for the client to use but is generally used by the customer
representatives in the company. It also is used by external clients of properties.

Does it make sense to merge the two applications? Why or why not. I can understand there is an inherent security flaw with introducing this type of architecture. But is it worth the time to merge these two even if I have to re-code some of it in order to merge the code bases? Also many of the queries and back-end calls are different. They are currently completely separate and stand alone applications. I did explain this to my boss and explained that we will be using the same database, he still wants to merge the code bases. I am also asked to create the whole design.


问:
Can I execute a query in a catch block of try-catch?
I want to confirm the right approach of using try-catch exception handler.

I have written a query in a try block, and if any exception is thrown, it will execute a query in a catch block.

Is this the right way?

```<code>try {
    $query->fieldOrderBy($column_name, 'value', $sv1);
} catch (Exception $ex) {
    if (!empty($ex)) {
        $for_boolean = explode('boolean_', $column_name);
        $query->fieldOrderBy($for_boolean[1], 'value', $sv1);
    }
</code>```

答:
Can I execute a query in a catch block of try-catch?

You can do (practically) whatever you want in a catch block. There is some ambiguity when returning from within catch/finally, but this is not the case here.

Is this the right way?

It depends on what are you trying to achieve. If when studying the business rules it makes sense to execute a given database query when something goes wrong in a specific case, then yes, this is the right way. For instance, one could imagine a case where an element is added to a database and if it fails because of an unique constraint, tries adding the same element after changing the problematic value.

In your case, it might make sense to order some data by something, if it fails, order by something else, and if it still fails, propagate the exception up the stack. Without any information about the domain, we couldn't possibly guess whether your approach is right or wrong.

Your code, on the other hand, looks problematic.

Given the name of $query->fieldOrderBy, I expect it to return something: either the ordered items, or the number of affected rows. You don't use/check the return value. Why?

What is $sv1? Is it actually the most explicit name you could give to the variable in a context of your business domain?

Why do you catch (Exception $ex) instead of catching a more specific type of exception?

Why if (!empty($ex))? What are you trying to achieve? What would be the case where catch block will be executed, but the condition will result in false?

In $for_boolean = explode('boolean_', $column_name);, what if the column name doesn't contain boolean_?

Before doing $for_boolean[1], you don't check that you actually have at least two elements.

If you're dealing with an SQL database, you shouldn't specify the names of columns in variables: this will result in computed queries, which will ultimately lead to SQL Injection (and poor performance).


问:
Why squash git commits for pull requests?
Why does every serious Github repo I do pull requests for want me to squash my commits into a single commit?

I thought the git log was there so you could inspect all your history and see exactly what changes happened where, but squashing it pulls it out of the history and lumps it all into one commit.  What is the point?

This also seems to go against the "commit early and commit often" mantra.

答:
The main reason from what I can see is as follows:

The GitHub UI for merging pull requests currently (Oct 2015) does not allow you to edit the first line of the commit message, forcing it to be Merge pull request #123 from joebloggs/fix-snafoo

The GitHub UI for browsing the commit history currently does not allow you to view the history of the branch from the --first-parent point of view

The GitHub UI for looking at the blame on a file currently does not allow you to view the blame of the file with the --first-parent point of view (note that this was only fixed in Git 2.6.2, so we could forgive GitHub for not having that available)

So when you combine all three of these situations above, you get a situation where unsquashed commits being merged look ugly from the GitHub UI.

Your history with squashed commits will look something like

```<code>1256556316... Merge pull request #423 from jrandom/add-slideshows
7hgf8978g9... Added new slideshow feature
56556316ad... Merge pull request #324 from ahacker/fix-android-display
787g8fgf78... Hotfix for android display issue
f56556316e... Merge pull request #28 from somwhere/select-lang-popup
9080gf6567... Implemented pop-up to select language
</code>```

Whereas without squashed commits the history will look something like

```<code>1256556316... Merge pull request #423 from jrandom/add-slideshows
7hgf8978g9... Added new slideshow feature, JIRA # 848394839
85493g2458... Fixed slideshow display issue in ie
gh354354gh... wip, done for the week
789fdfffdf... minor alignment issue
56556316ad... Merge pull request #324 from ahacker/fix-android-display
787g8fgf78... hotfix for #5849564648
f56556316e... Merge pull request #28 from somwhere/select-lang-popup
9080gf6567... implemented feature # 65896859
gh34839843... minor fix (typo) for 3rd test
</code>```

When you have a lot of commits in a PR tracing where a change came in can become a bit of a nightmare if you restrict yourself to using the GitHub UI.

For example, you find a null pointer being de-referenced somewhere in a file... so you say "who did this, and when? what release versions are affected?". Then you wander over to the blame view in the GitHub UI and you see that the line was changed in 789fdfffdf... "oh but wait a second, that line was just having its indent changed to fit in with the rest of the code", so now you need to navigate to the tree state for that file in the parent commit and re-visit the blame page... eventually you find the commit... it's a commit from 6 months ago... "oh **** this could be affecting users for 6 months" you say... ah but wait, that commit was actually in a Pull Request and was only merged yesterday and nobody has cut a release yet... "Damn you people for merging commits without squashing history" is the cry that can usually be heard after about 2 or 3 code archeology expeditions via the GitHub UI

Now let us consider how this works if you use the Git command line (and super-awesome 2.6.2 which has the fix for git blame --first-parent)

If you were using the Git command line, you would be able to control the merge commit message completely and thus the merge commit could have a nice summary line.

So our commit history would look like

```<code>$ git log
1256556316... #423 Added new slideshow feature
7hgf8978g9... Added new slideshow feature, JIRA # 848394839
85493g2458... Fixed slideshow display issue in ie
gh354354gh... wip, done for the week
789fdfffdf... minor alignment issue
56556316ad... #324 Hotfix for android display issue
787g8fgf78... hotfix for #5849564648
f56556316e... #28 Implemented pop-up to select language
9080gf6567... implemented feature # 65896859
gh34839843... minor fix (typo) for 3rd test
</code>```

But we can also do

```<code>$ git log --first-parent
1256556316... #423 Added new slideshow feature
56556316ad... #324 Hotfix for android display issue
f56556316e... #28 Implemented pop-up to select language
</code>```

(In other words: the Git CLI lets you have your cake and eat it too)

Now when we hit the null pointer issue... well we just use git blame --first-parent -w dodgy-file.c and we are immediately given the exact commit where the null pointer de-reference was introduced to the master branch ignoring simple whitespace changes.

Of course if you are doing merges using the GitHub UI then git log --first-parent is really crappy thanks to GitHub forcing the first line of the merge commit message:

```<code>1256556316... Merge pull request #423 from jrandom/add-slideshows
56556316ad... Merge pull request #324 from ahacker/fix-android-display
f56556316e... Merge pull request #28 from somwhere/select-lang-popup
</code>```

So to cut a long story short:

The GitHub UI (Oct 2015) has a number of shortcomings with how it merges pull requests, how it presents the commit history and how it attributes blame information. The current best way to hack around these defects in the GitHub UI is to request people to squash their commits before merging.

The Git CLI doesn't have these issues and you can easily choose which view you want to see so that you can both discover the reason why a particular change was made that way (by looking at the history of the unsquashed commits) as well as see the effectively squashed commits.

Post Script

The final reason often cited for squashing commits is to make backporting easier... if you only have one commit to back port (i.e. the squashed commit) then it is easy to cherry pick...

Well if you are looking at the git history with git log --first-parent then you can just cherry pick the merge commits. Most people get confused cherry picking merge commits because you have to specify the -m N option but if you got the commit from git log --first-parent then you know that it is the first parent that you want to follow so it will be git cherry-pick -m 1 ...

Body:
The main reason from what I can see is as follows:

The GitHub UI for merging pull requests currently (Oct 2015) does not allow you to edit the first line of the commit message, forcing it to be Merge pull request #123 from joebloggs/fix-snafoo

The GitHub UI for browsing the commit history currently does not allow you to view the history of the branch from the --first-parent point of view

The GitHub UI for looking at the blame on a file currently does not allow you to view the blame of the file with the --first-parent point of view (note that this was only fixed in Git 2.6.2, so we could forgive GitHub for not having that available)

So when you combine all three of these situations above, you get a situation where unsquashed commits being merged look ugly from the GitHub UI.

Your history with squashed commits will look something like

1256556316... Merge pull request #423 from jrandom/add-slideshows
7hgf8978g9... Added new slideshow feature
56556316ad... Merge pull request #324 from ahacker/fix-android-display
787g8fgf78... Hotfix for android display issue
f56556316e... Merge pull request #28 from somwhere/select-lang-popup
9080gf6567... Implemented pop-up to select language

Whereas without squashed commits the history will look something like

1256556316... Merge pull request #423 from jrandom/add-slideshows
7hgf8978g9... Added new slideshow feature, JIRA # 848394839
85493g2458... Fixed slideshow display issue in ie
gh354354gh... wip, done for the week
789fdfffdf... minor alignment issue
56556316ad... Merge pull request #324 from ahacker/fix-android-display
787g8fgf78... hotfix for #5849564648
f56556316e... Merge pull request #28 from somwhere/select-lang-popup
9080gf6567... implemented feature # 65896859
gh34839843... minor fix (typo) for 3rd test

When you have a lot of commits in a PR tracing where a change came in can become a bit of a nightmare if you restrict yourself to using the GitHub UI.

For example, you find a null pointer being de-referenced somewhere in a file... so you say "who did this, and when? what release versions are affected?". Then you wander over to the blame view in the GitHub UI and you see that the line was changed in 789fdfffdf... "oh but wait a second, that line was just having its indent changed to fit in with the rest of the code", so now you need to navigate to the tree state for that file in the parent commit and re-visit the blame page... eventually you find the commit... it's a commit from 6 months ago... "oh **** this could be affecting users for 6 months" you say... ah but wait, that commit was actually in a Pull Request and was only merged yesterday and nobody has cut a release yet... "Damn you people for merging commits without squashing history" is the cry that can usually be heard after about 2 or 3 code archeology expeditions via the GitHub UI

Now let us consider how this works if you use the Git command line (and super-awesome 2.6.2 which has the fix for git blame --first-parent)

If you were using the Git command line, you would be able to control the merge commit message completely and thus the merge commit could have a nice summary line.

So our commit history would look like

$ git log
1256556316... #423 Added new slideshow feature
7hgf8978g9... Added new slideshow feature, JIRA # 848394839
85493g2458... Fixed slideshow display issue in ie
gh354354gh... wip, done for the week
789fdfffdf... minor alignment issue
56556316ad... #324 Hotfix for android display issue
787g8fgf78... hotfix for #5849564648
f56556316e... #28 Implemented pop-up to select language
9080gf6567... implemented feature # 65896859
gh34839843... minor fix (typo) for 3rd test

But we can also do

$ git log --first-parent
1256556316... #423 Added new slideshow feature
56556316ad... #324 Hotfix for android display issue
f56556316e... #28 Implemented pop-up to select language

(In other words: the Git CLI lets you have your cake and eat it too)

Now when we hit the null pointer issue... well we just use git blame --first-parent -w dodgy-file.c and we are immediately given the exact commit where the null pointer de-reference was introduced to the master branch ignoring simple whitespace changes.

Of course if you are doing merges using the GitHub UI then git log --first-parent is really crappy thanks to GitHub forcing the first line of the merge commit message:

1256556316... Merge pull request #423 from jrandom/add-slideshows
56556316ad... Merge pull request #324 from ahacker/fix-android-display
f56556316e... Merge pull request #28 from somwhere/select-lang-popup

So to cut a long story short:

The GitHub UI (Oct 2015) has a number of shortcomings with how it merges pull requests, how it presents the commit history and how it attributes blame information. The current best way to hack around these defects in the GitHub UI is to request people to squash their commits before merging.

The Git CLI doesn't have these issues and you can easily choose which view you want to see so that you can both discover the reason why a particular change was made that way (by looking at the history of the unsquashed commits) as well as see the effectively squashed commits.

Post Script

The final reason often cited for squashing commits is to make backporting easier... if you only have one commit to back port (i.e. the squashed commit) then it is easy to cherry pick...

Well if you are looking at the git history with git log --first-parent then you can just cherry pick the merge commits. Most people get confused cherry picking merge commits because you have to specify the -m N option but if you got the commit from git log --first-parent then you know that it is the first parent that you want to follow so it will be git cherry-pick -m 1 ...


问:
Entity Framework in n-tier application confusion
I'm building a rather large (web) application where I'm using Entity Framework to communicate with the database.

My solution is set up in layers like so:

Client

Website (MVC web application)

Server

BusinessLogic (contains, well, business logic. There's a lot of business rules involved in this project)

Repository (contains repository classes for querying the database using EF)

Interfaces (interfaces for defining the repository classes, i.e. IFirmRepository)

Model (contains my edmx file, view models, enums etc)

So, the client/UI knows about the business logic layer where the business classes needed for a given view is injected into the MVC controllers. The business logic layer knows about interfaces and model and the repository implements the interfaces.

Been developing for the last week using this approach, I have a feeling that it's not quite "correct" since:

The repository classes becomes bloated with a lot of methods where I need to use the Include()method to be able to work with the disconnected entities in my business logic layer

For every query, I'm using a new context: using(var ctx = new MyContext()) and a single business logic method might be calling more than one repository method which makes for N number of new MyContext() which isn't ideal, I guess?

Relating to the above: I've read about having one context per http request is the way to go when it comes to websites, which my approach seems to "violate"?

Out of curiousity, I tried to simply make use of the MyContextdirectly in a business logic class, making the query for the object(s) needed and then performing business logic. Doing this felt very smooth/easy and made the repository seem like a lot more work than needed and almost redundant.

So, I guess different projects needs different approaches when it comes to the architecture, but before I scratch my repository completely and making use of the entity framework context directly in my business logic classes, I'd like your opinion on this. It kinda feels wrong (in the sense that I'm violating something) to scratch the repository, but on the other hand, it's so easy to simply do the magic without first defining the method in an interface, then implementing it as a repository and then make use of it in a business logic class.

So, what is your opinion on this? :-) Am I completely off the record here, or?

Thanks in advance.

答:
It sounds like you have too many repositories.

As a general rule I would try to stick to one per Database. Afterall thats your underlying repository and the Tables (objects) in it should all be related. So I can expect queries/methods lile getFirmsWithCustomer etc.

I think you are taking the correct approach in seperating EF from the business logic when you have a large application.

I would go further and say don't use EF with this pattern. EF works best for small projects where you want to skip writing the data layer. If you go the whole way with Sprocs and Repositories using SQL client will be less and easier to write code.


问:
Starting on Web Project now - Do we choose HTML5/JS over Silverlight?
we are about to start on a Web Development project (the planning starts early 2011).

Do we choose HTML5/JS over Silverlight?

Are there any applications which now run on HTML5? Samples?

A simple Google Search led me here. Those look great (especially the Star Wars one!), but they are not what you call proper applications as such.

答:
If you are going to write most of your app from scratch and have developers with very good skills and motivation to mess with unstable specifications and browser quirks in exchange for doing cool things that nobody did before - go HTML5.

If on the other hand you prefer to build on top of what others build, use advanced tools and ready-made widgets and prefer getting things done sooner rather than later, no matter if a little ugly, and want to have a wide choice of developers be available to you - you may want to go with more established technologies, like Flash or Silverlight.

It also depends on if there are some existing tools and libraries in the area you are targeting or you are opening an entirely new topic.


问:
OOP - Should I set the database connection as `public` for other classes to use it, although it might be unsafe?
I have a basic Database class, and it has a mysqli property (an object itself) which contains the connection information. Other classes uses this class to read and manipulate the database.

There are built-in functions in any database connection object (in this case, PHP's mysqli::multi_query, mysqli::next_result etc.), that I need to use in other classes.

The problem is that I really do not want to set the connection property as public since I believe it is a bad practice to do so in any property, especially not one with connection information.

So what should I do? Should I set it to public anyway, or should I create manually a function for each built-in function I need to use?

答:
The whole point of wrapping a core PHP database driver is to provide your custom interface for handling database requests. Making the mysqli property public completely defies the purpose and you wouldn't really need your custom class in the first place.

The best approach would be to create a DatabaseInterface, have class or classes implement it, classes, which, preferably in their constructor, take a core PHP database driver (be it mysqli or PDO) and use the DatabaseInterface as parameters for classes which require database interaction.

This way you provide your own abstraction, over which you have full control, and are also not limited to single implementation.

More details and implementation example

In PHP you have generally two recommended options for database connection.

using PDO

using mysqli

The problem is PDO and mysqli provide different interface to querying, creating transactions, so if you used for example mysqli in your application directly and then wanted to switch to PDO, you would have to refactor every single database call in your app.

Use interfaces for abstraction

You create an interface, which will represent your very own interface for database calls. Here is a very simple example how some of its methods may look.

```<code>interface MyDatabase
{
    public function beginTransaction();
    public function commitTransaction();
    public function doQuery($sql);
}
</code>```

Right now you want to use mysqli, so you create a new class, MyMySQLiDriver, which will implement the MyDatabase interface and either take a mysqli object in its constructor as a parameter, or you can use the procedural-programming mysqli_* functions.

```<code>class MyMySQLiDriver implements MyDatabase
{
    protected $mysqli;

    public function __construct($mysqli)
    {
        $this->mysqli = $mysqli;
    }

    public function beginTransaction() { /* use $this->mysqli here */ }
    public function commitTransaction() { /* use $this->mysqli here */ }
    public function doQuery($sql) { /* use $this->mysqli here */ }
}
</code>```

Anywhere else in your code, if you want to use a database, you are going to pass an object of MyDatabase (the interface) type as a parameter and use its methods.

```<code>function IAmUsingTheDatabase(MyDatabase $db)
{
    $db->beginTransaction();
    $db->doQuery("SELECT * ...");
    $db->commitTransaction();
}
</code>```

Note that the IAmUsingTheDatabase has no idea whether you are using PDO, mysqli or anything else. It wants to use the database and it uses the interface you provided.

As I have said in the comments under this post, if, in the future, you don't want to use the MyMySQLiDriver anymore, you create a new class, be it MyPDODriver or anything else, which will again implement MyDatabase interface.

Where to go from here

You can study more on this topic under Inversion of Control (this is directly tied to Dependency injection and benefits greatly from the Strategy pattern).

Body:
The whole point of wrapping a core PHP database driver is to provide your custom interface for handling database requests. Making the mysqli property public completely defies the purpose and you wouldn't really need your custom class in the first place.

The best approach would be to create a DatabaseInterface, have class or classes implement it, classes, which, preferably in their constructor, take a core PHP database driver (be it mysqli or PDO) and use the DatabaseInterface as parameters for classes which require database interaction.

This way you provide your own abstraction, over which you have full control, and are also not limited to single implementation.

More details and implementation example

In PHP you have generally two recommended options for database connection.

using PDO

using mysqli

The problem is PDO and mysqli provide different interface to querying, creating transactions, so if you used for example mysqli in your application directly and then wanted to switch to PDO, you would have to refactor every single database call in your app.

Use interfaces for abstraction

You create an interface, which will represent your very own interface for database calls. Here is a very simple example how some of its methods may look.

interface MyDatabase
{
    public function beginTransaction();
    public function commitTransaction();
    public function doQuery($sql);
}

Right now you want to use mysqli, so you create a new class, MyMySQLiDriver, which will implement the MyDatabase interface and either take a mysqli object in its constructor as a parameter, or you can use the procedural-programming mysqli_* functions.

class MyMySQLiDriver implements MyDatabase
{
    protected $mysqli;

    public function __construct($mysqli)
    {
        $this->mysqli = $mysqli;
    }

    public function beginTransaction() { /* use $this->mysqli here */ }
    public function commitTransaction() { /* use $this->mysqli here */ }
    public function doQuery($sql) { /* use $this->mysqli here */ }
}

Anywhere else in your code, if you want to use a database, you are going to pass an object of MyDatabase (the interface) type as a parameter and use its methods.

function IAmUsingTheDatabase(MyDatabase $db)
{
    $db->beginTransaction();
    $db->doQuery("SELECT * ...");
    $db->commitTransaction();
}

Note that the IAmUsingTheDatabase has no idea whether you are using PDO, mysqli or anything else. It wants to use the database and it uses the interface you provided.

As I have said in the comments under this post, if, in the future, you don't want to use the MyMySQLiDriver anymore, you create a new class, be it MyPDODriver or anything else, which will again implement MyDatabase interface.

Where to go from here

You can study more on this topic under Inversion of Control (this is directly tied to Dependency injection and benefits greatly from the Strategy pattern).


问:
Ways of creating expected object for assert
Recently, I started to use TDD. It's really cool and fun but creating expected object for assertEquals is very boring and tedious.

At the moment I see only two way for that:

Straightforward

Creating object in code using million of setters. Using that approach greater part of tests is creating expected object. I think it's not very cool.

Serialization

Writing expected object for example in JSON and then serialize it in test. I can't find disadvantages of that way except possibility of inconsistent state between my beans and test files.

EDIT

toString() (@Kilian Foth comment)

Some kind of serialization, but I think it deserves attention. Define a strictly controlled toString() and then assert equality with a literal string rather than a second object.

Configuring in DI container(inspired by @Spotted)

I remembered about DI. Does anybody configure expected bean in DI (Spring XML for example) and then inject it to test method? Is it bad and unefficient approach or something normal?

Are there any other techniques/approaches or special tools that can accelerate that process?

答:
Unless you are specifically testing the equals() method of a class, there is usually no reason for a unit test to assert the equality of two objects. A unit test should test one behaviour and not all features of a code unit, whether that is a module, a class or even a method (a method with many possible inputs usually needs many unit tests and not just one).

Therefore, there is often no need to create such a "comparison object". If you're verifying that a transaction puts your customer in the correct status, obtain the customer and assert things about its status, not that it's exactly equal to another complex object that the test provides. That is almost certainly testing too much an in a very brittle way, since any change to the customer class might break the "status" test.


问:
REST Service Description in a Hypermedia agnostic way?
How do I implement REST service description in a Content-type agnostic way?

Background

I am developing a RESTful API for Web Application. Now this app is somewhat different than a standard run-of-mills solution. This app uses a SIP B2BUA (asterisk), PHP+Mysql on Apache & NodeJS.

It is a call center solution that uses asterisk to handle VoIP calls and a LAMP stack for the UI.

Architecture

REST demands that application be stateless. However, due to the very nature of SIP, it cannot be 100% stateless. Thus I am using NodeJS at certain places to keep the real-time communication going.

Now, there is a REST API to all of this. It is designed in a pretty simple way. You have resources like user, call, campaign etc. And a user can initiate HTTP Verbs on these resources.

The Questions

I have arranged the architecture following the MVC pattern. The most salient thing I have done is, enforce Docblocks in the Models. The following is an example of such a class:

```<code>abstract class BaseUserInterface implements Interfaces\UserInterface {
protected $usrType = null;

/**
 * This is the constructor
 */
public function __construct(Interfaces\User $usrObj){
    $this->usrType = ($usrObj instanceof \Model\Agent) ? 'agent':$this->usrType;
    $this->usrType = ($usrObj instanceof \Model\Admin) ? 'admin':$this->usrType;
    if($this->usrType === null){
        throw new \Framework\APIException(__CLASS__." : Insane Type of User Passed while initiating Interface", 500);
    }

    //Force docblocks
    $methodList = $this->listMethods();
    foreach($methodList as $method){
        $docblock = $this->describe($method);
        if(!$docblock){
            throw new \Framework\APIException(__CLASS__." : Contract Violated - Method $method Lacks Documentation", 500);
        }
    }
} //End __construct

/**
 * This is the typeOfInterface
 */
public function typeOfInterface(){ //return whether this is admin or agent interface
    return $this->usrType;
} //End typeOfInterface

/**
 * This is the listMethods
 */
public function listMethods(){ //Allowed Methods
    return get_class_methods($this);
} //End listMethods

/**
 * This is the describe
 */
public function describe($methodName){
    $methodList = $this->listMethods();
    if(!in_array($methodName, $methodList)){
        throw new \Framework\APIException(__CLASS__." : Asked To Describe Insane Method - ".$methodName, 400);
    }
    $class = get_class($this);
    $reflector = new \ReflectionClass($class);
    $phpdoc = $reflector->getMethod($methodName)->getDocComment();
    if($phpdoc){
        return $this->docParse($phpdoc);
    }
    else {
        return false;
    }
} //End describe

/**
 * This is the DocParser
 */
protected function docParse($phpdoc){
    $phpdoc = new \phpDocumentor\Reflection\DocBlock($phpdoc);
            return $phpdoc->getShortDescription()."<br />";
} //End docParse

abstract public function logout();
</code>```

Of course, I have given an idea of the docblocks and not the complete docblocks here. Basically, they would have the necessary documentation. Now, all the classes in Model namespace that would extend this class would have to use docblocks thereby enforcing documentation.

Also, I have a Helper::convert() function that can convert any result between XML and JSON depending on the user's Accept Request in the HTTP Header.

So, I am all set with that.

What I am utterly confused with is:
1. I want the user to be able to ask for Describe() on available methods at a given resource. How do I implement that via HTTP headers?

OPTIONS in HTTP tells me to respond with allowed VERBS on ***this*** resource.

I want to have a common gateway to the app. User asks for /index.php. I respond with user, call, campaign and a brief message telling them that they can use GET on these resources to know more. Then upon those resources, I want to display available methods followed by description of the selected method and so on and so forth.

Most importantly, I want to respond in the user's chosen accept-header if supported by me.

How do I go about doing this following correct conventions? Also, some references to RFCs would be really appreciated.

答:
I want the user to be able to ask for Describe() on available
  methods at a given resource. How do I implement that via HTTP headers?

You don't.

REST works by having a pre-determined format for communication between client and server. For example HTML, or PNG, or MP4. The client understands HTML, the server understands HTML (well in some cases, in others the server is just a dumb document store)

The client tells the server what data formats it understands and the server responds with the format if it also can output this resource. The client shouldn't be learning about the data format used to represent the resources. It should instead navigate the data format to get to the resource it wants. It shouldn't understand the layout of the resources.

Take HTML for example. Firefox does not know the layout of resources on the New York Time site. It doesn't know what "Todays weather" means, nor does it know what "Headlines" mean.

Firefox does though know what HTML means. It then leaves the navigation of resources to the user.

Document your data format and then let the client (either via a human user or via an api crawler) discover the resources in your system.

And remember REST is a state machine. You find a resource, change the state of it, and push it back to the server to save. Don't tell the server to do something with a resource (other than GET,POST,PUT,DELETE etc), change the state of the resource on the client and push it back to the server to save.

I want to have a common gateway to the app. User asks for /index.php. I respond with user, call, campaign and a brief message telling them that they can use GET on these resources to know more. Then upon those resources, I want to display available methods followed by description of the selected method and so on and so forth.

Again don't put this in code. Put this is a spec that the client then implements.

The whole point of REST is that the client and the server are not tied in this fashion. For example when a web browser pulls down an image in PNG format it doesn't also contain instructions on what a PNG image is. The assumption is that the browser already understands what a PNG image is otherwise it wouldn't have told the server to represent the resource in this image format.

Most importantly, I want to respond in the user's chosen accept-header if supported by me.

Just check the Accept header on the request, if you support that format then response, if you don't return status code saying format not supported, or just return it in txt (most clients should at very least support text)


问:
Illusory code duplication
The usual instinct is to remove any code duplication that you see in the code. However, I found myself in a situation where the duplication is illusory.

To describe the situation in more details: I am developing a web application, and most views are basically the same - they display a list of items which the user can scroll and choose from, a second list that contains selected items, and a "Save" button to save the new list.

It seemed to me that the problem is easy. However, each and every view has its own quirks - sometimes you need to recalculate something, sometimes you must store some additional data etc. These, I solved by inserting callback hooks in the main logic code.

There are so many minute differences between the views that it is becoming less and less maintainable, because I need to provide callbacks for basically all functionality, and the main logic starts to look like a huge sequence of callback invocations. In the end I am not saving any time or code, because every view has its own code that is executed - all in callbacks.

The problems are:

the differences are so minute that the code looks almost exactly alike in all views,

there are so many differences that when you look at the details, to code is not a bit alike

How should I handle this situation?

Is having core logic composed entirely of callback calls a good solution?

Or should I rather duplicate the code and drop the complexity of callback-based code?

答:
There are already other useful answers. I will add mine.

Duplication is bad because

it clutters the code

it clutters our comphrension of the code
but most importantly

because if you change something here and you also
have to change something there, you could forget/introduce
bugs/.... and it is hard to never forget.

So the point is: you aren't eliminating duplication for the sake of it or because someone said it's important. You are doing it because you want to reduce bugs/problems. In your case, it appears that if you change something in a view, you probably won't need to change the exact same line in all of the other views. So you have apparent duplication, not actual duplication.

Another important point is to never rewrite from scratch something that is working now only on the basis of a matter of principle, as Joel said (you could have already heard of him....). So, if your views are working, proceed to improve step by step and don't fall prey to the "single worst strategic mistake that any software company can make".

Title: Illusory code duplication


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
My first two annoyances has not to do with PHP, but with its implied usage conventions.

'The file name extension' for library code (e.g. PEAR/Horde/Zend/etc.) should end on .phps instead of .php. The benefit of this is that it clearly separates code to run and code to include, as well as that optionally all (your) code is pretty readable/browsable from the server. As a bonus, spl_filename_extensions() can be used in your autoloader for other's convenience.

The convention (in the documents) is that :: is used for both static as well instance methods, I would be thankfull if they would use :: for static and -> for instance stuff. As a good convention there still will be room for error concerning interpretation, but it's at least more clear.

To name a few, I would also like to see the following:

Reflection*'s getDocComment (or perhaps another variant of the name or argument) should be more liberal and also get just the first comments (until space) above the mentioned type. In other words: I don't like the verbose (read: line eating) doccomment while I really just want to be able to provide the bare minimum in any kind of commenttype: //, #, or /* ... */.

List of used namespaces, e.g. getdefinednamespaces().

The behaviour of 'undefined constants' should be changable by an ini directive, e.g. an empty string or fatal error. Nevertheless, it should never be implicitly transformed to a string! (it's like the ; in javascript).

The constant __CLASS__ should also automatically work like this (called statically) stdClass::__CLASS__ == '\stdClass'. In other words, instead of referring to a class by a string, I want to use a class and its magic constant __CLASS__ to refer to it. (yes it is an idefix)

Type casting and magic methods __fromType($instancetype) and __toType($type). So an object can be casted to an integer: $y = (int) $x  or to another object $y = (BeanWrap) $x. Nevertheless, an implementation of this means that of the twelve available casts which cover eight different types, the names of these casts can not be used as classnames (e.g. int, binary, boolean) anymore.


问:
How much detail is in a good UI regression test?
We use a detailed step-by-step user-interface regression test for our commercial web application.  It has a "backbone" test for the most used / most important parts of the system, with optional tests for specific areas of functionality.  Using this plan has definitely helped us ensure high quality software.

But, having very specific tests can be counter-productive.  The tester concentrates on following the test and will completely miss usability issues, or not notice fairly obvious problems such as the bottom part of a page that is missing.

By contrast, some of the best UI testing happens when building a demo of a new feature.  I often do my own best testing by pretending to demonstrate the system to an imaginary prospect.  Yet when I tell the testers, "Just demonstrate the system to yourself" they don't cover nearly as much functionality as they do with a detailed point-by-point test.

I'm repeatedly asked to provide more and more detail in the test plan so that a new untrained tester can test with it without asking any questions.  Yet details seem to be counter-productive.  How much detail do you put in a regression test to make it effective?  How do you write tests that make the tester focus more on the system than on checking off items on the test?

答:
If you say "demonstrate the system", I hear customer workflows: how the customer is going to use the system.

So typically, next to some basic functionality, like "does it install, start etc.", I find UI testing mostly helpful to simulate a real user working with the system.

Also, most often, UI automaters get their specification from some other place. If there is no such place/person, you could ask them to talk to customers or product management on how they use the system.

This also has the benefit of you being a little more certain that the product you ship is working in (at least) some real world scenarios.


问:
DirectX11: Where exactly does the buffer swapping happen in the 'Swap Chain'?
I've read up on the theory/reasoning behind a swap chain in Graphics. Everywhere I've read, they talk about pointers to the front and backbuffer(s) which are swapped instead of actual data exchange. My question is, where exactly can we see this swapping? is it in some function? is it automatic? if it's automatic, where do we get the pointer to the other buffer?

If we look at this code from Rastertek for instance, m_renderTargetView always seems to point to the same buffer throughout the execution of the code :

```<code>result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
if(FAILED(result))
{
    return false;
}

// Create the render target view with the back buffer pointer.
result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
if(FAILED(result))
{
    return false;
}
backBufferPtr->Release();
backBufferPtr = 0;
</code>```

答:
When swapping with a Direct3D 11 device, the API presents the contents of the current buffer and internally maps in the next buffer as the same slot, making it seem like you're always working with the same buffer.

From what I've seen of Direct3D 12, they appear to remove this shadowing and instead forces the developer to manually keep track of which resource is used to present and which one is the render target.

Direct3D 12 forbids usage of the usual DXGI_SWAP_EFFECT_DISCARD and DXGI_SWAP_EFFECT_SEQUENTIAL, instead mandating DXGI_SWAP_EFFECT_FLIP_DISCARD or DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL. Generally you are forced to use DXGI flip model introduced in DXGI 1.2 improvements.

Citing MSDN's page titled DXGI 1.4 Improvements:

Invariant Backbuffer Identity

In Direct3D 11, applications could call GetBuffer( 0, … ) only once.
  Every call to Present implicitly changed the resource identity of the
  returned interface. Direct3D 12 no longer supports that implicit
  resource identity change, due to the CPU overhead required and the
  flexible resource descriptor design. As a result, the application must
  manually call GetBuffer for every each buffer created with the
  swapchain. The application must manually render to the next buffer in
  the sequence after calling Present. Applications are encouraged to
  create a cache of descriptors for each buffer, instead of re-creating
  many objects each Present.


问:
Run coded UI tests on different projects
With little or none previous experience of testing, I'm looking into adding automated testing to a continuous integration process of SharePoint applications. I've learned how this can be achieved using coded UI tests that are run before deployment and during the build and I've used Selenium with Java before, where we didn't record any scenarios but instead wrote tests by hand, identifying elements in the GUI and asserting results. With this little experience, I have a few questions about UI testing.

Is it possible to write test methods that can be applied on several different applications, such as testing buttons etc. or is this something that has to be written for each project, since the results of button click may vary? I assume that this would require following a specific standard .

Are there any UI testing methods that can be generalized and applied to all projects that go through a certain build, or is the same here that all UI tests must be written specifically for that application?

答:
You could share a low level layer of functionality for different applications (that at least have to be based on the same technology, like Web, WPF, ... or a superset thereof).

Actually, you can think of many UI testing tools as this (and this is why it often does not make sense for you to write that layer). Then you have to separate the identification part from the control part:

all buttons are clickable (if they are enabled, so they have an "enabled" property and a "click" function)

you distinguish 2 buttons via their UI path: /application1/greatDialog/ButtonOk and /application2/superDialog/subGrouping/ButtonMaybe

You only save little code though, since applications typically behave very differently. Depends all on how much is shared in the UI and how similar the usage is.


问:
Which string search algorithm is actually the fastest?
I have been stuck for some time on which is the fastest string search algorithm, heard many opinions, but in the end I'm not sure.

I have heard some people saying that the fastest algorithm is Boyer-Moore and some saying that   Knuth-Morris-Pratt is actually faster.

I have looked up for the complexity on both of them but they mostly look the same O(n+m). I have found that in the worst case scenario Boyer-Moore has an O(nm) complexity compared to Knuth-Morris-Pratt which has O(m+2*n). Where n=length of text and m=length of pattern.

As far as I know Boyer-Moore has a linear-worst case-time if I would use the Galil Rule.

My question, Over all which is actually the fastest String search algorithm (This question includes all possible sting algorithms not just Boyer-Moore and Knuth-Morris-Pratt).

Edit: Due to this answer

What I'm exactly looking for is:

Given a text T and a pattern P I have to find all the appearances of P in T.

Also the length of P and T are from [1,2 000 000] and the program has to run under 0.15 sec.

I know that KMP and Rabin-Karp are enough to get a 100% score on the problem but I for one wanted to try and implement Boyer-Moore. Which would be best for this type of pattern search?

答:
Use content addressable memory, implemented in software in the form of virtual addressing (pointing letters to letters).

It's kinda superfluous to an average string matching algorithm.

CAM can match a huge number of patterns simultaneously, up to about 128-letter patterns (if they are ASCII; if they are Unicode only 64). And it's one call per length of letter in the string you want to match to and one random read from memory per length of the max pattern length. So if you were analyzing a 100,000 letter string, with up to 90,000,000 patterns simultaneously (which would take about 128 GiB to store a count of patterns that large), it would take 12,800,000 random reads from RAM, so it would happen in 1ms.

Here's how the virtual addressing works.

If I start off with 256 startoff addresses, which represent the first letter, these letters point to 256 of the next letters. If a pattern is nonexistent, you don't store it.

So if I keep linking letters to letters, it's like having 128 slices of virtual addressing pointing to virtual addressing.

That will work — but to get to 900,000,000 patterns simultaneously matching, there's one last trick to add to it — and it's taking advantage of the fact that you start off with a lot of reuse of these letter buffers, but later on it scatters out. If you list the contents, instead of allocating all 256 characters,  then it slows down very little, and you'll get a 100 times capacity increase, because you basically eventually only get 1 letter used in every letter pointer buffer (which I dubbed 'escape').

If you want to get a nearest-neighbour string match then you have many of these running in parallel and you collect in a hierarchy, so you spread your error out unbiased.   if you try to nearest-neighbour with just one, then you're biased towards the start of the tree.


答:
This is going back 25 years, but I can remember the limits of screens where you could only see 20-22 lines of code on the screen at one go (due to terminal screen size to the Unix main frame) and it was very easy to have a function variable and a block variable with the same name and not realise it.  gcc brought in a --shadow flag to warn about this, but not all compilers had an equivalent.

Another issue was with code readability.

```<code>int j;
for(j=1;j<10;j++)
{
    int i=5;
    i++;
    printf("i=%i\n",i);
}
</code>```

Many developers at the time seemed to read this loop as setting i=5 every time around the loop, and not just set when the variable was created. Having

```<code>static int i=5;
</code>```

declared within a loop would have caused no end of confusion.

Title: When was block scope for variables introduced to C, and why is it still frowned upon?

Body:
In light of the recent OBJ_obj2txt vulnerability in LibreSSL (which was found during the OpenSMTPD audit, and does not affect OpenSSL), it came to my attention that the memory leak issue likely resulted from some earlier code refactoring, where the block scoped variable char *bndec was moved out to be function scoped instead.

I know first-hand that there is this great resistance to block scoped variables within old-school projects like OpenBSD, but what other justification would there be to move the char *bndec declaration?

More broadly, when was block scoping introduced for variables in C?  All I could find is that it was already part of C89.  Is that where it started, or was it also part of an earlier spec?

Body:
This is going back 25 years, but I can remember the limits of screens where you could only see 20-22 lines of code on the screen at one go (due to terminal screen size to the Unix main frame) and it was very easy to have a function variable and a block variable with the same name and not realise it.  gcc brought in a --shadow flag to warn about this, but not all compilers had an equivalent.

Another issue was with code readability.

int j;
for(j=1;j<10;j++)
{
    int i=5;
    i++;
    printf("i=%i\n",i);
}

Many developers at the time seemed to read this loop as setting i=5 every time around the loop, and not just set when the variable was created. Having

static int i=5;

declared within a loop would have caused no end of confusion.


问:
Incrementing Strings in PHP (and Perl)
PHP allows you to increment strings. Why?

Let's jump ahead a bit. Take the following code:

```<code>$string = '9ZzZ';
echo ++$string; // 10AaA
</code>```

From a purist point of view this may seem like nonsense, however, you can see there is clearly a pattern here. Each column is treated as a set, (numbers, uppercase letters, lowercase letters). Then each set behaves like its own numbering system.

The manual confirms this and states that they copied Perl:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

But, it doesn't actually explain why.

Perls manual states something very similar, but again goes in to no explanation as to why this extra magic was added.

The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern /^[a-zA-Z][0-9]\z/ , the increment is done as a string, preserving each character within its range, with carry

Similarly enigmatically:

The auto-decrement operator is not magical.

Why is increment so important but decrement isn't? And why would they do this at all?

It's logical in its own way, and I can see uses for it (though you could write something more obvious in its place). I can even see why they didn't to mill through the ASCII character set (since that might not be the character set your using) or through the character set defined in php.ini as that could significantly alter behaviour between systems. So why bother at all?

答:
My understanding is that the feature was originally intended for generating sequences of filenames for scripts that need to produce variable numbers of output files. While you could use a simple counter for the purpose, this hasa few drawbacks (unpredictable name length causes bad sorting when files are listed alphabetically; letters are preferable to digits when many files are needed in order to keep generated names short), both of which can be solved by initialising your counter to (for example) 'aaaa'.

While other solutions are clearly possible and arenot even especially hard, perl's solution is remarkably concise.

Why php copied the idea, I'm not sure. It was never really intended for the type of application that benefits from this. It perhaps has something to do with the fact that perl was the dominant language for web scripting at the time.

Title: Incrementing Strings in PHP (and Perl)


答:
There is a really useful utility in the unix world for splitting up large files named (unsuprisingly) split.

Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'.

You can see that incrementing of strings there.

Perl is especially useful in situations where one wants to pull out the swiss army chainsaw of the unix utility world. I have in the past used this functionality for writing my own tools that needed to have similar functionality as that provided by split. And 263 possible values in two characters is quite a bit more than 103.

As to why ++ is magical while -- isn't?  Its because it is easy to identify a consistent expectation for what ++ on a string does on boundary conditions while -- doesn't have easy expectations.

```<code>$foo = "zz";
$foo++;
print "$foo\n";
</code>```

This is aaa.  Very similar to how one would expect the following to behave:

```<code>$foo = 99;
$foo++;
print "$foo\n";
</code>```

And while:

```<code>$foo = 0;
$foo--;
print "$foo\n";
</code>```

gives you -1, would should:

```<code>$foo = "a";
$foo--;
print "$foo\n";
</code>```

return?  And with that, the designer throws up his arms and says "you know what, there's not a use case for it and I can't make it work consistently that isn't surprising to the programmer." and says instead "it isn't magical" and leaves it at that.

Title: Incrementing Strings in PHP (and Perl)

Body:
PHP allows you to increment strings. Why?

Let's jump ahead a bit. Take the following code:

```<code>$string = '9ZzZ';
echo ++$string; // 10AaA
</code>```

From a purist point of view this may seem like nonsense, however, you can see there is clearly a pattern here. Each column is treated as a set, (numbers, uppercase letters, lowercase letters). Then each set behaves like its own numbering system.

The manual confirms this and states that they copied Perl:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

But, it doesn't actually explain why.

Perls manual states something very similar, but again goes in to no explanation as to why this extra magic was added.

The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern /^[a-zA-Z][0-9]\z/ , the increment is done as a string, preserving each character within its range, with carry

Similarly enigmatically:

The auto-decrement operator is not magical.

Why is increment so important but decrement isn't? And why would they do this at all?

It's logical in its own way, and I can see uses for it (though you could write something more obvious in its place). I can even see why they didn't to mill through the ASCII character set (since that might not be the character set your using) or through the character set defined in php.ini as that could significantly alter behaviour between systems. So why bother at all?

Body:
There is a really useful utility in the unix world for splitting up large files named (unsuprisingly) split.

Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'.

You can see that incrementing of strings there.

Perl is especially useful in situations where one wants to pull out the swiss army chainsaw of the unix utility world. I have in the past used this functionality for writing my own tools that needed to have similar functionality as that provided by split. And 263 possible values in two characters is quite a bit more than 103.

As to why ++ is magical while -- isn't?  Its because it is easy to identify a consistent expectation for what ++ on a string does on boundary conditions while -- doesn't have easy expectations.

$foo = "zz";
$foo++;
print "$foo\n";

This is aaa.  Very similar to how one would expect the following to behave:

$foo = 99;
$foo++;
print "$foo\n";

And while:

$foo = 0;
$foo--;
print "$foo\n";

gives you -1, would should:

$foo = "a";
$foo--;
print "$foo\n";

return?  And with that, the designer throws up his arms and says "you know what, there's not a use case for it and I can't make it work consistently that isn't surprising to the programmer." and says instead "it isn't magical" and leaves it at that.


问:
No central database
I have a client that is looking to get a website/mobile apps/desktop apps built that deal with very sensitive data (more sensitive than bank/card details). Because of the sensitive nature of the data, they do not want to save it in a central database but they still want their apps to synchronise (let's say I add some data into my mobile app, I then want to be able to go to my desktop app and see the same data).

I cannot think of a nice, reliable way of doing this and I am not sure there is one. Which is why I am here. Does anyone know how I could deal with this data?

One solution I was thinking about was to have a client side database on each app that would somehow sync between apps, I can see this being very unreliable and getting messy though.

答:
One option to do the synchronization would be to do it peer-to-peer. This will still require a central server, but that server won't handle any of the data.

When a device goes online, a central server gets a notification with the user-id. When a second device of the same user goes online, the server sends both devices the IP addresses of the other. The devices can then exchange data directly. Caveat: one device needs to act as a server, so at least one can not be behind a NAT router.

Don't forget that you will need strong authentication and encryption for both the notification mechanism and for the peer-to-peer exchange.

Title: No central database


答:
Plenty of sensitive information gets stored in databases.  In fact, a central database is probably the most secure way to store this data.  Large enterprise databases have tons of functionality to do things like encrypt sensitive information, to audit who accesses it, to limit or prevent people including DBAs from viewing the data, etc.  You can have professional security experts monitoring the environment and professional DBAs overseeing backups so that you don't lose data.  It would almost certainly be much easier to compromise data stored on some random user's mobile device or laptop than to penetrate a well designed security infrastructure and compromise a proper central database.

You could design the system with a central database that stores only encrypted data and store the user's private key on the user's device.  That way even if the central database is completely compromised, the data is usable only by the user.  Of course, that means that you can't restore the user's data if they lose their key (say the only copy was on their phone and their phone was damaged).  And if someone compromises the key and, presumably, their login credentials, they would be able to see the data.

Title: No central database

Body:
I have a client that is looking to get a website/mobile apps/desktop apps built that deal with very sensitive data (more sensitive than bank/card details). Because of the sensitive nature of the data, they do not want to save it in a central database but they still want their apps to synchronise (let's say I add some data into my mobile app, I then want to be able to go to my desktop app and see the same data).

I cannot think of a nice, reliable way of doing this and I am not sure there is one. Which is why I am here. Does anyone know how I could deal with this data?

One solution I was thinking about was to have a client side database on each app that would somehow sync between apps, I can see this being very unreliable and getting messy though.