答:
There's nothing wrong in using exceptions for that. Even though it might look like a common scenario it must not be as common as not having any validation errors.

Even if the validation fails more often than not, exceptions are still a desirable solution for your problem. If you're worried about performance just don't as every developer knows that premature optimization is the root of all evil.

There are several ways to improve on it though:

Split your method in two, one to validate another to actually do the operation which then moves the responsibility to the caller

Have more specific exceptions (example: InputValidationException, FormatException) so it allows the caller to catch only relevant errors

Throw an exception that contains more than just the error message

Collect all validation errors and throw them as a list inside a ValidationException object allowing the caller to display multiple errors at a time

Based on my experience not using exceptions for validation errors will more likely turn your code into spaghetti in the long run. Specially if you have to handle validation errors that are being generated several levels down the call stack.

Exceptions is the best language tool that allows you to pass information across the entire stack without turning your API design in a huge mess.

Title: How can a method handle validation and entity creation without output parameters?

Body:
I have 3 simple classes.  A Reference, a Parent, and a Child.  The Child knows the Reference and Parent instances it's associated with.  Here they are, initialization and other data/methods omitted:

```<code>class Reference
{
    public int ID { get; private set; }
}

class Parent
{
    public int ID { get; private set; }
}

class Child
{
    public int ID { get; private set; }
    public Reference Reference {get; private set; }
    public Parent Parent {get; private set; }
}
</code>```

Here is a class that maintains collections of them:

```<code>class SetOfThings
{
    private List<Reference> _refs;
    private List<Parent> _parents;
    private List<Child> _children;

    // ...
    // initialization, etc
    // ...
}
</code>```

It enforces constraints like

cannot add a Child unless its Parent and Reference already exists

cannot add a Child if another Child with the same Parent and Reference already exists

and so on.  Currently, the AddChild method enforces the constraints with ArgumentExceptions and returns the new Child with a new unique ID:

```<code>class SetOfThings  // continued
{
    public AddChild(Reference ref, Parent parent)
    {
        if (!_refs.Contains(ref))
            throw new ArgumentException($"{ref} not yet known");
        if (_children.Any(c => c.Parent == parent && c.Reference == ref))
            throw new ArgumentException($"{ref} and {parent} already referenced by a child");

        int newID = MakeNewChildID();
        var newChild = new Child(newID, ref, parent);

        _children.Add(newChild);
        return newChild;
    }
}
</code>```

All of my AddChild calls look like this:

```<code>Child newChild;
try
{
    newChild = AddChild(someReference, someParent);
}
catch (ArgumentException ex)
{
    UI.Alert(ex.Message);
    return;
}

// ...
// Trigger state change, update UI with new child, etc.
// ...
</code>```

However, this feels like an abuse of the exception mechanism.  It isn't really "exceptional" behavior when those ArgumentExceptions are thrown - it's just normal control flow.  But I don't know how to avoid this:

I could return a bool that indicates success/failure and use an output parameter to "return" the new child,

```<code>bool AddChild(Reference r, Parent p, out Child c)
</code>```

but I don't get any indication of why a failure occurred, and output parameters sacrifice readability.

I could return null to indicate a failure.  The method signature wouldn't change, but I still don't know why failures occur.  Moreover, a null reference probably shouldn't be expected behavior any more than exceptions should be.

I could return a custom Notification object (or list thereof) that indicates failures with severity and message strings.

```<code>Notification AddChild(Reference r, Parent p, out Child c)
</code>```

Lots of information, hooray!  But I still need an output parameter. D'oh.

I could return Notification, but construct the Child before passing it into AddChild, and expose the Child.ID property as a public settable so the SetOfThings can change it appropriately.

```<code>var newChild = new Child(someRef, someParent);
var notification = set.AddChild(newChild);
if (/* notification is failure */)
    // change state, discard newChild, display message
else
    // change state, use newChild, etc.
</code>```

But the public settable Child.ID property to make this work is confusing at best, and dangerous at worst.

Am I missing some obvious or common alternative?  I'm not breaking new ground here, but I can't come up with a clear, readable way for a collection class to have creation and validation in the same method.


问:
Is it always the best way to go to queue emails instead of sending them real-time?
If you had to decide between queueing emails and sending them real-time, is it always the best way to go putting them in a queue and sending them one by one instead of instantly as soon as a user sends the request?

Emails are sent using an external service that is Mandrill. Evertime someone submits a specific form in our website, a notification email of the successful operation is sent. These "requests" are then handled in the back office by another team and then another email is sent to the original requester.

We are also going to need to build a marketing email system within the application so that's that.

What I meant by queueing emails (since we are using Mandrill) is queueing the API call to the service instead of sending it non-asynchronously. Since sending the email is not instantaneous, the client awaits until a response from Mandrill is received, instead of handling it with a queue system (like beanstalkd).

Here's a code sample of what I mean.

public function example($id)
{
    [...]

    $Mandrill = \App::make('mandrill');

    $message = $Mandrill->prepareEmail(
        [...]
    );

    $Mandrill->messages->send($message, false, null, null);
}
```

We immediatly send the API request and since the response is not immediate, the request stalls because it is waiting for the API response, that is what I mean by real-time (not sure if that's the correct term maybe?).

What I have shown you above is part of my current application's code base. What I am asking is if it's worth refactoring the code so that the API requests are sent over a queue of items and have a queue manager (with beanstalkd for example) handle them one by one on a separate request behind the scenes.

答:
Since emails are not realtime pr guaranteed delivery there is no obvious benefit to sending them in a blocking manner.  However, it isn't that simple in practice and blocking can have merit.

Go with asynchronous/queueing sending if blocking harms upstream processes.

Go with synchronous/blocking sending if the upstream process needs to know that the attempt to send failed in a trivial way (SMTP unavailable, SMTP authentication failed, etc.).

I would go with async as my default approach and either log failures or have a separate queue for send status that the upstream process or downstream monitoring processes can subscribe to and act on.

ContentLicense: CC BY-SA 3.0


问:
Why Garbage Collection if smart pointers are there
These days, so many languages are garbage collected. It is even available for C++ by third parties. But C++ has RAII and smart pointers. So what's the point of using garbage collection? Is it doing something extra?

And in other languages like C#, if all the references are treated as smart pointers(keeping RAII aside), by specification and by implementation, will there still be any need of garbage collectors? If no, then why is this not so?

答:
Please remember that in the end, everything boils down to a CPU executing instructions.   To my knowledge all consumer grade CPUs have instruction sets which require you to have data stored in a given place in memory and you have pointers to said data.  That's all that you have at the basic level.

Everything on top of that with garbage collection, references to data which may have been moved, heap compaction, etc. etc. is doing the work within the restrictions given by the above "memory chunk with an address pointer" paradigm.  Same thing with smart pointers -  you STILL have to make the code run on actual hardware.

ContentLicense: CC BY-SA 2.5


问:
Sorting algorithm that can handle some error
Suppose you want to sort your movie collection, from favorite to hated. You apply the rules of some sorting algorithm by asking many questions of the form: "Did I like A or B more?"

It's now sorted, right? Logically, every necessary question was asked to prove that when index(A) < index(B), A > B. But you can show that this is false for at least one pair A and B. Surely, the algorithm should have asked more questions.

Opinion is hard to nail down, and if one comparison is off, the whole sorting operation might result in something way off.

Which sorting algorithm would you pick to ensure the sorted list won't be too impacted by a bad comparison?

答:
The key thing here is to avoid making the same comparison more than once. And there is one sort that really meets that criteria in a way that is doable for a human sorting their movie collection.

Merge sort.

With the merge sort, you recursively break down the size of the set to 2 (or 1). And then you sort each of those. Now, you take two sets of 2 (the actual algorithm takes it down to sets of 1, but we're doing this by hand and so can avoid that level of exactness), and then compare the first element of each, of those.  If you have 36 and 24 - you have already compared 3 and 6, you aren't going to compare them again. The resulting set then becomes 2346 and then you continue on merging with the next set of four.

From the wikipedia page:

The key here is that with each comparison, you are not reevaluating the previous comparisons. Thus, if you decide that you like the Yellow Submarine more than the Hard Days Night once, you are not going to re-evaluate that and they aren't going to end up too far from each other in the end.

The problem with many other sorts is that you are either constantly asking "do I like this more than Santa Claus Conquers the Martians" each time with a selection / insert / bubble sort. And other sorts become far too complicated to be able to reason about.

A way to test this that would make for some very interesting blog posts is to implement the different sorts yourself and override > or compareTo in your chosen language.  In that method, add a slight bit of randomness to it, say, +/- 10% of the value. or +/- 1% of the value.

Then, sort the numbers 1 .. 100 100x and see how far out of whack each sorting method results in.


问:
Should one check for every little error in C?
As a good programmer one should write robust codes that will handle every single outcome of his program. However, almost all functions from the C library will return 0 or -1 or NULL when there's an error.

It's sometimes obvious that error checking is needed, for example when you try to open a file. But I often ignore error checking in functions such as printf or even malloc because I don't feel necessary.

```<code>if(fprintf(stderr, "%s", errMsg) < 0){
    perror("An error occurred while displaying the previous error.");
    exit(1);
}
</code>```

Is it a good practice to just ignore certain errors, or is there a better way to handle all the errors?

答:
A bit of an abstract take on the question. And it's not necessarily for the C language.

For larger programs you would have an abstraction layer; perhaps a part of the engine, a library or within a framework. That layer would not care about weather you get a valid data or the output would be some default value: 0, -1, null etc.

Then there's a layer that would be your interface to the abstract layer, that would do a lot of error handling and perhaps other things like dependency injections, event listening etc.

And later you would have your concrete implementation layer where you actually set the rules and handle the output.

So my take on this is that it sometimes is better to completely exclude error handling from a part of code because that part simply doesn't do that job. And then have some processor that would evaluate the output and point to an error.

This is mostly done to separate responsibilities that leads to code readability, and better scalability.


问:
Capturing mobile device system (output) audio
I'm trying to figure out a way to capture the system audio of an Android and/or Windows Phone. The idea is to provide a stream based on the music I'm currently playing on my phone.

What I'm not sure about is what the best approach would be for sending the audio. Preferably I'd like to capture all the device audio (same as when connected to a bluetooth device). But I'm not sure whether this is possible with Android or Windows Phone.

For Android I found this article http://xzpeter.org/?p=254, he states this is'nt possible without making your own Android build. Which isn't an option for me.

For Windows Phone I can only find ways to capture audio from the mic. Not directly from the system.

The only alternative I can come up with is to let the app provide all the audio, meaning I would have to build all the basic mediaplayer functionality into the app. But this would mean I have to put much more work into the app, and I wouldn't be able to use other apps like Winamp and YouTube to provide audio.

Did I maybe overlook a way to capture all the audio of the device? Or maybe there's a way to capture audio from specific applications?

Edit

After doing some more research, I really doubt I can capture all system audio. Or maybe it's possible to simulate an bluetooth audio device?

For the Windows Phone I was going for the alternative solution: selecting songs which would then be streamed to the server. But it seems that for Windows Phone it's not even possible to get physical access to the songs: https://stackoverflow.com/questions/16251400/stream-a-xna-framework-media-song-to-a-server

答:
Use your telephone to listen to what's happening on your PC.

I think that you are going to play music from phone to pc.If so here is an android app that captures all your media sound and streams it to your connected pc with windows operating system running check this website

Sound Wire

: http://soundwire-server.en.uptodown.com/


问:
How to model heuristic uncertainty when sorting data?
Sorting algorithms assume you have a defined comparator. For example, if sorting integers A and B, the A > B operation allows you to determine if A should be after or before B.

Imagine you want to implement a sort, but rather than a defined and consistent comparator, the comparison uses a heuristic of some sense - so it's not a guarantee it will be correct. An example might be analogous to how eye doctors identify your prescription. They show two prescriptions and ask which is better. In some cases, as a patient you might not answer correctly for two close values. For values that are far apart, you will be more accurate.

If for example, you want to compare numeric values, you might model this as a custom comparator like:

```<code>public class HeuristicComparator implements Comparator {

    @Override
    public int compare(double val1, double val2) {
        double adjustedVal1 = val1 + Math.random();
        double adjustedVal2 = val2 + Math.random();

        return Double.compare(adjustedVal1, adjustedVal2);
    }

}
</code>```

In this basic example, I arbitrarily assigning some random variation to the comparison operation, effectively saying that any double values less than 1.000 apart might be sorted incorrectly. 1.5 might be less than 1.3, but only some of the time.

What other strategies are there for modeling heuristic behavior like this rather than a comparator? It seems you could modify the sort logic too (perhaps skip random points, modify a sort to not "finish" all adjacent sorts)?   What sorting algorithms that can be easily modified to match this behavior?

Or would it always be preferable to modify the comparator?

答:
It's only preferable to modify the comparator if you can accept a number as your fuzzy result, and the computation only requires your left and right comparison values.

```<code>public int compare(double val1, double val2) {

    int magic = andThenAMiracleOccurs(val1, val2);

    return magic;
}
</code>```

What could be in andThenAMiracleOccurs?  Almost anything.  An Adaptive Logic Network comes to mind.  Using an ALN would allow you to perform least squares fitting to a curve; the output given the input could be almost any sort of mapping or approximation from input to output.

Of course, functions being what they are, val1 and val2 could be almost anything as well.

```<code>public int compare(Vector set1, Vector set2) {

    int magic = someFuzzyComparator(set1, set2);

    return magic;
}
</code>```

Here's something a little less abstract:

```<code>public int Compare(string string1, string string2)
{
    return SignedLevenshteinDistance(string1, string2);
}
</code>```

which would tell you not only whether two strings were equal, but would also tell you how different they are if they're not equal, and which direction they vary alphabetically.

Comparators can be enormously flexible, under the right circumstances (i.e. anywhere you need some special ordering in a collection that can be modeled on comparing two inputs and producing a signed integer output).

Body:
It's only preferable to modify the comparator if you can accept a number as your fuzzy result, and the computation only requires your left and right comparison values.

public int compare(double val1, double val2) {

    int magic = andThenAMiracleOccurs(val1, val2);

    return magic;
}

What could be in andThenAMiracleOccurs?  Almost anything.  An Adaptive Logic Network comes to mind.  Using an ALN would allow you to perform least squares fitting to a curve; the output given the input could be almost any sort of mapping or approximation from input to output.

Of course, functions being what they are, val1 and val2 could be almost anything as well.

public int compare(Vector set1, Vector set2) {

    int magic = someFuzzyComparator(set1, set2);

    return magic;
}

Here's something a little less abstract:

public int Compare(string string1, string string2)
{
    return SignedLevenshteinDistance(string1, string2);
}

which would tell you not only whether two strings were equal, but would also tell you how different they are if they're not equal, and which direction they vary alphabetically.

Comparators can be enormously flexible, under the right circumstances (i.e. anywhere you need some special ordering in a collection that can be modeled on comparing two inputs and producing a signed integer output).


问:
What are the drawbacks of sending XML to browsers and let them apply XSLT?
Context

Working as a freelance developer, I often made websites completely based on XSLT. In other words, on every request, an XML file is generated, containing everything we need to know about the page content: the name of the user currently logged in, the top menu entries, if this menu is dynamic/configurable, the text to display in a specific area of the page, etc. Then XSL process (caches, etc.) it to HTML/XHTML page to send to the browser.

It has a good point to make it easier to create small-scale websites, especially with PHP. It is a sort of template engine, but which I prefer to other template engines because it's much more powerful than most of template engines, and because I know it better and like it. It is also possible, when need, to give an access to raw XML data on demand for an automated access, without the need to create separate APIs.

Of course, it will fail completely on any medium-scale or large-scale website, since, even with good caching techniques, XSL still degrades overall website performance and requires more CPU serverside.

Question

Modern browsers have the ability to take an XML file and to transform it with an associated XSL file declared in XML like <?xml-stylesheet href="demo.xslt" type="text/xsl"?>. Firefox 3 can do it. Internet Explorer 8 can do it too.

It means that it is possible to migrate XSL processing from the server to the client side for 50% of users (according on browser statistics on several websites where I may want to implement this). It means that those 50% of users will receive only the XML file at each request, thus reducing their and server's bandwidth (XML file being much shorter than its processed HTML analog), and reducing server's CPU usage.

What are the drawbacks of this technique?

I thought about several ones, but it doesn't apply in this situation:

Difficult implementation and the need to choose, based on the browser request, when to send raw XML and when to transform it to HTML instead. Obviously, the system will not be much more difficult then the actual one. The only change to make is to add XSL file link to every XML, and to add a browser check.

More IO and bandwidth usage, since the XSLT file will be downloaded by the browsers, instead of being cached by the server. I don't think it will be a problem, since XSLT file will be cached by the browsers (like images, or CSS, or JavaScript files are cached actually).

Possibly some problems on client side, like maybe problems when saving a page in some browsers.

Difficulty to debug code: it is impossible to obtain an HTML source the browser is actually using, since the only displayed source is the downloaded XML. On the other hand, I rarely go look at HTML code on client side, and in most cases, it is unusable directly (whitespace being removed).

答:
Browsers can't progressively render XSLT

This means that nothing else loads and nothing is displayed until all data and the whole stylesheet is loaded and processed.

You're missing out on progressive rendering and prefetching of images, CSS & JS.

Initial load is delayed by another request

For small-ish files (<20kb) number of requests, not bandwidth, is the bottleneck for front-end performance, and most pages and stylesheets will fall into this category.

If you have large pages, then it's even worse — see the first point.

You probably aren't saving any bandwidth

XSLT itself is quite verbose and might need to contain templates for the whole site and logic for all rare cases, not just the things used on the current page.

You still have to include all data marked up in the main XML file you're sending, e.g. if you're sending a blog post, then there's no magic that XSLT can do to make it substantially smaller. If you're sending complex data, then it'll have lots of markup anyway.

Caches are overrated

Browser caches are not that great:

40-60% of Yahoo!’s users have an empty cache experience and ~20% of all page views are done with an empty cache.

and on mobile, where latency makes extra requests most expensive, caches are even worse.

Check your bounce rate — those are users who don't benefit from cached XSLT, and even pay extra price to download the stylesheet and wait for it to be processed.

gzip is a reverse XSLT

Most transformations done via XSLT come down to changing terse markup to more verbose one and adding repetition. But gzip is great at removing repetition/redundancy from files!

You should be using gzip anyway (it's wasteful to send XML uncompressed). It's very likely that gzipped size of processed document will be about the same as gzipped size of unprocessed XML — but you won't have to send extra XSLT, and browsers will be able to start rendering as soon as first packets arrive.

Clients might be slow

Even assuming best case of loading from cache, XSLT processing on client-side is faster only if user's CPU is faster, and their XSLT engine is faster.

On server-side you can do all kinds of optimisation tricks (e.g., cache processed fragments or even whole pages). You can use latest, fastest XSLT processor (browsers have only XSLT 1.0 and likely not very optimized). And your server probably has beefier CPU than many cheap office computers, phones, etc.


答:
The question is not actually language specific, but rather user specific.  Think about the question from a user perspective.  The user does something, like typing the name of the program on a command line and hitting enter.  What does the user expect?  How can they tell if something went wrong?  Can they afford to intercede if an error occurs?

In many types of code, such checks are overkill.  However, in high reliability safety critical code, such as those for nuclear reactors, pathological error checking and planned recovery paths are part of the day-to-day nature of the job.  It's deemed worth the cost to take the time to ask "What happens if X fails?  How do I get back to a safe state?"  In less reliable code, such as those for video games, you can get away with far less error checking.

Another similar approach is how much can you actually improve on the state by catching the error?  I cannot count the number of C++ programs that proudly catch exceptions, only to just rethrow them because they didn't actually know what to do with them... but they knew they were supposed to do exception handling.  Such programs gained nothing from the extra effort.  Only add error checking code that you think may actually handle the situation better than simply not checking the error code. That being said, C++ has specific rules for handling exceptions that occur during exception handling in order to catch them in a more meaningful way (and by that, I mean calling terminate() to make sure the funeral pyre you have built for yourself lights up in its proper glory)

How pathological can you get?  I worked on a program that defined a "SafetyBool" whose true and false values where carefully chosen to have an even distribution of 1's and 0's, and they were chosen so that any one of a number of hardware failures (single bit flips, data bus traces getting broken, etc.) did not cause a boolean to be misinterpreted.  Needless to say, I would not claim this to be a general purpose programming practice to be used in any old program.

Title: Should one check for every little error in C?

Body:
As a good programmer one should write robust codes that will handle every single outcome of his program. However, almost all functions from the C library will return 0 or -1 or NULL when there's an error.

It's sometimes obvious that error checking is needed, for example when you try to open a file. But I often ignore error checking in functions such as printf or even malloc because I don't feel necessary.

```<code>if(fprintf(stderr, "%s", errMsg) < 0){
    perror("An error occurred while displaying the previous error.");
    exit(1);
}
</code>```

Is it a good practice to just ignore certain errors, or is there a better way to handle all the errors?


问:
Sets Data Structure in Golang
I really like google golang but could some one explain what the rationale is for the implementors having left out a basic data structure such as sets from the standard library?</p>

答: I think this has to do with golang focus on simplicity. sets become really useful with difference, intersection, union, issubset, and so on.. methods. Perhaps golang team felt that it is too much for one data structure. But otherwise a "dumb set" that only has add, contains and remove can be easily replicated with map as explained by @jozefg.

Title: Sets Data Structure in Golang


问:
Mechanisms to ensure distributed systems do not sychchronize (anti-synchronize)
We have a service that based on a local timer does a GET request to our server on Azure to transmit some information to be saved on the server.  At this stage we are only testing and we are finding that some of the clients are synchronizing so they hit the server at the same time.  This seems to be caused due to delays within the azure infrastructure (long story behind that), for example the database is unavailable for a minute or so.  This causes the clients to synch up.

So the obvious answer for us is to introduce some randomness into the clients timer to ensure a reasonably even distribution on our server as the issue is when we go live it will kill our server if lots of clients are synchronized.

How much randomness is required to ensure the even distribution?  Searching turns up lots on synchronization (esp. java) but not tips on the anti-synchronization.

The question comes in two forms:
a) What is the correct terminology for this problem so that I can find either the right domain terms to get the theory behind this>
b) Tips on how to define the amount of randomness other than just guessing and setting up elaborate trial and error testing.

Any help appreciated.

答:
Two approaches come to mind.

Cron allows specifying what amounts to an order of magnitude rather than a specific time. If you need these clients to hit an endpoint on a fixed interval, this may be an attractive solution.

TCP handles collisions through exponential back off, which has the downside that it requires an irregular amount of time to complete. This can be a bit awkward unless your client is written as an asynchronous service. As the current behaviour already induces lag, it's more likely to improve performance than to degrade it.


问:
Data stored in two separate tables, how to select the right table
I have two Tables T1 and T2 in which, where in T1 contains column name 'Year' which saves year information and T2 contains column name as 'P_year' which saves year information.

In the Table T1, I saved some data for the years '2011,2012,2013,2014'. In the Table T2, I am saving the data for the years '2015,2016...and it goes on.

Now, I had developed a common webform to view the results, wherein I placed a dropdown for the year to choose all the years 2011,2012,2013,2014,2015...

And I am confused how to choose...like if the user has selected any particular year, How should I choose the right select statement with the right table...i.e.if the user has selected 2013,then I have to choose select statement related to table T1 and if the user has selected 2015, then I have to choose select statement related to table T2 ?

And if the user doesn't selects the year,How should I display all the data from both tables ?

```<code>if(year == "2011" !!year == "2012"!!year == "2013"!!year == "2014")
{
query1 = "select * from T1 where year ="Selected Year";
}
else if (year == "2015")
{
query2 = "select * from T2 where year ="2015";
}
else
{
query1 = "select * from T1 where year in('2011','2012','2013','2014');
query2 = "select * from T2 where year ="2015";
}
</code>```

So,I can handle the execution in choosing the right query to execute if the user has selected any particular year. But issue rise up, if the user doesn't selects the year, I have to display the data from both tables executing both queries...like I have shown above in the last else statement.

So, Is there any way to write code in a optimized way. Note:- Right here, I am just showing up a single lined query statement,but in real it exists for 5 or 6 lines of select statement.

Anyone please help me out in this regard.

Thanking You.

答:
'2011,2012,2013,2014'
'2015,2016 and so on'

dropdownlist included all Years

convert dropdownlist.selectedValue to int

if(int < 2015)
    query1
else
    query2


问:
Almost every reported bug is a high-priority bug
I have noticed a pattern while working on several software projects: the big majority of the bugs reported had a high/very-high priority. I asked some colleagues about why this may be happening, and they mentioned that if a bug doesn't haven't that level of priority it is very rare that the Bug gets developer attention, which indeed makes sense.

So, I wanted to know if this problem is common or if I just had bad luck. I did a quick Google search, and I found that some teams implement Bug Reporting guidelines or have a separate "Bug Triage" team. If you have faced and solved this issue, what was the approach that worked for you?

This question is specifically about the "Priority Inflation" problem: If you face the scenario and what meassures result effective against this problem.

答: One can add higher and higher priority levels to the system, especially if it is Jira. Giving the new high priorities increasingly silly but dire names can increase the Hawthorne effect bump in the quality of priority choices made by all parties. If the highest priority has a really outlandish name, the effect could be permanent. Eventually when someone chooses a priority, they have to weigh the social consequences of choosing the "bug of death" priority vs. getting it due attention. So, the highest priority is de facto reserved for something that happened to the CTO at home in front of his guests, or other incidents of equivalent visibility. </p>


问:
implementing an extended interface on a concrete class
I don't know if this is a best practices or not. If I have a interface that extends another interface such as :

```<code>public interface A extends B{
    public void something();
};
</code>```

and a concrete class that implements A such as:

```<code>public class MyClass implements A {
    @Override
    public void something(){
        System.out.println("ZOINKS");
    }

    @Override
    public void somethingFromB(){
        System.out.println("Hey, Scoobs!");
    }
};
</code>```

Should I be adding B to the concrete class to identify the other interface?

答:
A extends B means "A is a B". By implementing A, MyClass says "I'm a A, and therefore I'm B".

So, given the Java semantic, it's perfectly right to only (directly) implement the specialized interface. It's clear, and it avoids redundancy.

The only case where a redefinition could be interesting is when you use an interface as a marker (which is probably not such a good idea). It's simpler to get the interfaces directly implemented by a class rather than all the interfaces, including the inherited and extended ones.

Personally, I never 'redeclare' an implementation.


问:
What pain point does Intelligent Children Design Pattern solve?
In absence of this pattern, downcasting is needed in the derived classes. My question is does this pattern solve only the problem of downcasting? And why is downcasting bad compared to the alternative offered by Intelligent Childrean Design Pattern?

答:
Intelligent children is used when there are two base classes at the root of separate but related class hierarchies. For example Widget and WidgetRenderer are the base classes and ListBoxWidget needs to be used by the draw() method of the ListBoxWidgetRenderer. So the draw() method will want to downcast the Widget pointer.

Downcasting is generally frowned on, so every fresh reader will have to be convinced that it's okay in a given situation. With this pattern the right pointer is made available at the right type.


问:
What is a recommended pattern for REST endpoints planning for foresighted changes
Trying to design an API for external applications with foresight for change isn't easy, but a little thought up front can make life easier later on. I'm trying to establish a scheme that will support future changes while remaining backward compatible by leaving prior version handlers in place.

The primary concern on this article is to what pattern should be followed for all defined endpoints for a given product/company.

Base Scheme

Given a base URL template of https://rest.product.com/ I have devised that all services reside under /api along with /auth and other non-rest based endpoints such as /doc. Therefore I can establish the base endpoints as follows:

```<code>https://rest.product.com/api/...
https://rest.product.com/auth/login
https://rest.product.com/auth/logout
https://rest.product.com/doc/...
</code>```

Service Endpoints

Now for the endpoints themselves. Concern about POST,GET,DELETE is not the primary objective of this article and is the concern on those actions themselves.

Endpoints can be broken down into namespaces and actions. Each action must also present itself in a way to support fundamental changes in return type or required parameters.

Taking a hypothetical chat service where registered users can send messages we may have the following endpoints:

```<code>https://rest.product.com/api/messages/list/{user}
https://rest.product.com/api/messages/send
</code>```

Now to add version support for future API changes which may be breaking. We could either add the version signature after /api/ or after /messages/. Given the send endpoint we could then have the following for v1.

```<code>https://rest.product.com/api/v1/messages/send
https://rest.product.com/api/messages/v1/send
</code>```

So my first question is, what is a recommended place for the version identifier?

Managing Controller Code

So now we have established we need to support prior versions we need to thus somehow handle code for each of the new versions which may deprecate over time. Assuming we are writing endpoints in Java we could manage this through packages.

```<code>package com.product.messages.v1;
public interface MessageController {
    void send();
    Message[] list();
}
</code>```

This has the advantage that all code has been separated through namespaces where any breaking change would mean that a new copy of the service endpoints. The detriment of this is that all code needs to be copied and bug fixes wished to be applied to new and prior versions needs to be applied/tested for each copy.

Another approach is to create handlers for each endpoint.

```<code>package com.product.messages;
public class MessageServiceImpl {
    public void send(String version) {
        getMessageSender(version).send();
    }
    // Assume we have a List of senders in order of newest to oldest.
    private MessageSender getMessageSender(String version) {
        for (MessageSender s : senders) {
            if (s.supportsVersion(version)) {
                return s;
            }
        }
    }
}
</code>```

This now isolates versioning to each endpoint itself and makes bug fixes back port compatible by in most cases only needing to be applied once, but it does mean that we need to do a fair bit more work to each individual endpoint to support this.

So there's my second question "What's the best way to design REST service code to support prior versions."

答:
Another approach to handle API versioning is to use Version in HTTP Headers. Like

```<code>POST /messages/list/{user} HTTP/1.1
Host: http://rest.service.com
Content-Type: application/json
API-Version: 1.0      <----- like here
Cache-Control: no-cache
</code>```

You can parse the header and handle it appropriately in the backend.

With this approach the clients need not to change the URL, just the header. And also this makes the REST endpoints cleaner, always.

If any of the client didn't send the version header, you either send 400 - Bad request or you can handle it with backward-compatible version of your API.

Body:
Another approach to handle API versioning is to use Version in HTTP Headers. Like

POST /messages/list/{user} HTTP/1.1
Host: http://rest.service.com
Content-Type: application/json
API-Version: 1.0      <----- like here
Cache-Control: no-cache

You can parse the header and handle it appropriately in the backend.

With this approach the clients need not to change the URL, just the header. And also this makes the REST endpoints cleaner, always.

If any of the client didn't send the version header, you either send 400 - Bad request or you can handle it with backward-compatible version of your API.


问:
Design review of a small configuration framework
I want to create a simple configuration framework. Yes I know, there are many frameworks, which make their job very well. But for interesting in architecture, I want to create my own.

My framework should notice the principles of SOLID
You should be able, to store you configuration in several formats.
As a proof on concept, I've drawed a simple uml.

Everything starts with a simple factory. This factory returns an abstract class called: "Configurator". Within the "Configurator"-class there's a method factory, which returns an interface, called: "IConfigurationSource". The configuration source is just a interface for storing my settings into a file or any different data storage.

Just a example of a xml implementation:

For a new format, I've to create a new class which inherits "Configurator".
You've to override the factory method and return a concrete type of a "IConfigurationSource". In this class, the "IConfigurationSource" will be initialized. I've also to implement a class which inherits "IConfigurationSource" again. This class will provide my data handling into a concrete data storage, in our example a xml file.

At least, a short description of my variables (examples):

component: For each configuration component, I'll provide a separate xml file. That means: "logging, network, users, etc..."

valueName: This is the name of a configuration item. For example: "maxUsersAtTheSameTime"

value: This is the value itself

This is my idea, to create a simple configuration framework. Later I'll implement something like object mapping etc...

Does this design fully support SOLID principles?

答:
Well, everything you described is too abstract to really reason about, but I will try.

I believe you have the following problem. Your Configurator class looks like a in-memory configuration storage, which application will read / write to. But why to tie this to some concrete classes by creating two parallel class instances?

When you talk about configuration, you have two clear responsibilities:

Key-value (may be, tree-like) in-memory configuration storage for
application to read / write to.

Various configuration readers and
writers to save / load configuration from various file formats.

In your case you tie both class hierarchies (Configurator and ConfigurationSource) to file format and I believe this to be excessive. In-memory configuration storage should be format-agnostic.

Such design also makes your factory file-format focused because it should create configuration sources only given, say, resource url to load configuration from (well, let's abstract something a little). No specific Configurator needed here.


答:
If you have this problem where users are assigning ever-higher priority bugs then the only realistic solution is a triage mechanism. All bugs get reported with whatever priority they like, but some poor manager will have to go through every newly reported bug and reset its priority to a sensible level.

After a while your users will either get the message, or you can change the reporting system so that every bug has a default priority. If they want it escalated they will have to contact someone to bump it, which will require some justification. This fact alone will cause 99% of all bugs to be left un-escalated by the user.

Obviously you have more bugs than you can process, so maybe you need to embark on a bug-fix roundup to clear the backlog. This will show the users that their bugs will get fixed without needing them to be marked as super-super-dooper-really-no-honest-this-time-important.

Title: Almost every reported bug is a high-priority bug

Body:
I have noticed a pattern while working on several software projects: the big majority of the bugs reported had a high/very-high priority. I asked some colleagues about why this may be happening, and they mentioned that if a bug doesn't haven't that level of priority it is very rare that the Bug gets developer attention, which indeed makes sense.

So, I wanted to know if this problem is common or if I just had bad luck. I did a quick Google search, and I found that some teams implement Bug Reporting guidelines or have a separate "Bug Triage" team. If you have faced and solved this issue, what was the approach that worked for you?

This question is specifically about the "Priority Inflation" problem: If you face the scenario and what meassures result effective against this problem.


问:
What is internal state and is there a difference between state and internal state
Ok, this question has been asked before, but it's still not clear to me. What exactly is internal state?

So far state is clear to me:
Functions contain behavior, variables have state, values don't. So state typically means the current value or data something like variables contain, simply said, if I'm right. By changing their values, you change their state (if this isn't correct, let me know :)).

But internal state is not very clear to me, it almost seems to me people are mixing up classes and objects: https://stackoverflow.com/questions/21345975/what-is-internal-state

And this definition isn't 100% clear te me either: http://www.cs.nmsu.edu/~rth/cs/cs177/map/intstate.html

So Objects contain internal state, am I right? So the object's state is actually the internal state? So If I have a class:

```<code>class Foo {
    public $aMemberVar = 'aMemberVar Member Variable';
    public $aFuncName = 'aMemberFunc';

    function aMemberFunc() {
        print 'Inside `aMemberFunc()`';
    }
}
</code>```

And I create an object:

```<code>$foo = new Foo;
</code>```

The objects internal state consists of the values $aMemberVar and $aFuncName ?? And the internal state can change, for example by changing:

```<code>$foo->aMemberVar = 'new value';
</code>```

But to be clear, the internal state includes private variables as well? You cannot change them, but they are part of the internal state?

Do I understand this correctly or do I misunderstand something? I'm quite confused cause why should you name it internal state if it's typically just state...

答:
Internal state mainly makes sense as a term to differentiate from externally visible (and possibly directly modifiable) state.

Otherwise state is state. Don't worry about saying internal unless you need to differentiate from external. If you just say "state", it implies all state information unless you make it more specific through context.

Linux has a lot of internal state that it does not share with users. But you can see some external representation of state in tools like top or ps. Trying for a useful analogy.

Yes private members (variables, properties depends on the language) are part of state, as long as the object exists. They are internal, of course.

There's a whole other way to use the term external state, to represent the state of the environment in which the object or system exists. Some people use it this way. Other people just mean object state that is public.


问:
Does the Factory Pattern violate the Open/Closed Principle?
Why does this ShapeFactory use conditional statements to determine what object to instantiate. Dont we have to modify ShapeFactory if we want to add other classes in the future? Why doesnt this violate the open closed principle?

答:
It all depends how you implement it. You can use std::map to hold function pointers to functions creating objects. Then the open/close principle is not violated. Or switch/case.

Anyway, if you do not like the factory pattern, you can always use dependency injection.


答:
The conventional object-oriented wisdom is to avoid if statements and replace them with dynamic dispatch of overridden methods in subclasses of an abstract class. So far, so good.

But the point of the factory pattern is to relieve you from having to know about the individual subclasses and work only with the abstract superclass. The idea is that the factory knows better than you which specific class to instantiate, and you will be better off working only with the methods publishd by the super class. This is often true and a valuable pattern.

Therefore, there is no way that writing a factory class can forego the if statements. It would shift the burden of choosing a specific class to the caller, which is exactly what the pattern is supposed to avoid. Not all principles are absolute (in fact, no principle is absolute), and if you use this pattern you'd assume that the benefit from it is greater than the benefit of not using an if.

Title: Does the Factory Pattern violate the Open/Closed Principle?

Body: Why does this ShapeFactory use conditional statements to determine what object to instantiate. Dont we have to modify ShapeFactory if we want to add other classes in the future? Why doesnt this violate the open closed principle?


答:
It goes a bit like this:

Mgr: what are you working on? Dev: this low priority tasks Mgr : shouldn't you be working on high priority tasks?

Client: when will my bug be fixed? Dev: it's low priority we have high priority tasks. Client: oh, well then set my bug status to high priority.

This will lead to ever escalating levels of priority.
I see you've already gone beyond high priority to very high priority.
What will be next are:

Super High Priority

Ultra High Priority

Very Super Ultra High Priority.

Very Super Ultra Mega High Priority.

etc. etc.

Yes, this is a normal process. As long as there is no cost involved with assigning priority, and the caller has influence, of course they will try get their issue resolved in the fastest way and set the highest priority.

There are basically 2 ways to counter this:

Take control away from the client regarding priority levels.

Associate a cost to the client for elevated priority levels.


答:
If you're talking about the Abstract Factory pattern, the decision making often isn't in the Factory itself but in application code. It's that code that chooses what concrete factory to instantiate and pass around to the client code that will use objects produced by the Factory. See the end of the Java example here : https://en.wikipedia.org/wiki/Abstract_factory_pattern

Decision making not necessarily implies if statements. It could read the concrete Factory type from a config file, derive it from a map structure, etc.


问:
Command pipeline design question - where to place validation?
Here is the situation:

I have a database and a class that is basically a representation of a set of fields of different tables in it. Let's call it Message.
"Message" does not know of the database and whenever I need to synchronize it to DB I use separate functions accepting instances of Message to do it.

Whenever I need to do some operation that involves synchronizing data from "Message" to database,
I do not just call the Modifier1/Modifier2 functions because more often than not, I need to either pass or roll back the whole sequence.
(usually when ORA- DB error occurs)

So, I have a queue of actions set up:

```<code>std::list<std::function<DBType>>
</code>```

In reality there is a wrapper class around this queue that receives actions via signals/slots mechanism and executes the whole accumulated pack of actions on:

```<code>Execute();
</code>```

So, it's like this : if I need to update the database in some piece of code:

```<code>   // sending update #1
   emit dbAction(std::bind<CREATE SOME FUNCTOR HERE>);
   // sending update #2
   emit dbAction(std::bind<CREATE SOME OTHER FUNCTOR HERE>;
   // flushing the queue
   emit flushDb();
</code>```

the actions execute, everyone is happy. End of the story. Until now that is.
Now, I realized I have to have a set of preconditions on "Message" that will prevent these actions from passing through.

Options available:

1) To inject verification code into called functions. But the conditions have nothing to do with them and entirely depend on external context.

2) To let user of the queue to check conditions in outside code. But let's be realistic - even if I am the said user, what's not enforced, is easily forgotten.

3) To use some class to emit these actions after checking preconditions on the arguments. But this will require to update its interface for any new action and will not allow to just send a lambda through.

4) My current insane solution: instead of just sending std::function with already bound arguments, create a templated functor that keeps parameters accessible until they are actually needed by the queue.

```<code>//abstract class so that I can store unrelated template instantiations in a single container in my queue
class  IMessageActionDB
{
  public:
    virtual ~IMessageActionDB();
    enum EActionTypes
    {
          noaction = 0,
      action_type_1 = 1,
      //...
      action_type_N = N
    };

    void operator()(DBType db)
    {
        if(!Verify())
            throw exception;
        BindToExecutable();
        calledFunc(db);
    };
     // will bind whatever is stored in MessageActionDB to the calledFunc
    virtual void BindToExecutable() = 0;
    // will check the action with supplied checker functor
    bool Verify() = 0;

    protected:
    std::function<void(DBType)> calledFunc;
};

// templated action that will accept any function/number of parameters for later use
template<class FunctionType, class ...Ts>
 class  MessageActionDB : public IMessageActionDB
{
  public:
    MessageActionDB(FunctionType f, std::tuple<Ts...> t);

    void BindToExecutable();
    {
        //perform template mumbo jumbo to bind func and parameterPack to calledFunc
        calledFunc = bind_tuple(func, parameterPack)
    }
    bool Verify()
    {
        //call verifiers in order returning if action satisfies or not
        return result;
    };

  private:
     std::tuple<Ts...> parameterPack;
     FunctionType func;
     std::list<std::function<bool(Ts...)>> actionVerifier;
};
</code>```

(Note taht I an still unsure if I want to put verifiers into constructor parameters or let them be generated by a factory singleton in a constructor body)

This way, I can assign verifier for action based on its EActionTypes type, and queue wrapper can use Verify function at invokation time to check if the action is allowed.

Is this sane? Is there a better way/place to inject checking of preconditions?

Quite frankly, my solution feels awkward, I can't shake the feeling that I've done something completely wrong.

答:
Your description sounded a lot like functional approach. But let me try to inject some object orient-ness ;)

From what I've understood so far, you have a simple pipeline which is passed a Message object. Then, depending on some conditions (or unconditionally), some database actions are executed and then the whole operation is committed (or rolled back).

So, I see it like this:

Each action, performed on the database is a Command pattern implementation (DBCommand).

When you need some conditions to be applied to the command execution, you can create a new command, that implements Composite pattern (ConditionalDbCommand). When ConditionalDbCommand's execute() is called, it first verifies the conditions and if they are ok, execute() of inner command is called.

The pipeline can also look like a command. It holds a list of commands to execute and commits/rolls back wrapping transaction.


问:
AutoIncrement Integer Column,Guid or PGuid, which to choose?
Guid has been a Global Unique Identification. Why does "PGuid" (Global Unique Identification) appear?

1) Is Guid NOT PERMENT for unique? (I sometimes wonder whether Guid is REALLY PERMENT generator in .NET or Java)

2) Is "PGuid" just for "easy to read with namespace"? In what kinds of situations can we choose "Pguid" instead of "Guid" (Please offer some MOST DIFFERENCES examples).

3) Since we can use integer column in SQL or in most of db as a unique identifier, why Guid or Pguid? Are there any reasonable things for them?

It would be very nice if you can list each item and explain it in detailled sitations.

Reguards!

PS: I wanna add "Guid" or "Pguid" as a tag for my question, however I didn't find it. Anyone helps to apply it onto my question?

答:
There are two points:

PGUID may stand for Pointer to the GUID, not Permanent GUID. This is a pointer to the beginning of the memory block, where GUID is.

If you really meant Persistent Identifiers, then the difference can be seen as follows. ISBN can serve as a persistent identifier for the book because the book will forever have the same ISBN. If you add database entry about this book, make a mistake, delete an entry and readd again, guid will change. Persistent id will not.


问:
Laravel 5.1 creating model overrides per client
Okay, so I have a Laravel 5.1 project with close to 200 models. This is fine for the core operation of the app, however, in many cases a client may want us to grab something from the database in a special way.

For example, we have a client that wants to calculate the a pension amount slightly different than the normal way.

Is there a design or architecture pattern out there that would allow me to easily switch between client specific model overrides? For example if I am working with "client A" all I do is change a config and it pulls in that clients extensions if they exist but uses the base models if not.

答:
For example, we have a client that wants to calculate the a pension
  amount slightly different than the normal way.

Implement all client-specific calculations on all models as implementations of the Strategy pattern. This way you will be able to quickly swap them.


答:
Introduce a cost to support requests. You can only allow a user to report X number of high priority items in a given period of time, Y number of medium priority items, and Z low priority.

Of course, that also means the dev team and management are going to have to then guarantee that a certain number of these will in fact be fixed - all the high priority items, most of the medium priority items, and (maybe) some of the low priority items within a certain timeframe.

But if this is going to work, management are actually going to have to buy into it, otherwise the whole exercise is a waste of time.

At the end of the day though, your particular situation seems to be a symptom of the a problem that your management aren't allocating enough resources to dealing with support issues. If issues were being dealt with in a timely manner, then I don't think this would be happening.

Something like this was implemented in the first company I worked for as the support process was dysfunctional and led to a situation where if everything is an emergency, nothing is. In our case, after getting the in-house situation under control, the new software development manager put a hard limit on the number of high priority issues a customer could lodge depending on how much they paid in support contracts. If they went over the limit, either they coughed up more cash or the support issue was lowered in priority.


答:
This happens extremely often in large corporations where IT is seen as ancillary, and/or is outsourced. Business people don't understand software and don't care to, all that they care is that "their" bug gets fixed yesterday, regardless of how non-critical it is. They don't realise, or care, that there are a hundred other users also filing bugs, and a team of maybe 5 developers available to fix things.

This is exacerbated by poor management, especially non-IT managers who can't say "no" or who simply let business people set bug priority. (In either case, said manager isn't doing his/her job.) Most managers will prioritise the bug that they were last contacted about because "it's urgent"; the net result is that developers end up jumping from bug to bug, thus fixing a single bug takes longer (context switching), and at the end of the day everyone is unhappy. "When every bug is a high-priority bug, no bugs are high priority."

I've been in this situation, and generally the only way to escape it is to get out. Bug reporting guidelines are always ignored because users don't give a s**t. Attempting to introduce bug triage will either be resisted, or it will be implemented and then ignored the next time a user calls your manager to complain about "their" bug.

Basically, if the developers have no control of the priority, you've already lost.


问:
Java code design for a Geocoder Webservice client
Please bear with me, if this type of question has been asked before. I am having a dilemma with object design and seeking experts' help here to come up with the correct/better design for a webservice client. I am attaching a crude UML diagram below:

I have been writing/fixing Java code, but just getting into object design/architecture. I am writing a webservice client in Java to integrate a commercial Address Validation Geocoding Webservice into our application. Ours is a Tax software written in PowerBuilder running inside EAServer. I am writing the web service client in Java, so it can be integrated with the PB client through CORBA.

I have done a similar service earlier to get some GIS information and this was slightly simpler design handling only XML for both Request and Response. I handled getting/sending request and response in the controller itself.

I started using the same design and hit a road block: current web service handles both XML and REST (through HTTP GET URL); actually, there are 2 webservice urls, the one for Address Validation/Geocoding supports XML or REST, and the other for searching addresses uses REST only. I want to design a generic request abstract class/interface and the controller that can be used for both the services. While trying to come up with the classes, I ran into a classic design issue. Now with Request itself can be a XML string or a URI object (for REST Request), my approach of getting the request and sending it in Controller seems flawed.

Should I make the Request object itself build and send XML/REST itself to the external Service or should I somehow manage to get different types of Requests into the Controller and send it from there (using getRequest, sendRequest)?

Also, I am learning to use Design Patterns in Java. What type of design pattern would be applicable here? I saw command pattern suggested for a similar client. Also, can MVC pattern be applied here?

I just want to get it right, before I started coding.

UPDATE:

My Address Record to send as part of request is,

```<code>public class AddressRecord {
  protected String AddressLine1;
  protected String AddressLine2;
  protected String City;
  protected String State;
  protected String PostalCode;
  protected String Country;
...
}
</code>```

And my request object is,

```<code>public class Request {
  protected AddressRecord  records[];
  protected ArrayList      actions;
  protected ArrayList      columns;
  protected Properties     options;
  protected String         transmissionReference;
  protected String         customerId;
....

}
</code>```

It can have one or addresses (I am planning to send only one for now). It also allows to specify the exact columns needed, actions to be done, Options etc.

And my XMLRequest extends,

```<code>public class RequestXml extends Request {
..
public String buildRequest()
{
...
}
</code>```

And my problem came when I try to do REST Request similarly,

```<code>public class RequestREST extends Request {
..
public URI buildRequest()
{
...
}
</code>```

Depending on the columns chosen, the address will be validated and the service will optionally pass back the Lat/Long for the address, if found. A typical Address Request and Response may contain one or more of the following record (in XML format):

Request record

```<code><Request>
  <Actions>Check</Actions>
  <Columns />
  <CustomerID>1234567890</CustomerID>
  <Options />
  <Records>
    <RequestRecord>
      <AddressLine1>200 Main St</AddressLine1>
      <AddressLine2 />
      <City>Los Angeles</City>
      <PostalCode>90012</PostalCode>
      <State>CA</State>
      <Country>USA</Country>
      <CompanyName></CompanyName>
      <EmailAddress />
      <FirstName />
      <FreeForm />
      <FullName></FullName>
      <LastLine />
      <LastName />
      <PhoneNumber></PhoneNumber>
      <RecordID>1</RecordID>
    </RequestRecord>
    <TransmissionReference />
  </Records>
</Request>
</code>```

Response record:
Will contain validated and standard formatted address record.

```<code><ResponseRecord>
  <AddressLine1>200 Main St</AddressLine1>
  <AddressLine2></AddressLine2>
  <City>Los Angeles</City>
  <State>CA</State>
  <CompanyName></CompanyName>
  <EmailAddress></EmailAddress>
  <NameFull></NameFull>
  <PhoneNumber></PhoneNumber>
  <PostalCode>90012</PostalCode>
  <RecordExtras></RecordExtras>
  <RecordID>1</RecordID>
  <Reserved></Reserved>
  <Results>AS01</Results>
  <AddressExtras></AddressExtras>
  <AddressKey>92688211282</AddressKey>
</ResponseRecord>
</code>```

I am probably stretching it too much. Like @Vladislav suggested, I could probably make buildRequest in URI request also return a String, and that might solve this issue; that can get this job done, but I am trying to learn to do it the proper way of identifying objects and design.

UPDATE2:
@Vladislav, This is what I had for an earlier Webservice client. They called their service GeoQuery, so I named it BoeQueryManager. Does this qualify to be the transport class you are referring to? I think this qualifies to be the Controller. The GeoQuery_MyLAService, generated by WSDL2Java may be the Transport object you referred to? I have redone the diagram, for the new program, to reflect the changes I see per my new understanding of your comments. Can you please validate that?

FYI, our address validation is done in 3-parts - Address
  Validation/Search, Geocode and once we get the Lat/Long, do the
  internal GIS function to get city layers. I already did the 3rd part,
  now working on replacing the 1st and 2nd services.

```<code>public class BoeGeoQueryManager {

  private void init(String aUrlStr) {

    try {
      URL endPoint = new URL(aUrlStr);
      GeoQuery_MyLAService service = new GeoQuery_MyLAServiceLocator();
      geoq = service.getGeoQuery_MyLAcfc(endPoint);
    } catch (MalformedURLException me) {
      logger.error("BOEGIS", "", this.toString() + " - " +  "init", "Error initializing. " + me.getMessage());
      me.printStackTrace();
    } catch (ServiceException se) {
      logger.error("BOEGIS", "", this.toString() + " - " +  "init", "Error initializing Service. " + se.getMessage());
      se.printStackTrace();
    }
  }

  // Search by Address
  public String queryBoeGis(String aAddress) throws Exception {
    BoeXMLRequest lRequest = new BoeXMLRequest(aAddress, 0, 0, GISRequest.SEARCH_MODE_ADDRESS);

    return queryBoeGis(lRequest);

  }

  // Search by Lat/Long
  public String queryBoeGis(double aLatitude, double aLongitude) throws Exception {
    BoeXMLRequest lRequest =
        new BoeXMLRequest(GISRequest.REQUEST_BLANK_ADDRESS, aLatitude, aLongitude,
            GISRequest.SEARCH_MODE_LATLONG);

    return queryBoeGis(lRequest);

  }

  // 3. The controller is doing the Webservice call here. I just pass in
  // the Request object into this. Controller is fully aware it's a XML
  // Request/Response.
  public String queryBoeGis(BoeXMLRequest aRequest) throws Exception {

    String respXML = "";
    String reqXML = "";

    requestCount++;
    try {
      reqXML = aRequest.getXml();

      if (aRequest.isModeLatLong()) {
        respXML = geoq.qByCoords(reqXML);
      } else if (aRequest.isModeAddress()) {
        // search by address (or both)
        respXML = geoq.addressValidationService(reqXML);
      }
      respXML = XMLDocument.cleanup(respXML);
      BoeXMLResponse boeResponse = new BoeXMLResponse(respXML);

      // To be able to get a flattened XML to be sent to the Legacy application
      if (adjustXML)
        respXML = XMLExtractor.getAdjXml(aRequest, boeResponse);

    } catch (Exception e) {
      e.printStackTrace();
      respXML = "";
    }

    // Otherwise, return the original XML
    return respXML;
  }
}
</code>```

答:
You created two parallel class hierarchies: Request with concretes (XmlRequest, JsonRequest etc) and Response with concretes (XmlResponse, JsonResponse etc).

But what I think you have to deal with is a Request / Response as a business entities (Request can be as simple as a string, containing address to geocode for our example, and a Response - an array of two floats - geographic coordinates) and a number of transports (Json, Xml etc.).

Each transport has it's Request and Response encoder / decoder of the original Request object to represent request and response from appropriate web services.

This way you will decouple your business logic from concrete implementations.

Your controller will create a Request object and then, depending on some conditions, choose appropriate transport for it to send / receive data. Transports serialize Request, communicate with external web services, receive and deserialize Response and return it to the controller.

UPDATE:

After seeing your updates above I would like you to check if you need Request class descendants at all. Your request /  response scheme is highly customised depending on the transport. Why not to have a single Transport class hierarchy, which will receive your Request object and return Response?

Transport will handle all URIs or whatever internal protocol details are.

UPDATE 2:

just curious: while learning OO, I keep hearing about making objects
  self contained. This is why I made XMLRequest etc, thinking that's the
  only one that knows about the request.

Well, that's right. It's about SRP actually. If an implementation is very simple, you can assign 'transport' responsibility to a Transport class. If implementation becomes or is planning to become complex, you transform Transport into a module, make facade for it and then assign 'request handler' and 'response handler' responsibilities to classes, inside this module.

When I'm doing OO design, I'm actually trying to keep system understandable and separable at all "zoom" levels: layer -> module -> class -> class member.

I guess your second diagram is much better, but still blurs responsibilities between classes. Controller should create Request object and use some kind of factory to instantiate Transport. In this way, transport details are hidden from controller. It should know about abstract Transport class / module without going into details about its implementation.


答:
At the risk of stating the obvious I'm going to assume there is no bug tracking software that is setting bugs to high priority as default (or has been set to this setting).

I'm afraid, that in the absence of controls, this is the default scenario for multiple teams, clients etc reporting in. If the status quo is being abused then some sort of triage process is definitely in order.

A quick win which I've seen work very well in the past is that P1 (top priority bugs) spawn a plethora of management alerts. If the system has been abused, it is immediately bumped down. Or if it genuinely urgent, a conference call or physical meeting happens to address the issue as soon as possible.

I'm assuming here that you're talking about all bugs not just those from the initial development. If you're typically a green field development gun for hire, then it certainly isn't unusual that most bugs are high priority following the initial alpha release.


答:
I asked some colleagues about what this may be happening, and they
  mentioned that if a bug doesn't haven't that level of priority it is
  very rare that the Bug gets developer attention, which indeed makes
  sense

Actually, if you ask me it does not. The more (used) levels of priority, the more information you have. If you effectively only have one priority, that's the same thing as having no priority at all.

And since you still have the same number of bugs to tackle, and the same amount of manhours in which to do it, it follows that some other heuristic will be used, possibly the null one - "first come, first served". And so you now have a bug priority metric, except that's the time of arrival and no longer under your control.

It can be a symptom of not enough resources being allocated to the bug fixing (there are some policies such as "No new features until the bugs are fixed" that can help there. Joel approves; understanding limits and consequences is a business decision).

In one project I worked, the incoming bugs were accumulated in a "no priority buffer" and every Monday we would review the bug list, estimate difficulty (a very rough estimate; more often than not we just put in, "Average") and sort them by available time. This did tend to bump down the list boring, uninteresting or thought-to-be-hard bugs; to offset that, supervisors and marketing had a certain number of credits per week that they could spend to bump the priority of favorite bugs, and were reimbursed for unsolved bugs (this set a limit on how much a developer-despised bug could be delayed).

It was also possible to merge, cancel and split bugs; I remember one module which was so hopelessly flawed that we sank some twenty or thirty bug reports into a single "rewrite this thing from scratch", which was then split in "clearly state the inputs and outputs of the wretched thing", "write tests to ensure inputs and outputs match the spec", and so on. The last item was "print the old code on recycled paper, bring it out on the lawn and set it on fire" (we did that, too. I remember how good it felt. We took turns on the eulogy; it was quite hilarious).

After some haggling, we had the week's to-do list, which was divided in "will do", "might do" and "can't do" that were bumped to next week. This is where some additional haggling came in: we had say fifty hours to allocate to bugs, and we were 95% sure to fix the first twenty. The management strongly wanted a twenty-first bug to be fixed and had no credits left; we would then offer to swap that bug with one on the "Will do" list, or someone would say "Get me off the FooBazFeature subteam for a couple of days and I'll do it", or we would say "We need more manpower".

The system satisfied no one, really, but this was believed (at least among the developers) to be a good sign.

Some additional negative patterns that turned up were the "Wishful Thinking" on the managers' part ("You stated bug 57212 requires eight hours. That is unacceptable. Make it four") and the "Debug by Fiat" ("Do whatever you want but these forty bugs must be fixed before the big demo next week. You cannot have more time, you cannot have more people"). Also the Boxer Syndrome ("I will work harder"), that tended to work very well for a short time, but usually led to a developer freaking out or leaving for greener pastures.


问:
Does it matter to you that a software is "available source" but not "open source"
You probably know the list of open source licenses officially approved by the OSI. Most notably I guess would be the GPL, MIT, [insert your favorite license here].

I recently ran into a project which although was open source (the creator made all source code available), was not officially open source under one of those official licenses.

It released the source, but made no promise to release the source in the future.

It allowed modification suggestions, but made no promises to accept patches and disallowed external distribution of externally-patched versions.

It allowed the use of the software in commercial or paid projects, but disallowed the sale of the software itself.

I suppose it could be called "available source" not open source as we like to think of it.

I can see why the management team of a company wouldn't want to do business with this software. They can't fork it, they can't sell it, they can't create their own version of the software and distribute it or sell it.

But would it matter to you as part of a software engineering team who's just using this software? I can still get my work done with it, I can use it in a project for which I'm paid (but I can't sell the software itself, which I'm not in the business of doing anyway), and I can make changes to the code to make it behave differently for my needs (but I can't make those modifications public), and if I do want those modifications officially made available to others, the approval is up to the project itself and they choose whether to incorporate them in an official release or not.

So we know that a company that wants to base its business on this "available source" software can't do that, but as someone from the software engineering team, would those differences matter to you or do they seem less relevant?

Curious what others think of this.

答:
To be honest, I don't see why the management team of a company would have problems with using such an "available source" library. As far as integration into their own product is concerned, they can just regard it as a closed-source library.

For me, as a programmer, it does not matter if a library is "open source" or "available source". I prefer not to make local modifications to an external library, because that means an additional maintenance burden. Not only when bugs are found in my local modifications, but also on integrating the modifications again and again when a new release of the library comes out.

The only situations where, IMHO, "open source" beats the "available source" licence outlined in the question is when

the licence of our product also requires disclosure of the sources of contained libraries

we are in the business of producing an enhanced/extended version of the library


问:
How to write unit tests for an application that mostly performs "hard to test" actions?
In my company we develop medical data-acquisition systems. The main functions of each application are:

Interface with data-sampling hardware;

Save/load collected data to/from files on disk;

Perform mathematical analyses (DSP, image processing) to collected data;

Display/plot the information using a graphics-heavy UI;

As far as I know, these are exactely the application areas that most textbooks on unit testing recommend "not to test", or at least that should be left as thin as possible (GUI typically) so that you can test the "true" functionality that has been put elsewhere (say, at the model layers).

I am genuinely commited to raise the quality standards of our software projects, but the nature of our applications, and these counter-indications found on texts about the subject, make me think if that is even possible, and if so, how could I circumvent these limitations.

答:
You mock out the things that you don't want test, and write tests that purely exercise the business logic.

For instance, you don't want to test the file-system read/write code. That is the file system implementer's job. You do want to test that your code transforms data the correct way. Therefore, decouple the data loading from data processing, inject a loader that imports carefully crafted test data, and verify that they are transformed in the expected way. What you're describing is precisely the reason that people recommend the dependency inversion principle so much.


答:
As people have said, this is why the people reporting bugs don't get to assign priority. Your dev team should be in control of their own task assignment (within the scope set by higher management). So, someone further up says "work on this app, fix this feature, make it better at doing this", and the team gets to decide how to go about that, because they're the ones with the technical expertise required to assess how best to achieve what management wants.

The people reporting the bugs should be assigning impact or severity levels, which have defined scope. You can easily call people out for not sticking to agreed levels of severity, because you have material evidence for those levels. For example:

Complete loss of functionality

Partial loss of functionality

Widespread reduction in effectiveness

Localised reduction in effectiveness

Annoyance or hindrance (workaround exists)

Cosmetic

Nobody actually noticed, was found during obscure exploratory test

To start, you can use these levels as a blunt instrument to point out that a misalignment of some title text isn't a Level 1 bug because it's not rendering the entire application unusable. Once they get the idea, you can make it more fine-grained, and start debating whether the glitch in updating this one textbox is a Level 5 because you can fix it by right-clicking in the textbox a few times, or a Level 4 because it's slowing down everyone in Accounting so they get fewer forms processed per hour.

Once you've got useful, measurable information on how bad the bug is for your organisation, assigning priority becomes obvious. Whatever is currently causing the largest problem for the organisation - lost profits, damage to public image, employee unhappiness, whatever - is going to be High Priority, and you work down from there.


问:
Is it safe to directly access superglobals with isset()?
I understand that one should always try to avoid direct access to superglobals to put values from superglobals into variables, eg.:

```<code>$name = filter_input(INPUT_POST, 'name');
//instead of
$name = $_POST['name']; // not safe
</code>```

My question if it is safe to use isset() to test if a superglobal is present, eg:

```<code>if (isset($_POST['name')) {

}
</code>```

I personally do not understand why this would not be good practice, but I am not that advanced in programming.

(Recently I started using Netbeans, and it gives me a tooltip recommending to change this code. Maybe the message is not entirely correct, but I would rather know for sure. I have not found a good answer anywhere else.)

答:
I still am not sure whether or not there is a danger in using isset() on input variables such as $_POST. But I did find that there is a function in PHP made for just this purpose. It is the PHP function filter_has_var().
For more info on filters for input variables, I can also remommend to read more about PHP filter functions</p>


答:
DISCLAIMER: I have not yet had experience with user-reported bug priority shenanigans. I know the question asks for this, but it might help having the perspective of an outsider.

Your problem is not that you have too many high-priority bugs. Your problem is that you have too many people who have direct control over bug priority. If every user can directly assign a priority to their bug, they will almost automatically report their issue as high priority.

You could make it so bug priority has to be configured by a manager or a helpdesk drone, but this could lead to favoritism and social engineering, where a client gets artificially higher priority because of their status or because they know how to craft their messages to make them seem more important. It is also a lot more labor-intensive.

There is a middle ground, where your users have some control over the priority, but in a way that makes it harder to exploit the system. Essentially, you force your users to use a template for reporting bugs. They first select a category:

The program becomes unusable or crashes when I do something.

The program has a graphical defect that affects functionality.

The program does not allow me to do something I should be able to do.

The program allows me to do something I shouldn't be able to do.

The program gives the wrong result when I do something.

The program takes too long to do something.

The program has a graphical defect that does not affect functionality.

The program has a defect that does not fit in one of the above categories.

To give examples:

My iPhone crashes when I receive a message containing Hebrew symbols.

My Android lock screen is rotated in such a way that half of it falls of the screen.

My Android phone sometimes doesn't accept my lockscreen code, even though I entered the right code.

When I try to navigate to PhoneHub.net, my phone redirects me to an adult site.

When I open the Facebook app, it takes a minute to open, even on fast connections and with no other apps running.

Your app has a spelling error.

I found a security defect in your program and would like to report it.

As you can see, each of these errors has a different grade of severity, and the categories are roughly ordered based on this severity. You can then assign each bug a priority based on the category, who reports it and keywords that appear in the description. Bugs in category 7 should get their priority assigned manually.

Note that this can happen fully automatically, and you should let this happen automatically; in fact automation is the key here. Users are prone to overestimating their own importance to the business, so they don't see an issue in reporting their bugs as a higher priority than they should. they're less inclined to deliberately place their bug in a different category, because that requires them to basically lie about the bug.

Users might still enter their bugs in the wrong category of course. The first thing you should do is, from version 1.0, show a friendly message encouraging users to provide accurate information about the bug to help the developers to find and fix it faster. Most users will understand and stop misreporting bugs. Some users might still continue providing wrong information. When that happens, send those users a gentle reminder via mail that accurate information is important and to please not abuse the system. If they continue falsifying records, you give them a warning that they're willfully abusing the system and continued abuse will result in their bugs automatically being assigned a lower category. If they persist, you can adjust their bug multiplier.

You can see parts of this system in place in high-throughput support situations: giant tech companies like Microsoft, Facebook, Google, Gaming companies with a lot of users like Valve and Blizzard, certain governments,... While I'm not sure of the workings behind the scene, you notice that their user-facing support system has a similar interface to what I suggest here, with a strict category system.


问:
Should one check for every little error in C?
As a good programmer one should write robust codes that will handle every single outcome of his program. However, almost all functions from the C library will return 0 or -1 or NULL when there's an error.

It's sometimes obvious that error checking is needed, for example when you try to open a file. But I often ignore error checking in functions such as printf or even malloc because I don't feel necessary.

```<code>if(fprintf(stderr, "%s", errMsg) < 0){
    perror("An error occurred while displaying the previous error.");
    exit(1);
}
</code>```

Is it a good practice to just ignore certain errors, or is there a better way to handle all the errors?

答:
Different safety requirements demand different levels of correctness. In aviation or automobile control software all return values will be checked, cf. MISRA.FUNC.UNUSEDRET. In a quick proof of concept which never leaves your machine, probably not.

Coding costs time. Too many irrelevant checks in non-saftey-critical software is effort better spent elsewhere. But where is the sweet spot between quality and cost? That depends on the debugging tools and the software complexity.

Error handling can obscure control flow and introduce new errors. I quite like Richard "network" Stevens' wrapper functions which at least report errors.

Error handling can, rarely, be a performance issue. But most C library calls will take so long that the cost of checking a return value is immeasurably small.


问:
CQRS and DDD terminology
Since CQRS and DDD do not imply one another I was curious what terms belong to DDD and what terms belong to CQRS. Because the two concepts are so much used together in the literature I usually mix them up.

I came up with this list of the terms that I think go to one camp or the other.

DDD

Domain model

Aggregate (and aggregate root)

Value objects, entities, services

Bounded context

Ubiquitous language

Events?

CQRS

Command (Command Handlers)

Events? (Event Handlers?)

Saga, process managers

Read model / Write model

Projections (different read models)

Eventual consistency

Could anyone correct me (and/or explain), what is where?

答:
Most of the terms belong to both domains because they are intertwined.  In fact, Martin Fowler writes that

CQRS should only be used on specific portions of a system (a
  Bounded Context in DDD lingo) and not the system as a whole.

It is a way to implement a DDD-application and as such will have terms intermingled. Udi Dahan has a good writeup on CQRS and says

Arguably, you could have some commands be processed by transaction script, others using table module (AKA active record), as well as those using the domain model. Event-sourcing is another possible implementation.

If you really want to, you can talk about your domain in DDD terms and avoid talking about saga's, commands and the read/write model in the same way that you can talk about an application without talking about tables and primary keys of the underlying persistence mechanism, but you will occasionally mix the two. I wouldn't really focus on putting the terms in the DDD or CQRS basket...

Title: CQRS and DDD terminology


答:
As as company, you want to solve the issues with the highest importance/cost ratio. Users decides importance, Engineering decides cost. If users assigns the same importance to all bugs, then cost alone matters.

Practically speaking, this means you define priority as importance/cost, and do not allow users or developers to set that priority directly. Neither side has the full picture.

If users decide to rate all issues equally important, that's OK - but it means that engineering (cost) decides what's done. Explain to them that importance is the only way in which they can influence (but not decide) priority.


答:
A few factors...

Often the person report the bug does not know the bigger picture and is unable to decide how significant the bug is.

Often low priority bugs never get triaged or considered, therefore it is better to give a priority that is too high and let the person doing the triage lower it.

As I developer I have often looked at bug report and found that there is a very high priority problem behind the bug, but the product manager doing triage does not care about the bug.

So I think all bug reports need to be looked at QUICKLY by one to two experienced developers, adding their thoughts to the bug report, then the bug needs to be triaged.   Expecting the person that finds the bug to be able to set a useful priority at the point in time when they find it, is just asking too much.


答: In general, unless you have a good reason for not checking that error condition, you should.  The only good reason I can think of for not checking for an error condition is when you can't possibly do something meaningful if it fails.  This is a very hard bar to meet though, because there's always one viable option: exit gracefully.


问:
Temporary Variables or Not: Choose CPU Time or RAM?
In a case where multiple variables are set equal to an operation using the result of an other operation, is it best to create a temporary variable for the result of the second operation (this would save memory) or is it best to create a temporary variable for the result of the second operation (this would save time)?

For example:

```<code>// Option 1 (memory)
totalRevenue += numSold * price;
totalProfit += numSold * price - numSold * cost;
return numSold * price;

// Option 2 (time)
saleRevenue = numSold * price;
totalRevenue += saleRevenue;
totalProfit += saleRevenue - numSold * cost;
return saleRevenue;
</code>```

I understand that this choice, especially in the example above, is rather trivial. My suspicion is that it makes most sense to create the temporary variable, but I can't help feeling that it is a waste. No, memory isn't very scarce these days, but I feel like Option 1 wastes less time than Option 2 does memory. Am I right?

Why choose one way over the other?

答:
This optimization is called common subexpression elimination and is built into nearly all optimizers.

The actual draw back of too many eliminations is register pressure, a.k.a. running out of registers to hold all the temporary values. This could mean spilling the temporary to the stack which may incur a cache miss when reading it back in later and cause a massive slowdown in what should be a function that only does a bit of math. Even if simply recalculating would be faster.

Optimizers can convert in both directions as needed. So don't worry about it too much until profiling indicates that the function is a hotspot.


问:
the future of commercial products
I'm seeing that the open source solutions are growing rapidly & many companies use them now.  What do you think the future for commercial products or solutions will be?</p>

答:
It's good to remember that there are lots of different markets out there. Most coarsely: the individual consumers, and the others.

Commercial solutions are indeed having hard times in the dozenware consumer field. Widely interesting field == lots of open source developers == lots of competition == lots of high-quality free alternatives.

This would already be hard enough to compete against without the additional fact that consumers are extremely price-aware. Even if you ask just $1 for your product, it's too much if someone offers an equivalent product for free. You can only try to compete with some additional services, support and such. The profit margins will be ridiculously small. It's not fun.

Then there's the long tail: specialized niche products. There's way less open source / free competition in fields that are interesting for just a tiny fraction of people, and therefore some money can be made there, even if the markets are much smaller. Need some software for controlling your space shuttle or candy factory? Good luck with finding a free, OS solution! Besides, someone who has a space shuttle hardly needs to think about saving some pennies in software development.

Title: the future of commercial products


答:
The only situation where that style matters is if one or more conditions are true:

The "operation" involves a non-trivial, non-purely-arithmetic function call (such as a database lookup, or a linear/binary search for an element inside an array, etc.), or if you have good reasons to believe that the operation takes more than a fraction of a second,

Or, the result of the operation takes up tens or hundreds of megabytes or more,

Or, if you are using a very inefficient, non-optimizing compiler and targeting a very slow computing platform.

(The list is non-exhaustive and may be amended anytime. Anyone with edit-answer privilege are welcome to edit this list without asking. Thanks for your contributions. check the duplicate question first.)

Title: Temporary Variables or Not: Choose CPU Time or RAM?

Body:
In a case where multiple variables are set equal to an operation using the result of an other operation, is it best to create a temporary variable for the result of the second operation (this would save memory) or is it best to create a temporary variable for the result of the second operation (this would save time)?

For example:

```<code>// Option 1 (memory)
totalRevenue += numSold * price;
totalProfit += numSold * price - numSold * cost;
return numSold * price;

// Option 2 (time)
saleRevenue = numSold * price;
totalRevenue += saleRevenue;
totalProfit += saleRevenue - numSold * cost;
return saleRevenue;
</code>```

I understand that this choice, especially in the example above, is rather trivial. My suspicion is that it makes most sense to create the temporary variable, but I can't help feeling that it is a waste. No, memory isn't very scarce these days, but I feel like Option 1 wastes less time than Option 2 does memory. Am I right?

Why choose one way over the other?


问:
Where should you store/how should you control access to application secrets?
There are these relevant questions questions:

Strategy for keeping secret info such as API keys out of source control?

How do you deal with configuration files in source control?

How to version control config files pragmatically?

But as far as I can tell, they deal with the opposite side of the problem. So yes, we've designed a good application that has no secrets stored in it or its repository. They either pull them from the environment variables or from files stored on the system. Great, awesome, secure, right?

But what about our secrets? Where do they come from? Do we store these in another vcs repository? Do they only exist in an encrypted database?

Obviously we want developers to have their own credential sets - but we're going to need to have credentials for our test/preprod/prod servers.

How do we keep those secure? Of course we want them accessible to the systems that need them...

答: Secrets such as credentials to a database should be kept in a local configuration file, either of your own making, or securely transmitted to you.</p>


问:
Containing the GPL inside an external service?
Not asking for legal advice, just educated intuition.

Lets say a programmer creates a program to provide a service, for instance (hypothetically) face recognition. User logs in, uploads pictures and the program informs their friends that a picture of them was uploaded (or whatever).

Now the programmer finds another GPL software that can greatly enhance the performance of their program by preforming some initial CV analysis. Can the programmer place the GPL software on a private RPC server and have their paid software communicate with that server?

Meaning would that require making the new program GPL aslo?

答:
It's possible that the intent of the GPL could still be enforced here. The FSF does briefly mention this sort of scenario in the the GPL FAQ:

It is essential for people to have the freedom to make modifications
  and use them privately, without ever publishing those modifications.
  However, putting the program on a server machine for the public to
  talk to is hardly “private” use, so it would be legitimate to require
  release of the source code in that special case.

So of course they don't want the GPL undermined in this way but the issue is awkward. It could still be argued that the GPL code that's being hidden, the server wrapper code, and the client code are together a single work that must all be GPL compatible whenever they are propagated. It's not a huge stretch if the sole functionality of the server is to mediate between GPL code and client code that depends on the GPL code and directly interacts with its data structures. No one can know for sure but it's not unthinkable that the FSF could convince a judge that a network is not an impenetrable shield against copyright infringement liability.