答:
Your question seems to equate loose coupling with Design Patterns, but they are really separate, but related things.

Loose coupling is a fundamental concern in programming. As soon as we moved away from machine code and into symbolic languages, programs became loosely coupled with their execution. Etc.

OO itself is basically a model for creating loosely coupled components. Encapsulation makes the internals of objects loosely coupled with other objects. Functional programming maybe even more so, because the function execution is loosely coupled with the execution of other functions in the extreme.

Almost by definition, any design you do is going to involve loose coupling. There are ways you can arrange to have things tightly coupled inadvertently, but I've only seen a few cases where someone actually designed a system to be more tightly coupled.

(Every now and then I work with someone who wants to prevent future developers from making design choices by embedding static references to particular framework artifacts, forcing their use - on purpose. But that's really the exception. Most design revolves around breaking things up for modularity and reuse in lots of contexts.)


问:
Is it necessary to map integers to bits in a genetic algorithm?
From what I've read, genetic algorithms are usually (always?) applied to chromosomes of bits. So if a problem involves maximizing a function that takes integer values, the integers are first encoded as bits.

Is this mapping necessary? It seems that you could take chromosomes of integers and apply crossover and mutation directly. So, if I have a function that takes 35 integer inputs, I can just apply the genetic operators to those integers, rather than on the 35xB bits (where B is the number of bits needed to encode an integer). Is there a reason this isn't done?

Perhaps the algorithm would suffer because the problem is defined more coarsely (that is, a problem can be defined with shorter chromosomes if we're not using bits), but I'm curious if anyone has a better answer.

答:
As long as you have a crossover and mutate, you're in business. The underlying type doesn't matter. I've seen GAs on graph structures where the crossover and mutate operate on graphs directly, adding or combining nodes.

Actually, I usually encode everything to chars and then provide crossover and mutate at the byte level, rather than on bits. Adding a bit mask to take it to the bit level isn't hard, but life is just too short.

OwnerDisplayName: itzy

ContentLicense: CC BY-SA 3.0


问:
Why should one subclass instead of composite when using the Factory Method design pattern?
I'm currently learning about design patterns. I learned about the Factory Method pattern.

This pattern means that in order to implement a factory to create objects, one should subclass the class that needs these objects, and have the subclass create them. This way the superclass only works with more abstract references instead of the concrete implementations the subclass generates, which creates a loosely coupled design.

This usually means the superclass becomes abstract, since it's createObject() method must be abstract so that the subclass containing the factory method will have to implement this method.

Like any factory pattern, this pattern encapsulates the creation of the concrete object, and allows the client to work with a higher level of abstraction. But this specific pattern is built on inheritance.

What I don't understand is - Why would anybody go through all the trouble of subclassing the class that needs a factory and making it abstract? Composition is so much better for this purpose in any way.

It makes much more sense to create an abstract class or an interface called Factory. It would declare one method: createObject(). We create concrete implementations of it for different purposes (WeaponFactory, TitleFactory..) Then, we give the client a Factory member instance factory. This reference is set to whatever concrete Factory is needed at runtime, and the client can simply use factory's createObject() when needed (without having to know what concrete implementation factory is holding).

I don't understand why one would go through the trouble of subclassing a class and making it abstract just for the benefit of allowing it to use a factory in a loosely-coupled manner.

The simple composition-based design I described is better in any way - I think.

Do you agree? Could  you explain why anybody would use the Factory Method Pattern I described?

答:
The Design Patterns book is descriptive, not prescriptive; it describes the patterns the GoF have observed in the wild; patterns that solve problems.

Some problems can be solved in more than one way.

The alternative you describe is also my preferred approach, but it's also described in the book: it's a combination of the Abstract Factory and Strategy patterns. You use an Abstract Factory as a Strategy.

I don't understand why one would go through the trouble of subclassing a class and making it abstract just for the benefit of allowing it to use a factory in a loosely-coupled manner.

For the exact same reason that you would combine Abstract Factory and Strategy. However, the best solution partly depends on your language.

If, for example, you were programming in Eiffel, Factory Method would probably be easier, because Eiffel has multiple inheritance, but (IIRC) no interfaces.

Also, if you're using a language where you can create a derived value on the spot (such as Java or F#), Factory Method might actually be easier than the Abstract Factory/Strategy combo.


问:
Is a genetic algorithm needed when computation is infinitely fast?
From what I understand, genetic algorithms try out multiple variations and evaluate the fitness of each variation. Then they select the best variations, change them a bit and continue the process with the next generation.

But what if we have unlimited computation resources? Can we then just try out all possible variations and evaluate their fitness without resorting to the complex process of breeding new generations? In other words, are genetic algorithms only needed when computation is expensive and when a brute-force method is impossible? Or do they add other benefits as well?

答:
Yes, if computation were free, then you wouldn't need genetic algorithms at all. But remember that this is a huge, huge "if" that none of us will ever live to see!

Still, since you're asking... if computation were infinitely fast, there would be no reason whatsoever not to apply the simplest brute-force combinatorial generate-and-test sledgehammer to a problem. Every question that can be answered with a finite set of information (i.e. a constraint satisfaction problem in the loosest possible sense of that term, which is quite loose indeed) would be instantly solvable; hill climbing, heuristics and all the clever simplifications that we now use to build e.g. a world-class chess engine would simply not be necessary.

Put another way, if computation approaches infinite speed, the decision which approach to use becomes founded on how hard it is to write the computer program to be executed, not how long it takes to actually execute; and that means that it simply isn't worthwhile to invent a more complicated algorithm when the simplest possible will also work and run in the same time.

Arguably, computation has indeed been moving in this direction, but again, remember, that we aren't quite there yet, and probably never will be. (Unless the quantum computer is perfected, of course.)


问:
From a TDD perspective, am I a bad person if I test against a live endpoint instead of a mock?
I follow TDD religiously.  My projects typically have 85% or better test coverage, with meaningful test cases.

I do a lot of work with HBase, and the main client interface, HTable, is a real pain to mock.  It takes me 3 or 4 times longer to write my unit tests than it does to write tests that use a live endpoint.

I know that, philosophically, tests that use mocks should take priority over tests that use a live endpoint.  But mocking HTable is a serious pain, and I'm not really sure it offers much of an advantage over testing against a live HBase instance.

Everyone on my team runs a single-node HBase instance on their workstation, and we have single-node HBase instances running on our Jenkins boxes, so it's not an issue of availability.  The live endpoint tests obviously take longer to run than the tests that use mocks, but we don't really care about that.

Right now, I write live endpoint tests AND mock-based tests for all my classes.  I'd love to ditch the mocks, but I don't want quality to decline as a result.

What do you all think?

答:
I agree completely with the response of guillaume31, never mock types that you don't own!.

Normally a pain in the test (mocking a complex interface) reflect a problem in your design. Perhaps you need some abstraction between your model and your data access code, form example using an hexagonal architecture and a repository pattern its the most usual way to solve this kind of problems.

If you want to do a integration test for checking things do a integration test, if you want to do a unit test because you are testing your logic do a unit test and isolate de persistence. But doing an integration test because you don't know how to isolate your logic from a external system (or because isolating its a pain) its a big smell, you are choosing integration over unit for a limitation in your design not for a real need to test integration.

Take a look to this talk form Ian cooper: http://vimeo.com/68375232 , he talks about hexagonal architecture and testing, he talks about when and what to mock, a really inspired talk that solves many questions like yours about real TDD.


问:
How to reuse spaghetti code
We're working on a new firmware for our new V2 device. The company has an older V1 firmware (and hardware). Hardwares are similar to each other (but there are some differences) so basically we could use V1 firmware with "some" modifications. Unfortunately V1 firmware is spaghetti code. We need to support both hardware including new features, so code should be maintainable.

We've tried to create a backlog with small stories. Each story would show a new working function to the user while it extracts out a reusable part of V1 code to a library project and use it in V2. It would have been kept both V1 and V2 firmwares always releasable and we would have been able to show a working demo early (with limited functionality at first).

In time it turned out that management expects that it will be a short project (since hws are similar) and they suggest another approach: move everything to the library project and modify only those parts which are different. This approach seems riskier because we won't be able to demonstrate any progress (the first demo will be later, it's rather all or nothing, every module has to work more or less for the first demo) and I guess it could lead to unpredictable bug fixing.

What should I take into account before deciding between the two approaches? Is there a third one?

答:
Is there a third one?

If the V2 hardware is "downward compatible" to some degree to the V1 hardware, there might be. Is there a chance to get the V1 firmware running an the V2 hardware with minimal effort, supporting none of the new V2 features? Maybe by adding some "compatibility layer" to the unmodified V1 code? If that's the case, I suggest you try this first - with a limited time frame. If that approach fails, you will have all arguments at your hands to tell your management why your cherry-picking approach will work better.

And if the "take V1 firmware as is" approach works, your management is probably right. The new V2 features have to be added after the "port", and you may have to live with some spaghetti code longer than you like, but instead of refactoring all the code (with the chance of introducing new bugs), you can refactor the pieces you have to change, but not more (which has a much better economic).

Another factor is if you try to create two codebases (for V1 and V2 hardware), which you have to maintain both in the future, or if your new code base for the V2 hardware shall also be able to handle the V1 device (and you want only to have one codebase to maintain or both device versions). If the latter is the case, and you try the "rewrite in small steps" approach, your new code is likely to introduce new bugs to the existing V1 functionality. So you have to test on both kind of devices thoroughly, and may loose existing quality on V1 for the first releases. The new code will also be not really releasable at the beginning (not as a firmware update for existing V1 hardware in production), since it will miss some of the existing, working functionality at the start. On the other hand, reusing the existing V1 code mostly unmodified will you provide you with a production-ready version for V1 from day 1.

Title: How to reuse spaghetti code


问:
Is doing an assignment inside a condition considered a code smell?
Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. Here's one example:

```<code>List<String> currentStrings = getCurrentStrings();
while(currentStrings.size() > 0) {
  doThingsThatCanAlterCurrentStrings();
  currentStrings = getCurrentStrings();
}
</code>```

One things I dislike about this code is the duplicate call to getCurrentStrings(). One option is to add the assignment to the condition as follows:

```<code>List<String> currentStrings;
while( (currentStrings = getCurrentStrings()).size() > 0) {
  doThingsThatCanAlterCurrentStrings();
}
</code>```

But while I now have less duplication and less code, i feel that my code is now harder to read. On the other hand, it is easier to understand that we are looping on a variable that may be changed by the loop.

What is the best practice to follow in cases like this?

答:
The fundamental problem here, it seems to me, is that you have a N plus one half loop, and those are always a bit messy to express. In this particular case, you could hoist the "half" part of the loop into the test, as you have done, but it looks very awkward to me. Two ways of expressing that loop may be:

Idiomatic C/C++ in my opinion:

```<code>for (;;) {
    List<String> currentStrings = getCurrentStrings();
    if (!currentStrings.size())
        break;
    doThingsThatCanAlterCurrentStrings();
}
</code>```

Strict "structured programming", which tends to frown on break:

```<code>for (bool done = false; !done; ) {
    List<String> currentStrings = getCurrentStrings();
    if (currentStrings.size() > 0) {
        doThingsThatCanAlterCurrentStrings();
    } else {
        done = true;
    }
}
</code>```

Body:
The fundamental problem here, it seems to me, is that you have a N plus one half loop, and those are always a bit messy to express. In this particular case, you could hoist the "half" part of the loop into the test, as you have done, but it looks very awkward to me. Two ways of expressing that loop may be:

Idiomatic C/C++ in my opinion:

for (;;) {
    List<String> currentStrings = getCurrentStrings();
    if (!currentStrings.size())
        break;
    doThingsThatCanAlterCurrentStrings();
}

Strict "structured programming", which tends to frown on break:

for (bool done = false; !done; ) {
    List<String> currentStrings = getCurrentStrings();
    if (currentStrings.size() > 0) {
        doThingsThatCanAlterCurrentStrings();
    } else {
        done = true;
    }
}


问:
How to Console.WriteLine from [TestMethod]?
I am trying to show some information from a [TestMethod] method.

Usually we use NUnit and a line with Console.WriteLine runs fine and we can see it in 'output' window, but on this project we must to use Testing tools embebed with VS2010 and Console.WriteLine doesn't run because we cannot see anything.

答:
OK, you have to use Assert and all that, but the other answers don't answer the actual question. Maybe you have your reasons (as I have mine, which is how I found this question).

This might help you a little:

It turns out to see a test’s output, you just double-click on the test
  summary line, and all the output is down at the bottom of that window.
  You get Console.Out messages and (more importantly)
  {Trace,Debug}.WriteLine()

If you're using ReSharper, select your test method in the Unit Test Sessions pane, and the output will be in the Output tab:

In my case, I just needed to quickly test some performance. As I already have a unit test project, it was quicker to do it this way than having to create a new Console Application. So instead of just telling people why their question is wrong, I believe we should tell them why their question is wrong, but still try to answer the question.

Sorry for the rant.


答:
The former code seems more rational and readable to me and the whole loop also makes perfect sense. I'm not sure about the context of the program, but there is nothing wrong with the loop structure in essence.

The later example seems trying to write a Clever code, that is absolutely confusing to me in the first glance.

I also agree with Rob Y's answer that in the very first glance you might think it should be an equation == rather than an assignment, however if you actually read the while statement to the end you will realize it's not a typo or mistake, however the problem is that you can't clearly understand Why there is an assignment within the while statement unless you keep the function name exactly same as doThingsThatCanAlterCurrentStrings or add an inline comment that explains the following function is likely to change the value of currentStrings.

Title: Is doing an assignment inside a condition considered a code smell?

Body:
Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. Here's one example:

```<code>List<String> currentStrings = getCurrentStrings();
while(currentStrings.size() > 0) {
  doThingsThatCanAlterCurrentStrings();
  currentStrings = getCurrentStrings();
}
</code>```

One things I dislike about this code is the duplicate call to getCurrentStrings(). One option is to add the assignment to the condition as follows:

```<code>List<String> currentStrings;
while( (currentStrings = getCurrentStrings()).size() > 0) {
  doThingsThatCanAlterCurrentStrings();
}
</code>```

But while I now have less duplication and less code, i feel that my code is now harder to read. On the other hand, it is easier to understand that we are looping on a variable that may be changed by the loop.

What is the best practice to follow in cases like this?


问:
How many programming languages is a programmer expected to be an expert at?
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.

答:
This is a good question, but I don't think there is a standard. Normally by what I have seen the people are full expert in one high level language (C++, Java, etc. ) in one environment(windows/linux, mac, solaris). They know roughly some other high level language but not fully understand it. (e.g. C++, Java people knows each other roughly). By roughly I mean they can compare the performance of one task in the language they are expert and in the other language. And then they are moderate in some of the scripting language. (e.g. Linux people knows bash, Windows people knows VBA, web people knows PHP).

For me what matters is is the basic algorithm knowledge than the language. If your basics are good, there are less chances to mess up in any language.

But yes, sometimes it may be useful to know what language could be better for what task. e.g the following code is much faster in pascal than in C.

strcat(A,"Hello"); strcat(A,"WOrld");strcat(A,"I say hi!");

This is because Pascal saves the length of the string in the first location and hence it is easy to jump to the last location. In C the string termination is '\0' and hence you will actually have to traverse the whole string for strcat operation.

ContentLicense: CC BY-SA 2.5


问:
What is the word to describe languages that have classes and inheritance?
What is the word used to describe the type of programming languages that provide explicit syntax for defining classes and that support inheritance?

For example: "A ______ language, such as C++, Java, C#, or D."

I keep thinking "object oriented", but that also includes languages like Lua and JavaScript, which aren't quite what I'm thinking of.

I am sure there is a definitive term for this group of languages, I just do not know what it is.

答:
Classes and inheritance are completely orthogonal to OO. There are languages with classes that aren't object-oriented, there are languages with inheritance that aren't object-oriented, there are languages which are object-oriented and have classes but not inheritance, there are languages which are object-oriented and have inheritance but no classes, and there are languages which are object-oriented and have neither inheritance nor classes.

A common term for languages like Smalltalk is "class-based object-oriented language" (which silently implies inheritance between classes). However, this doesn't apply to languages like Java or C#, because here, object-oriented programming isn't done with classes but with interfaces. In Java or C#, classes describe Abstract Data Types, not Objects, interfaces describe Objects. (See On Understanding Data Abstraction, Revisited by William R. Cook)

So, the best you can probably do is "language with class-based inheritance", which is sometimes also referred to as "classical inheritance".


问:
How should I document a multi-tier application?
I have to create a documentation structure for a legacy application, and I'm not sure of how to organize it.
Documentation goals:

List of use-Cases

Program flow for each of the use cases. (Flow-chart of all the logical steps the code does for a particular use-case).

As far as possible explanations of why a certain business/code logic is followed.

Documentation format if possible should not require installing a new tool, and at best be readable in Word or PDF Format (so that the business types can check it easily).

Some questions that should be answerable using the documentation: "What business logic does the code execute for a given use case?";"Is this code redundant elsewhere in the application?"; "If I change this code, what Use-Cases are affected?";

Application characteristics: (it's generally a bit messy, with presentation and business logic slightly mixed in almost every layer)

Presentation in .NET Web Forms using WebControls (GridViews, ObjectDataSource, Reports) and JavaScript(jQuery, jQuery-ui) in *.aspx pages

Server-Side Code in C# in the *.aspx.cs to handle post-back events.

C# Code-Pages and a Seperate Project integrated into the WebApplication supplying Business Logic as part of the Web-Application

SQL Server for data persistence (Master-Data DB, Data Staging DB)

Views including some data from others Servers

C# CLR assemblies for business logic deployed on the SQL Server, and some minor SQL Stored Procedures/Triggers

A File structure on the same server as the SQL DB that handles archiving, data-import from files.

File interface to SAP (that I don't fully understand yet).

So far... I've started documenting in Word. I have a separate Word file for the Front-End and the Database/File Structure. I begin each File with Use-Cases (user-initiated are in the front-end, scheduled jobs in the Database file), followed by the code structure. Each use case has a hyperlink to a flowchart/explanation of the code that first gets executed, which has a hyperlink to the flowchart/explanation of the code that next gets executed, etc... I do this so that each part of code is documented only once, and that other parts of code documentation can link to it if they execute it in the application.

Problems:

I can't navigate backwards from hyperlinks (i.e. I can't answer the question: "If I change this code, what Use-Cases are affected." I can only go from Use-Case to Code, not the other way around.)

The word document already feels clunky and messy after I've barely started to write stuff into it.

Question: How can I document this multi-tier application without making a great mess?

答:
In my experience this big efforts in documentation are a waste of time. Its better to use this time adding new features to the application and value to your business or refactoring the messy parts of the code, a word document usually don't solve any problem in a software application.

I'm not saying that documenting its not necessary or its nor a good thing, but documentation an traceability (the ability to go from code to the user history/use case) must be done in a day to day basis in a project not in a big effort when probably its to late.

Anyway, i prefer to use some shared tool like a wiki, when you are building the next feature for your application write the documentation that you think that can save time for the next guy and only for that part of the application. In this way, you are adding valuable documentation step by step and your (and all the team) learn the habit of revise the documentation in each task. With big documentation efforts is very usual that the final documentation its of little value and sooner than you think its completely useless and out of date because the team don't have the habit of modify the documentation with each new change in the application.

About traceability, use a ticketing tool (like jira, trac, if you use .net microsoft have good tools for this) integrated with your VCS and in each commit include the number of the ticket this commit its related to. Again its a day to day practice that gives you without effort REAL traceability, traceability in a wiki on in a word document its only a illusion.


问:
How much effort should I invest in creating loosely coupled designs?
I am currently learning about design patterns.

I think most people would agree that these patterns are great tools, but should be used with moderation and not as the answer for everything. Using them too much would over-complicate the application with little benefit. Patterns should be used only where they can be the best solution or help in the creation of a good solution (do you agree?).

With this in mind:

The book I'm reading (Head First Design Patterns) frequently emphasizes the importance of loose coupling. This loose coupling is acheived by following principles such as 'program to an interface, not an implementation' and 'encapsulate what varies'.

Basically, most patterns I learned so far exist mostly to allow designs to be loosely coupled, and thus more flexible.

I understand the importance and benefits of loose coupling.

But my question is, how much effort should one actually invest in creating loosely coupled, flexible designs?

Those who oppose design patterns say that the costs to using these patterns often outweighs the benefits. You invest a lot of time in creating a loosely coupled design using some pattern, where in reality - the loose coupling, 'programing to an interface, not an implementation', and all of these principles - might not actually be so important.

What I'd like to know, is how much effort should I actually put in creating additional levels of abstraction and designs, only to allow my application to follow OO principles such as loose coupling, programmign to an interface, etc. Is it really worth it? How much effort should I put in this?

答:
Patterns should be used only where they can be the best solution or help in the creation of a good solution (do you agree?).

I see design patterns strictly as implementation details. If you document your public APIs and program to that documentation, in general it won't matter (or affect you much) where you have design patterns. That is, you don't go "I have a bridge pattern here, and I will implement a visitor on top of it". Instead, it is "this class will have different implementations on various operating systems so it will be implemented using a bridge pattern". Then, when you use it, you are indifferent to it being implemented as a bridge - because you look at the public API, not a bridge pattern.

how much effort should one actually invest in creating loosely coupled, flexible designs?

Loose coupling can be achieved by following a simple set of rules. If you respect these, your code will be (more) loosely coupled, as you write it (i.e. any effort is already part of the development process).

Among the rules (not an exhaustive list):

define your interfaces by thinking (or writing) client code (how the class will be used), not what the class will do (i.e. desing for interface, not implementation)

"tell, don't ask"

construct objects from already created parts

pass into the constructor the actual objects you will use (not factories for the members, parameters for the factories of the parameters, or anything like that).

DRY (if you have two lines that appear in the same order in two places, extract them into a separate function and so on).

If the creation of an object is a more complex operation, implement the creation of the intermediary parts as a factory method/class (i.e. not in the constructor body).

YAGNI (create things as you need them, not before).

These rules are followed differently, depending on language, development methodology followed by your team (e.g. TDD), time budget constraints and so on.

For example, in Java, it is good practice to define your interface as an interface and write client code on that (then, instantiate the interface with an implementation class).

In C++ on the other hand, you do not have interfaces, so you could only write the interface as an abstract base class; Since in C++ you only use inheritance when you have a strong requirement for it (and as such avoid the overhead of unnecessary virtual functions), you will probably not define the interface separately, just the class header).

Those who oppose design patterns say that the costs to using these patterns often outweighs the benefits.

I think they're doing it wrong. If you write loosely coupled (and DRY) code, integrating design patterns into it comes with minimal extra effort. Otherwise, you will have to adapt your code for implementing a design pattern.

If you have to do lots of changes to implement a design pattern, your problem is not the design pattern -- it is your code base being monolithic, and tightly coupled. This is a bad/suboptimal design problem, not a design patterns problem.

What I'd like to know, is how much effort should I actually put in creating additional levels of abstraction and designs, only to allow my application to follow OO principles such as loose coupling, programmign to an interface, etc. Is it really worth it? How much effort should I put in this?

Your questions make the (unstated) assumption that the only benefit of loose coupling is the ability to easily implement design patterns. It is not.

Among the benefits of loose coupling are:

refactoring and redesign flexibility

less wasted effort

testability

increased possibility to reuse the code

design simplicity

less time spent in the debugger

... and a few others that don't come to my mind right now.


答:
The problem with infinitely fast computations is that they infinitely fast cover a state space which is larger than the information limit of our known universe. You mentioned "brute force", however consider that brute forcing chess for example, can produce an output that exceeds in size the number of atoms in the universe.

Taking the example of chess further, as you brute force chess, you have to whittle down the number of chess board combinations you consider and you will have to make a decision which states to keep, and which states to discard - so indeed selective algorithms, such as genetic algorithms, will forever be necessary.

Title: Is a genetic algorithm needed when computation is infinitely fast?

Body:
From what I understand, genetic algorithms try out multiple variations and evaluate the fitness of each variation. Then they select the best variations, change them a bit and continue the process with the next generation.

But what if we have unlimited computation resources? Can we then just try out all possible variations and evaluate their fitness without resorting to the complex process of breeding new generations? In other words, are genetic algorithms only needed when computation is expensive and when a brute-force method is impossible? Or do they add other benefits as well?


答:
First, I would definitely frame the first version as a for-loop:

```<code>for (List<String> currentStrings = getCurrentStrings();
     currentStrings.size() > 0; // if your List has an isEmpty() prefer it
     currentStrings = getCurrentStrings()) {
  ...
}
</code>```

Unfortunately there's no idiomatic way in C++, Java or C# that I know of to get rid of the duplication between initializer and incrementer. I personally like abstracting the looping pattern into an Iterable or Enumerable or whatever your language provides. But in the end, that just moves the duplication into a reusable place. Here's a C# example:

```<code>IEnumerable<T> ValidResults<T>(Func<T> grab, Func<bool, T> validate) {
  for (T t = grab(); validate(t); t = grab()) {
    yield return t;
  }
}
// != null is a common condition
IEnumerable<T> NonNullResults<T>(Func<T> grab) where T : class {
  return ValidResults(grab, t => t != null);
}
</code>```

Now you can do this:

```<code>foreach(var currentStrings in NonNullResults(getCurrentStrings)) {
  ...
}
</code>```

C#'s yield makes writing this easy; it's uglier in Java or C++.

C++ culture is more accepting of assignment-in-condition than the other languages, and implicit boolean conversions are actually used in some idioms, e.g. type queries:

```<code>if (Derived* d = dynamic_cast<Derived*>(base)) {...}
</code>```

The above relies on the implicit conversion of pointers to bool and is idiomatic. Here's another:

```<code>std::string s;
while (std::getline(std::cin, s)) {...}
</code>```

This modifies within the condition.

The common pattern, however, is that the condition itself is trivial, usually relying completely on some implicit conversion to bool. Since collections don't do that, putting an empty test there would be considered less idiomatic.

C culture is even more accepting, with the fgetc loop idiom looking like this:

```<code>int c;
while((c = fgetc(stream)) != EOF) {...}
</code>```

But in higher-level languages, this is frowned upon, because with the higher level usually comes lesser acceptance of tricky code.

Body:
First, I would definitely frame the first version as a for-loop:

for (List<String> currentStrings = getCurrentStrings();
     currentStrings.size() > 0; // if your List has an isEmpty() prefer it
     currentStrings = getCurrentStrings()) {
  ...
}

Unfortunately there's no idiomatic way in C++, Java or C# that I know of to get rid of the duplication between initializer and incrementer. I personally like abstracting the looping pattern into an Iterable or Enumerable or whatever your language provides. But in the end, that just moves the duplication into a reusable place. Here's a C# example:

IEnumerable<T> ValidResults<T>(Func<T> grab, Func<bool, T> validate) {
  for (T t = grab(); validate(t); t = grab()) {
    yield return t;
  }
}
// != null is a common condition
IEnumerable<T> NonNullResults<T>(Func<T> grab) where T : class {
  return ValidResults(grab, t => t != null);
}

Now you can do this:

foreach(var currentStrings in NonNullResults(getCurrentStrings)) {
  ...
}

C#'s yield makes writing this easy; it's uglier in Java or C++.

C++ culture is more accepting of assignment-in-condition than the other languages, and implicit boolean conversions are actually used in some idioms, e.g. type queries:

if (Derived* d = dynamic_cast<Derived*>(base)) {...}

The above relies on the implicit conversion of pointers to bool and is idiomatic. Here's another:

std::string s;
while (std::getline(std::cin, s)) {...}

This modifies within the condition.

The common pattern, however, is that the condition itself is trivial, usually relying completely on some implicit conversion to bool. Since collections don't do that, putting an empty test there would be considered less idiomatic.

C culture is even more accepting, with the fgetc loop idiom looking like this:

int c;
while((c = fgetc(stream)) != EOF) {...}

But in higher-level languages, this is frowned upon, because with the higher level usually comes lesser acceptance of tricky code.


答:
A well-organized Wiki would be my suggestion.  I have used Atlassian Confluence in the past. I believe this is well worth the time spent, especially from the company's perspective.  It does take a lot of time and effort to create, maintain and enforce documentation standards, but after you've had a few senior developers leave a mess of legacy code, you'll be glad you did.

A wiki can be organized like a file folder and can even create index pages for you to allow you create all the linking you need.  Also, the searching in Atlassian is excellent.

For users that are not savvy enough to create pages, just have them create nice Word docs, then import them into the Wiki.

The main thing is to have a well defined structure and enforce documentation standards.  This must have complete buy-in from management to work.  I maintained a wiki for my previous group and it became essential to daily operations because I kept it clean and organized.

Title: How should I document a multi-tier application?

Body:
I have to create a documentation structure for a legacy application, and I'm not sure of how to organize it.
Documentation goals:

List of use-Cases

Program flow for each of the use cases. (Flow-chart of all the logical steps the code does for a particular use-case).

As far as possible explanations of why a certain business/code logic is followed.

Documentation format if possible should not require installing a new tool, and at best be readable in Word or PDF Format (so that the business types can check it easily).

Some questions that should be answerable using the documentation: "What business logic does the code execute for a given use case?";"Is this code redundant elsewhere in the application?"; "If I change this code, what Use-Cases are affected?";

Application characteristics: (it's generally a bit messy, with presentation and business logic slightly mixed in almost every layer)

Presentation in .NET Web Forms using WebControls (GridViews, ObjectDataSource, Reports) and JavaScript(jQuery, jQuery-ui) in *.aspx pages

Server-Side Code in C# in the *.aspx.cs to handle post-back events.

C# Code-Pages and a Seperate Project integrated into the WebApplication supplying Business Logic as part of the Web-Application

SQL Server for data persistence (Master-Data DB, Data Staging DB)

Views including some data from others Servers

C# CLR assemblies for business logic deployed on the SQL Server, and some minor SQL Stored Procedures/Triggers

A File structure on the same server as the SQL DB that handles archiving, data-import from files.

File interface to SAP (that I don't fully understand yet).

So far... I've started documenting in Word. I have a separate Word file for the Front-End and the Database/File Structure. I begin each File with Use-Cases (user-initiated are in the front-end, scheduled jobs in the Database file), followed by the code structure. Each use case has a hyperlink to a flowchart/explanation of the code that first gets executed, which has a hyperlink to the flowchart/explanation of the code that next gets executed, etc... I do this so that each part of code is documented only once, and that other parts of code documentation can link to it if they execute it in the application.

Problems:

I can't navigate backwards from hyperlinks (i.e. I can't answer the question: "If I change this code, what Use-Cases are affected." I can only go from Use-Case to Code, not the other way around.)

The word document already feels clunky and messy after I've barely started to write stuff into it.

Question: How can I document this multi-tier application without making a great mess?


答:
If by "unlimited computation resources" you mean that your algorithm would take 0 time and that memory is unlimited and electricity is of no concern, I would say the only algorithm to use would be a brute force algorithm that tries every possible input and is guaranteed to find the very best one.  If you are referring to unlimited memory but a possible difference in time required, then a genetic algorithm might be preferable because it might come to a solution faster than a brute force algorithm.  But the genetic algorithm's solution might not be optimal, so depending on the context and your requirements you might still prefer the brute force method.

Given that unlimited computation resources is not possible, the question at first seemed like idle speculation.  But as we get more and more computational power, the question becomes more relevant because we may not need genetic algorithms in an age of enormous supercomputers.  However, I have noticed that even as computers become more powerful, we keep asking them to do harder and harder computations with more and more data.  So in the end, I think genetic algorithms will be with us for the foreseeable future and will be used even when a lot of computing power is available.

However, if truly unlimited computation resources ever became available, a lot more would change than whether or not to use genetic algorithms.


问:
What should be the minimal quantity of code production per week?
I'll try to further explain what I mean.

Imagine you are the boss of a company. You have to deal with the tradeoff between the quality of the code and the speed of producing it. Let's assume to measure the coding speed according to Agile Methodologies in Story Points

Let's consider the two extremes:

Our developers spend a lot of time in formation without writing any line of code. They are getting certified. They know about every technology and pattern, they spend hour in thinking how to better implement something but the productivity goes to 0.

Our developers go straightforward to the solution of the problems. They produce a lot of code, they respect the deadlines. But it's really poor quality. A lot of code smells and other problems which will slow down the code in a few time.

It' objective that both the two extremes are not optimal. So what's your suggestion and consideration for finding the optimal tradeoff?

答:
None.

If you start measuring the quantity of code written, this would have negative effect:

If for you, more code is better, developers will start writing more code when it brings nothing useful,

If for you, less code is better, developers would condense the code they write, rendering it barely readable.

Metrics should be used very carefully.

Some of them may be useful when used correctly. This is the case of:

Code metrics,

Code coverage (code covered by tests),

ABCDE-T model of technical debt,

WTFs per minute during code reviews,

Number of reported bugs,

etc.

Some of them should usually be banished, since they do more harm than good most of the time. This is the case of:

LOC,

Number of comments per line of code,

Number of lines of code per file,

Number of commits per day,

etc.

Ask yourself one simple question.

What is more important for you: (A) delighting your customers by shipping features they need early and at a reasonable price, or (B) have more or less code in the code base?


问:
How to maintain trade off between number of columns in table vs join operations?
I have learnt that if there are more columns in table, then get those results using join query.

How to decide the max number of columns in table?

How feasible is "Join Operation" if too many table involved?

And if join operation hurts performance

Can we define all columns in one table to get rid of join operation?

I found many developer telling me that its better to have few extra columns if needed frequently in most database operation than to have multiple tables.

答:
The golden rule for software design: it depends.

The trouble with trying to evaluate it the way you are doing it is that there is insufficient information.  What I have seen work well is to focus on just having a good normalized design (http://en.wikipedia.org/wiki/Database_normalization) and use appropriate indexes for performance, then de-normalize as a last resort as you find performance problems.

For example, our DBA found that after scaling our app up after a decade, a lot of the database's time was spent JOINing to additional tables just to get a single column.  Duplicating a couple of key columns into a couple tables (I think he used a trigger to maintain it, but not sure, wasn't my area) to eliminate a few frequently used JOINs helped improve performance.  It wasn't a huge deal, but imagine if 90% of your queries got 10% faster.  That could be worth it.

Again, this was after 10 years of observing and optimizing.  Don't jump in to this sort of optimization.  Just focus on normalization until you find a compelling reason to de-normalize.

This trade-off you are looking for is way too case-by-case.  There is no specific maximum # of columns that I can tell you is too many.


问:
Should one create underlying architecture to increase flexibility - in advance or when needed?
In this question I asked: Is the cost of designing more levels of abstraction to allow loose coupling worth the benefits, or not?

People said that it's often worth the cost, but one should sense whether his/her application will actually be using this underlying design later on, or if it's just going to be a waste of time.

My new question is:

Should one create the infrastructure to allow flexibility and maintainability in advance - thus making the development 'cleaner' and more 'organized', as things are developed on existing infrastructure and abstraction levels?

With this approach, you desing the underlying infrastructure while not having much knowledge on how things will actually be implemented later. Thus, you might be coding things that might not be used later, and waste your time. But, the development will be cleaner and more organized.

Or should one create infrastructure to increase flexibility and make things more loosely coupled, during the implementation of something - thus wasting less time on things that might not actually be used later?

This approach prevents you from coding things that won't be used, but forces you to design underlying abstraction levels and designs for existing code, thus modifying existing code, instead of coding the underlying designs before coding the code that uses these designs.

Example for approach 1: "Okay, now we start making this relatively large part of the application. This part will generally have to do with reacting to a couple of GUIs. Let's make an underlying level of abstraction for this part of the program, to later use when we implement it."

Example for approach 2: "Okay, I'm in the middle of designing this part of the program. While working on it, I see this part better be loosely coupled. Let's make another level of abstraction to allow it, and modify this code to use that level of abstraction".

Which approach makes more sense, or is more common?

答:
I'd advise against approach 1. Writing code is a process of discovery - just like no plan survives contact with the enemy, every design will have flaws that are only caught once you start implementing it. Besides, you can abstract anything in an arbitrary number of directions and levels. If you design for too many "what-ifs", your architecture won't be aligned with your needs; if taken far enough, you end up with ridiculous things like Greenspun's Tenth Rule or the Inner-Platform Effect (think about it - if everything is customizable, what you'll have left is a programming language.)

On top of that, you're chasing a moving target (changing requirements). Even if you miraculously get the design correct now, there's no guarantee it'll still be relevant later, as you said.

In short, it's a slipperly slope. It doesn't deliver immediate value and there's a good chance it'll steer you in the wrong direction.


问:
Given two sorted array in ascending order with same length N, calculate the Kth min a[i]+b[j]. Time complexity O(N)
Given two sorted array in ascending order with same length N, calculate the Kth min a[i]+b[j]. Time complexity O(N).

Another variant of the question goes like this:
given a matrix with sorted rows, and sorted columns, find kth smallest.

We can easily formulate an O(klogk) solution with minheap, but the challenge is doing the same in O(N) time ...

The paper below formulates the solution but I could not understand it. Can somebody explain it or any alternative idea?

hint: http://www.cse.yorku.ca/~andy/pubs/X%2BY.pdf

答:
If you have a pair of numbers a[i] and b[j] then the next value  will be a[i+1] + b[k] with k<=j or a[k] + b[j+1] with k <= i.

This means that you can get the next number by:

```<code>int newI = i+1;
int newJ = j;
for(;newJ>=0 && a[i]+b[j]<a[newI]+b[newJ];newJ--){}
int newI2 = i;
int newJ2 = j+1;
for(;new2I>=0 && a[i]+b[j]<a[new2I]+b[new2J];new2I--){}
if(a[new2I]+b[new2J]<a[newI]+b[newJ])
    //new2I and new2J are the next values
else
    //newI and newJ are the next values
</code>```

You do this K times, it's not O(n) though.

Body:
If you have a pair of numbers a[i] and b[j] then the next value  will be a[i+1] + b[k] with k<=j or a[k] + b[j+1] with k <= i.

This means that you can get the next number by:

int newI = i+1;
int newJ = j;
for(;newJ>=0 && a[i]+b[j]<a[newI]+b[newJ];newJ--){}
int newI2 = i;
int newJ2 = j+1;
for(;new2I>=0 && a[i]+b[j]<a[new2I]+b[new2J];new2I--){}
if(a[new2I]+b[new2J]<a[newI]+b[newJ])
    //new2I and new2J are the next values
else
    //newI and newJ are the next values

You do this K times, it's not O(n) though.


问:
Why aren't databases integrated as a language feature?
Are there any programming languages that have a built-in database as a first-class language feature rather than connecting to an external SQL (or other) database? What would be the drawbacks and benefits to such a feature? What would such a feature look like and how would it change the way we program?</p>

答: I don't necessarily think the right question is "why aren't there?" but "why should there be?".  What would be gained from having databases be a feature of the language?  Remember, the language is at the very bottom of the programming stack.  Making a language bloated affects everything.  Thus, language designers need to be slow to add new features, especially ones that would involve such an investment.


问:
How can NSObject contain an NSString if NSString is an NSObject
How can NSObject contain an NSString if NSString is an NSObject

```<code>/* NSObject.h
Copyright (c) 1994-2012, Apple Inc. All rights reserved.
*/

(NSString *)description;
</code>```

NSObject has a property named 'description' that is an NSString but isn't NSString an NSObject? How is it that this works?

答:
Not totally sure I understand the issue but i'll try explain. Please comment if i'm way off the mark.

Yes NSObject has an NSString as a property.

Yes NSString is a subclass of NSObject.

There is no issue in doing this. It is somewhat common, under certain circumstances, for a class to have a variable of its own type. Think of singletons for example. These are classes which hold a static copy of themselves to ensure only one can be created.

The difference here is that, NSObject has an NSString so that all its subclasses will. Every object has a description property and its a useful debugging tool, among other things. When printing an object to the console, it will call the description property and pass that as the string value, much like toString() in other languages.

You might possibly be concerned with the fact that, this means NSString has an NSString property. This is true, but calling the NSString's description will simply return the string data. Any attempt to recursively call description will result in the same value being returned.

This is all perfectly valid in the rules of inheritance.


问:
Performance and data retrieving
I'm currently developing a mobile application in Objective C for iOS devices. While doing the application I reach the point where I have to retrieve data from a database and show it on a table (the name of a specific workout routine and his description).

The way I see it I can do this in two ways:

I can select every workout from the database and the associated description, build a collection of objects, send it to the appropriate controller and show in a table all the names, when one is selected I can send the appropriate object to another controller (the one from the next view) and show the appropriate description (this way I just do one operation over the database and manage a lot of objects).

The other way of doing this is just retrieving all the workouts names, when one is selected retrieve the associated description from the database and show it (this way I do two operations over the database but manage a lot of less data and objects in the application).

What I'm concerned about is performance. Is it better to do more operations over the database and manage less information and objects in the application or is it better to do less operations over the database and manage more information and objects? I know that every application is different and one answer can't be applied to everyone of them, but how should I think about it when developing one?

答:
Since the database is on the device (per comments), I would focus my performance concerns on memory management over speed.

Talking to a local database is crazy fast unless you're doing something really unusual (e.g., sequencing DNA, cracking encryption, anything with millions or billions of loop iterations).

You might find the accepted answer to Planning for efficiency early vs Premature optimization helpful.

Long story short, it's not going to matter.

Take the approach that's easiest to maintain and debug.

Title: Performance and data retrieving


问:
why is len not a reserved keyword in python
why is functions like len and max not a reserved keyword in python. Following are the only reserved words http://docs.python.org/2/reference/lexical_analysis.html#keywords

答:
It doesn't make sense to privilege the built in functions like len, str, and so on, because that would require a core language change. To add len and so on to the core language would require changes to the parser to recognize and reject changes to them. And adding parser changes can be quite risky for a very small benefit, and it could also impact performance.

When on the other hand, it keeps the language clean and simple, and enables useful edge cases, for example redefinitions of len, etc. While this might scare you, I guarantee you it was useful to someone somewhere.

If you're paranoid that someone overwrote len, you can always do the following:

```<code>from __builtins__ import len as SUPERSECURELEN
</code>```

You cannot modify the builtins module. So its safe.

Body:
It doesn't make sense to privilege the built in functions like len, str, and so on, because that would require a core language change. To add len and so on to the core language would require changes to the parser to recognize and reject changes to them. And adding parser changes can be quite risky for a very small benefit, and it could also impact performance.

When on the other hand, it keeps the language clean and simple, and enables useful edge cases, for example redefinitions of len, etc. While this might scare you, I guarantee you it was useful to someone somewhere.

If you're paranoid that someone overwrote len, you can always do the following:

from __builtins__ import len as SUPERSECURELEN

You cannot modify the builtins module. So its safe.


答: A box can have another box in it. A linked list node often refers to another list node, for example, to make a list. The box inside it may be empty (null). Slightly breaking the comparison, in code, the box inside can specify itself as the box inside it as well (a this reference in Java). So it really isn't an issue. It would only be an issue if each object had a different, non-null string, since that would be infinite.</p>

Body:
How can NSObject contain an NSString if NSString is an NSObject

```<code>/* NSObject.h
Copyright (c) 1994-2012, Apple Inc. All rights reserved.
*/

(NSString *)description;
</code>```

NSObject has a property named 'description' that is an NSString but isn't NSString an NSObject? How is it that this works?


问:
What are the use cases for these relationship types?

Use Case

What are the use cases for creating a one-to-one relationship where the parent points to the child compared to a child pointing to the parent? If there is no difference, is one preferred over the other?

Example

```<code>+---------+     +-------+       +--------+     +----------+
+ Parent  +     + Child +       + Parent +     + Child    +
+---------+     +-------+  vs.  +--------+     +----------+
+ idChild + --> + id    +       + id     + <-- + idParent +
+---------+     +-------+       +--------+     +----------+
</code>```

I suspect that you'd choose between these relationships depending on which entity is used first in the application. i.e. If the parent object always appears before the child object, then the relationship should be mapped from the parent to child.

答: I was working on a software project with one-to-one relationships, in our project was the child pointing on the parent, because it just is more logical, that the child shows its parent and not other way round.


答:
The only language that I can think of is the old xBase languages like DBase, Clipper and FoxPro. There is a GNU project that offers a free and mostly compatible version called Clip

The was also Pick Basic which tied a programming language directly to an database platform.

This has been done. It was an evolutionary dead end that limited how a language could access data.

Title: Why aren't databases integrated as a language feature?

Body: Are there any programming languages that have a built-in database as a first-class language feature rather than connecting to an external SQL (or other) database? What would be the drawbacks and benefits to such a feature? What would such a feature look like and how would it change the way we program?</p>


问:
Should I include myself as an author after modifying 3rd-party code?
It's common practice to make some tweaks or fixes in 3rd-party code (be it a simple gist or an entire library). But it's also common that many of these code have their own licensing rules and eventually a header on every file with copyright informations.

After making those modifications what's the correct thing to do next? Keep the licence info untouchable or try to update it including yourself with something like @author or @revision tags?

Another common problem is changing the 3rd-party namespace/package to fit it to your project conventions. Some license types include these kind of information in their license block, can I change it freely?

I know the answer for these questions depends on each license type, so to make my question more specific...

Considering general license rules (usually they are different in minor aspects, right?), is ethical(or at least allowed) that I freely add information to the license block about my modifications and perhaps also modify how do I refer to it in my code (e.g use YACorp.YALib as Utils.YALib)?

答:
After making those modifications what's the correct thing to do next? Keep the licence info untouchable or try to update it including yourself with something like @author or @revision tags?

I think you're confusing the software license and any prologue that might be part of the software.

The license is where the owners of the copyright to the program specify the terms of use (the license) for other people.  Some licenses are very permissive, others are much more restrictive.

The prologue is where authors insert @author and @revision tags to provide a way to track changes to the source code.  In some cases, becoming an author of a non-trivial addition to the code may give you claim to the copyright over that section of the code.  Disentangling copyright concerns can be thorny and is best handled by attorneys.  However, you specifically stated you're not concerned with that aspect so I'll move on.

Another common problem is changing the 3rd-party namespace/package to fit it to your project conventions. Some license types include these kind of information in their license block, can I change it freely?

This really depends upon the conventions of the project.

If you fork the project, you can do whatever you want.

If you plan on contributing your changes back to the project, you should stick with the established convention.  If there's a compelling reason to change the namespace then you need to present that to the application's community.

Considering general license rules (usually they are different in minor aspects, right?),

is ethical(or at least allowed) that I freely add information to the license block about my modifications and perhaps also modify how do I refer to it in my code (e.g use YACorp.YALib as Utils.YALib)?

Don't change the license!

First off, you likely do not have the legal rights to change the license.  Second, any changes you make are likely going to mess up the license.  Leave license changes to the attorneys.

As far as updating the prologue, it depends upon project norms.  Some projects don't want a prologue because they use source control to track that.  Other projects do.  Follow the project's conventions.

Actualy my concerns are more about "respect to the community" than the legal aspects, I'm asking more about how much we can "go wild" remaining ethical if our project can be considered private or personal.

If you're keeping your changes to yourself, why do you care what others think?  Something that you use only for yourself and never distribute to others has no impact back upon the original project.  So they don't care what you do.

If you plan on distributing your changes or contributing them back to the project, you need to evaluate the conventions of that project.  Some projects don't want to be forked and will have a license in place preventing that.  Others go so far as to say "do what you want" and you're given carte blanche to do as you see fit.  Ultimately, the answer here depends upon the particular project you're looking at.

ContentLicense: CC BY-SA 4.0


答: In terms of database design is quite more logical to have the child store the relationship back to the parent. Primarily, because keeping the information for each child in the parent's is inflexible (assuming you use fields for child's IDs), like in your first example, since you cannot dynamically allocate more than a single reference to a child.</p>

Title: What are the use cases for these relationship types?

Body:
Use Case

What are the use cases for creating a one-to-one relationship where the parent points to the child compared to a child pointing to the parent? If there is no difference, is one preferred over the other?

Example

```<code>+---------+     +-------+       +--------+     +----------+
+ Parent  +     + Child +       + Parent +     + Child    +
+---------+     +-------+  vs.  +--------+     +----------+
+ idChild + --> + id    +       + id     + <-- + idParent +
+---------+     +-------+       +--------+     +----------+
</code>```

I suspect that you'd choose between these relationships depending on which entity is used first in the application. i.e. If the parent object always appears before the child object, then the relationship should be mapped from the parent to child.


问:
Logging page/session ID in an inner module
We have a C# ORM module that generates queries. It logs generated queries and other information into the error/trace file. It is used by our web application. Most of our queries are generated dynamically (based on dynamic business rules and user interactions) which we have little control over.

Obviously the ORM module is completely decoupled from the web application, and therefore completely unaware of web sessions, page hits etc. The downside is that the log entries it generates cannot be traced back to the original page hit. When we notice a non-performant query in the log, we cannot easily determine which page hit generates that query.

How can I keep the ORM module decoupled from the web application, but still allow it to log enough relevant information for me to correlate each log entry to a session/page hit?

(I know we can pass the logger object around, and the logger object can preserve that session information. However, some of these function calls are nested 10 levels deep, so passing the logger around is cumbersome).

答: Make the logger globally available, so you don't have to pass it around. If you have more than one logger (maybe one per session), you need to make it "globally within the session context". For example, you could provide a global "logger repository" which holds a reference to each active logger and lets you access them by the session id, or some other context id. The one thing you need here is some kind of id which is available through all the layers of your application. It is hard to give you a more specific advice without actually knowing more about your code.</p>


问:
Is doing an assignment inside a condition considered a code smell?
Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. Here's one example:

```<code>List<String> currentStrings = getCurrentStrings();
while(currentStrings.size() > 0) {
  doThingsThatCanAlterCurrentStrings();
  currentStrings = getCurrentStrings();
}
</code>```

One things I dislike about this code is the duplicate call to getCurrentStrings(). One option is to add the assignment to the condition as follows:

```<code>List<String> currentStrings;
while( (currentStrings = getCurrentStrings()).size() > 0) {
  doThingsThatCanAlterCurrentStrings();
}
</code>```

But while I now have less duplication and less code, i feel that my code is now harder to read. On the other hand, it is easier to understand that we are looping on a variable that may be changed by the loop.

What is the best practice to follow in cases like this?

答:
Duplication is like medicine.  It's harmful in high doses, but can be beneficial when appropriately used in low doses.  This situation is one of the helpful cases, as you've already refactored out the worst duplication into the getCurrentStrings() function.  I agree with Sebastian, though, that it's better written as a for loop.

Along those same lines, if this pattern is coming up all the time, it might be a sign that you need to create better abstractions, or rearrange responsibilities between different classes or functions.  What makes loops like these problematic is they rely heavily on side effects.  In certain domains that's not always avoidable, like I/O for example, but you should still try to push side effect-dependent functions as deep into your abstraction layers as possible, so there aren't very many of them.

In your example code, without knowing the context, the first thing I would do is try to find a way to refactor it to do all the work on my local copy of currentStrings, then update the external state all at once.  Something like:

```<code>for(String string: getCurrentStrings()) {
    doSomething(string);
}
clearCurrentStrings();
</code>```

If the current strings are being updated by another thread, an event model is often in order:

```<code>void onCurrentStringAdd(String addedString) {
    doSomething(addedString);
}
</code>```

You get the picture.  There's usually some way to refactor your code to not depend on side effects as much.  If that's not practical, you can often avoid duplication by moving some responsibility to another class, as in:

```<code>CurrentStrings currentStrings = getCurrentStrings();
while (!currentStrings.empty()) {
    currentStrings.alter();
}
</code>```

It might seem like overkill to create a whole new CurrentStrings class for something that can be mostly served by a List<String>, but it will often open up a whole gamut of simplifications throughout your code.  Not to mention the encapsulation and type-checking benefits.

Body:
Duplication is like medicine.  It's harmful in high doses, but can be beneficial when appropriately used in low doses.  This situation is one of the helpful cases, as you've already refactored out the worst duplication into the getCurrentStrings() function.  I agree with Sebastian, though, that it's better written as a for loop.

Along those same lines, if this pattern is coming up all the time, it might be a sign that you need to create better abstractions, or rearrange responsibilities between different classes or functions.  What makes loops like these problematic is they rely heavily on side effects.  In certain domains that's not always avoidable, like I/O for example, but you should still try to push side effect-dependent functions as deep into your abstraction layers as possible, so there aren't very many of them.

In your example code, without knowing the context, the first thing I would do is try to find a way to refactor it to do all the work on my local copy of currentStrings, then update the external state all at once.  Something like:

for(String string: getCurrentStrings()) {
    doSomething(string);
}
clearCurrentStrings();

If the current strings are being updated by another thread, an event model is often in order:

void onCurrentStringAdd(String addedString) {
    doSomething(addedString);
}

You get the picture.  There's usually some way to refactor your code to not depend on side effects as much.  If that's not practical, you can often avoid duplication by moving some responsibility to another class, as in:

CurrentStrings currentStrings = getCurrentStrings();
while (!currentStrings.empty()) {
    currentStrings.alter();
}

It might seem like overkill to create a whole new CurrentStrings class for something that can be mostly served by a List<String>, but it will often open up a whole gamut of simplifications throughout your code.  Not to mention the encapsulation and type-checking benefits.


问:
Why were default and static methods added to interfaces in Java 8 when we already had abstract classes?
In Java 8, interfaces can contain implemented methods, static methods, and the so-called "default" methods (which the implementing classes do not need to override).

In my (probably naive) view, there was no need to violate interfaces like this. Interfaces have always been a contract you must fulfill, and this is a very simple and pure concept. Now it is a mix of several things. In my opinion:

static methods do not belong to interfaces. They belong to utility classes.

"default" methods shouldn't have been allowed in interfaces at all. You could always use an abstract class for this purpose.

In short:

Before Java 8:

You could use abstract and regular classes to provide static and default methods. The role of interfaces is clear.

All the methods in an interface should be overriden by implementing classes.

You can't add a new method in an interface without modifying all the implementations, but this is actually a good thing.

After Java 8:

There's virtually no difference between an interface and an abstract class (other than multiple inheritance). In fact you can emulate a regular class with an interface.

When programming the implementations, programmers may forget to override the default methods.

There is a compilation error if a class tries to implement two or more interfaces having a default method with the same signature.

By adding a default method to an interface, every implementing class automatically inherits this behavior. Some of these classes might have not been designed with that new functionality in mind, and this can cause problems. For instance, if someone adds a new default method default void foo() to an interface Ix, then the class Cx implementing Ix and having a private foo method with the same signature does not compile.

What are the main reasons for such major changes, and what new benefits (if any) do they add?

答:
A good motivating example for default methods is in the Java standard library, where you now have

```<code>list.sort(ordering);
</code>```

instead of

```<code>Collections.sort(list, ordering);
</code>```

I don't think they could have done that otherwise without more than one identical implementation of List.sort.

Body:
A good motivating example for default methods is in the Java standard library, where you now have

list.sort(ordering);

instead of

Collections.sort(list, ordering);

I don't think they could have done that otherwise without more than one identical implementation of List.sort.


答:
Perhaps the intent was to provide the ability to create mixin classes by replacing the need for injecting static information or functionality via a dependency.

This idea seems related to how you can use extension methods in C# to add implemented functionality to interfaces.

Title: Why were default and static methods added to interfaces in Java 8 when we already had abstract classes?

Body:
In Java 8, interfaces can contain implemented methods, static methods, and the so-called "default" methods (which the implementing classes do not need to override).

In my (probably naive) view, there was no need to violate interfaces like this. Interfaces have always been a contract you must fulfill, and this is a very simple and pure concept. Now it is a mix of several things. In my opinion:

static methods do not belong to interfaces. They belong to utility classes.

"default" methods shouldn't have been allowed in interfaces at all. You could always use an abstract class for this purpose.

In short:

Before Java 8:

You could use abstract and regular classes to provide static and default methods. The role of interfaces is clear.

All the methods in an interface should be overriden by implementing classes.

You can't add a new method in an interface without modifying all the implementations, but this is actually a good thing.

After Java 8:

There's virtually no difference between an interface and an abstract class (other than multiple inheritance). In fact you can emulate a regular class with an interface.

When programming the implementations, programmers may forget to override the default methods.

There is a compilation error if a class tries to implement two or more interfaces having a default method with the same signature.

By adding a default method to an interface, every implementing class automatically inherits this behavior. Some of these classes might have not been designed with that new functionality in mind, and this can cause problems. For instance, if someone adds a new default method default void foo() to an interface Ix, then the class Cx implementing Ix and having a private foo method with the same signature does not compile.

What are the main reasons for such major changes, and what new benefits (if any) do they add?


答: Adding database into a programming language might cater only to a very narrow set of users.  What if they want to use some non RDBMS features? Or don't want to use a database at all?  The compiler will unnecessarily be bloated for such use cases.</p>


问:
Is better Show() + Hide() or SetVisible(bool visible)?
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions

答:
I prefer SetVisible(bool visible), because it lets me write client code like this:

```<code>SetVisible(DetermineIfItShouldBeVisible());
</code>```

instead of having to write

```<code>if (DetermineIfItShouldBeVisible()) {
    Show();
} else {
    Hide();
}
</code>```

The SetVisible approach may also allow for easier implementation.  For example, if a particular concrete class simply delegates the method to its composite classes, then SetVisible means one less method to implement.

```<code>void ButtonWithALabel::SetVisible(bool visible) {
    myButton.SetVisible(visible);
    myLabel.SetVisible(visible);
}
</code>```

Body:
I prefer SetVisible(bool visible), because it lets me write client code like this:

SetVisible(DetermineIfItShouldBeVisible());

instead of having to write

if (DetermineIfItShouldBeVisible()) {
    Show();
} else {
    Hide();
}

The SetVisible approach may also allow for easier implementation.  For example, if a particular concrete class simply delegates the method to its composite classes, then SetVisible means one less method to implement.

void ButtonWithALabel::SetVisible(bool visible) {
    myButton.SetVisible(visible);
    myLabel.SetVisible(visible);
}


问:
Why can't the Factory Method pattern create a family of objects?
There are two main differences between the design patterns Factory Method and Abstract Factory.

Difference 1 is that Factory Method is mainly based on inheritance. A class in a way uses it's subclass to create objects. The objects created depend on the subclass used. While Abstract Factory is based on inheritance but in a way also on composition - A client 'owns' an Abstract Factory instance to hold a concrete factory.

Difference 2 is that Factory Method creates one object, while Abstract Factory creates a family of related objects.

Difference 1 I understand (although I'm having trouble understanding why anyone would prefer to subclass a class that needs a factory instead of just 'giving' it a factory using composition [unless that class already has a subclass]).

But difference 2 I don't understand.

Why can't Factory Method create a family of products instead of one product? It can certainly return an array of products of the same family. All of these products share a common interface - the method can return an array of that type. Why is it said that this method only produces one product?

Additionally, a factory method inside a concrete subclass of an abstract factory creates different products using different methods that are called by the client.

Why can't a concrete factory in the Factory Method pattern do the same? Have different factory methods for different products?

答:
You need to understand that the Factory Method refers to the functionality of a factory, whereas the Abstract Factory refers to the functionality of a factory of factories. The answer linked by @pdr further expands on this point.

To directly address your main concern,

Difference 2 is that Factory Method creates one object, while Abstract Factory creates a family of related objects.

The Factory Method returns a single implementation for the required functionality, i.e. it returns a FinancialManager or a OperationsManager to satisfy the need for an IManager.

An Abstract Factory will return a factory that then provides you with actual implementations, i.e. it returns a FinancialFactory or an OperationsFactory as the implementation for an IProfessionalFactory. Each of these implement their own version of BuildManager() -> IManager; however, they could also implement other methods to build a family of related objects, like BuildEngineer() -> IEngineer or BuildAssistant() -> IAssistant, each returning a financial- or operations-related implementation based on whether you use a FinancialFactory or an OperationsFactory.


答:
Because you can only inherit one class. If you've got two interfaces whose implementations are complex enough that you need an abstract base class, those two interfaces are mutually exclusive in practice.

The alternative is to convert those abstract base classes into a collection of static methods and turn all the fields into arguments. That would allow any implementor of the interface to call the static methods and get the functionality, but it's an awful lot of boilerplate in a language that's already way too verbose.

As a motivating example of why being able to provide implementations in interfaces can be useful, consider this Stack interface:

```<code>public interface Stack<T> {
    boolean isEmpty();

    T pop() throws EmptyException;
 }
</code>```

There's no way to guarantee that when someone implements the interface, pop will throw an exception if the stack is empty. We could enforce this rule by separating pop into two methods: a public final method that enforces the contract and a protected abstract method that performs the actual popping.

```<code>public abstract class Stack<T> {
    public abstract boolean isEmpty();

    protected abstract T pop_implementation();

    public final T pop() throws EmptyException {
        if (isEmpty()) {
            throw new EmptyException();
        else {
            return pop_implementation();
        }
    }
 }
</code>```

Not only do we ensure all implementations respect the contract, we've also freed them from having to check if the stack is empty and throwing the exception. It's a big win!...except for the fact that we had to change the interface into an abstract class. In a language with single inheritance, that's a big loss of flexibility. It makes your would-be interfaces mutually exclusive. Being able to provide implementations that only rely on the interface methods themselves would solve the problem.

I'm not sure whether Java 8's approach to adding methods to interfaces allows adding final methods or protected abstract methods, but I know the D language allows it and provides native support for Design by Contract. There is no danger in this technique since pop is final, so no implementing class can override it.

As for default implementations of overridable methods, I assume any default implementations added to the Java APIs only rely on the contract of the interface they were added to, so any class that correctly implements the interface will also behave correctly with the default implementations.

Moreover,

There's virtually no difference between an interface and an abstract class (other than multiple inheritance). In fact you can emulate a regular class with an interface.

This is not quite true since you can't declare fields in an interface. Any method you write in an interface can't rely on any implementation details.

As an example in favor of static methods in interfaces, consider utility classes like Collections in the Java API. That class only exists because those static methods can't be declared in their respective interfaces. Collections.unmodifiableList could've just as well been declared in the List interface, and it would've been easier to find.

Body:
Because you can only inherit one class. If you've got two interfaces whose implementations are complex enough that you need an abstract base class, those two interfaces are mutually exclusive in practice.

The alternative is to convert those abstract base classes into a collection of static methods and turn all the fields into arguments. That would allow any implementor of the interface to call the static methods and get the functionality, but it's an awful lot of boilerplate in a language that's already way too verbose.

As a motivating example of why being able to provide implementations in interfaces can be useful, consider this Stack interface:

public interface Stack<T> {
    boolean isEmpty();

    T pop() throws EmptyException;
 }

There's no way to guarantee that when someone implements the interface, pop will throw an exception if the stack is empty. We could enforce this rule by separating pop into two methods: a public final method that enforces the contract and a protected abstract method that performs the actual popping.

public abstract class Stack<T> {
    public abstract boolean isEmpty();

    protected abstract T pop_implementation();

    public final T pop() throws EmptyException {
        if (isEmpty()) {
            throw new EmptyException();
        else {
            return pop_implementation();
        }
    }
 }

Not only do we ensure all implementations respect the contract, we've also freed them from having to check if the stack is empty and throwing the exception. It's a big win!...except for the fact that we had to change the interface into an abstract class. In a language with single inheritance, that's a big loss of flexibility. It makes your would-be interfaces mutually exclusive. Being able to provide implementations that only rely on the interface methods themselves would solve the problem.

I'm not sure whether Java 8's approach to adding methods to interfaces allows adding final methods or protected abstract methods, but I know the D language allows it and provides native support for Design by Contract. There is no danger in this technique since pop is final, so no implementing class can override it.

As for default implementations of overridable methods, I assume any default implementations added to the Java APIs only rely on the contract of the interface they were added to, so any class that correctly implements the interface will also behave correctly with the default implementations.

Moreover,

There's virtually no difference between an interface and an abstract class (other than multiple inheritance). In fact you can emulate a regular class with an interface.

This is not quite true since you can't declare fields in an interface. Any method you write in an interface can't rely on any implementation details.

As an example in favor of static methods in interfaces, consider utility classes like Collections in the Java API. That class only exists because those static methods can't be declared in their respective interfaces. Collections.unmodifiableList could've just as well been declared in the List interface, and it would've been easier to find.


问:
Most of programmer work deals with mapping?
During all my work I've been working with ORM, WS, integration services, viewmodel and so on.

The common stuff in all these kind of work is that I had to make mappings and not always the available framework are enough to help in this mapping.

The question which I'm wondering is: is a consistent part of the development process dealing with mapping? It would be good to develop a tool for solving this kind of problems?

i.e.

```<code>sqlClient.AddParameterWithValue("switch", SqlDbType.TinyInt, user.IDUser);
sqlClient.AddParameterWithValue("IDUtente", SqlDbType.Int, user.IDUser);
</code>```

i.e.

```<code>GetSQLParameter("@switch", SqlDbType.TinyInt, 1), _
GetSQLParameter("@IDUtente", SqlDbType.Int), _
</code>```

i.e.

```<code>MappingFramework.Mapper.CreateMap<DataRecordWrapper, User>()
    .ForMember(dest => dest.IDUser, opt => opt.MapFrom(src => src.GetInt("switch")))
    .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.GetString("IDUtente")))
</code>```

答:
It's about integration.

The vast majority of software exists simply to integrate systems together so that tools and data and various things can all interoperate to make larger more robust products. The amount of any industry that is inventing novel products rather than taking known products and combining them is terribly minuscule, this goes for the software industry as well. A large majority of what developers are doing is integrating separate systems to get multiple independent features/products to work together as a single cohesive product.

There are tools out there that have attempted to generalize this task so that you can utilize them to do all of your integration of separate systems and features; they're called ETL tools. They're far too generic for most of the work we do integrating systems, but some people use them to drive their entire product.

It's often simpler to create something purposebuilt for each little integration spot than to use a general approach to all integration because general approaches have to be far larger, more robust, and due to that more complex. Like I said, some people do use ETL tools to drive their entire product, but ETL tools are vastly more complex and tricky to use than writing a few lines of code purposebuilt for a given integration spot.


问:
Adding svn support to our git repo
We have been using SVN for several years.

Recently, we switched over to git, since some members of the organization pointed out that if our SVN server dies our team is toast.

So far, we've got something worked out with the git workflow, however some team members really do not like this git process. They want to simply right-click on a file and then hit SVN Commit (we're using tortoiseSVN) without having to worry about all this pushing and pulling.

I've been asked to provide SVN support for our repository while keeping the git repo (hosted on github) updated. The workflow I'm imagining is that we'll all just do the normal SVN things as before, and then once in awhile I'll just do a push to github to backup our files.

What are some options for using git purely for backup purposes (one person would manage the git repo), while everyone uses the SVN repo?

I've read about git-svn, but it seems like a completely different tool. Perhaps someone can clarify this? If I checked out a svn repo using git-svn, would I be able to operate on it using tortoiseSVN? Or can everyone else use a regular SVN checkout, while I maintain a git-svn checkout?

答:
If you want just backups, I would recommend not to use git at all - that makes things unneccessarily complicated. Instead, backup your SVN server daily.

Of course, if you don't just want backups, but also mobile access to the repo, you could choose an svn hoster. Maybe this site will help you to pick one.

Title: Adding svn support to our git repo


答:
Let's go with this formulation:

Another variant of the question goes like this: given a matrix with
  sorted rows, and sorted columns, find Kth smallest.

Let M(1,1) denote the corner of the matrix with the smallest number and let M(n,n) be the corner with the highest number. (obviously they both are on the same diagonal of M).

Now let's think of sub-matrices: if we take the sub-matrix ranging from M(0,0) to M(p,p) we get a matrix that has the p^2 smallest value at position M(p,p) and all its other values are smaller. AND the fields M(0,p)-M(p,p) and M(p,0)-M(p,p) taken together consist of 2p-1 values.

So we only look at these values:

because we know for sure that the Kth smallest value is in there.

So your desired algorithm boils down to (pseudocode):

```<code>p := ceil( sqrt(K) )
candidate_list := merge (M(*,p), M(p,*)) // this has O(p) runtime since both lists are sorted
kth_element := candidate_list[p^2 - k] // +1 if your list starts at 1.
</code>```

Since the first and last row have runtime O(1) the total runtime is

```<code>O(p) <= O(sqrt(k)+1) <= O(sqrt(n^2)+1) <= O(n+1) <= O(n)
</code>```

Body:
Given two sorted array in ascending order with same length N, calculate the Kth min a[i]+b[j]. Time complexity O(N).

Another variant of the question goes like this:
given a matrix with sorted rows, and sorted columns, find kth smallest.

We can easily formulate an O(klogk) solution with minheap, but the challenge is doing the same in O(N) time ...

The paper below formulates the solution but I could not understand it. Can somebody explain it or any alternative idea?

hint: http://www.cse.yorku.ca/~andy/pubs/X%2BY.pdf

Body:
Let's go with this formulation:

Another variant of the question goes like this: given a matrix with
  sorted rows, and sorted columns, find Kth smallest.

Let M(1,1) denote the corner of the matrix with the smallest number and let M(n,n) be the corner with the highest number. (obviously they both are on the same diagonal of M).

Now let's think of sub-matrices: if we take the sub-matrix ranging from M(0,0) to M(p,p) we get a matrix that has the p^2 smallest value at position M(p,p) and all its other values are smaller. AND the fields M(0,p)-M(p,p) and M(p,0)-M(p,p) taken together consist of 2p-1 values.

So we only look at these values:

because we know for sure that the Kth smallest value is in there.

So your desired algorithm boils down to (pseudocode):

p := ceil( sqrt(K) )
candidate_list := merge (M(*,p), M(p,*)) // this has O(p) runtime since both lists are sorted
kth_element := candidate_list[p^2 - k] // +1 if your list starts at 1.

Since the first and last row have runtime O(1) the total runtime is

O(p) <= O(sqrt(k)+1) <= O(sqrt(n^2)+1) <= O(n+1) <= O(n)


问:
Java Method Returns Unbounded Type
I was reading this article, https://weblogs.java.net/blog/emcmanus/archive/2010/10/25/using-builder-pattern-subclasses, about subclassing a builder class. I understood the article but there was one small bit that bothered me. There was this method,

```<code>public static Builder<?> builder() {
        return new Builder2();
}
</code>```

When I changed Builder<?> to Builder, a raw type, the compiler would not compile the code. What is the additional information was passed to the compiler via with the additional <?>?

I have pasted the code here:

```<code>public class Shape {

  private final double opacity;

     public static class Builder<T extends Builder<T>> {
         private double opacity;

         public T opacity(double opacity) {
             this.opacity = opacity;
             return self();
         }

 /*
         public T height(double height) {
             System.out.println("height not set");
             return self();
         }
 */
         protected T self() {
             System.out.println("shape.self -> " + this);
             return (T) this;
         }

         public Shape build() {
             return new Shape(this);
         }
     }

     public static Builder<?> builder() {
         return new Builder();
     }

     protected Shape(Builder builder) {
         this.opacity = builder.opacity;
     }
 }

 public class Rectangle extends Shape {
     private final double height;

     public static class Builder<T extends Builder<T>> extends Shape.Builder<T> {
         private double height;

         public T height(double height) {
             System.out.println("height is set");
             this.height = height;
             return self();
         }

         public Rectangle build() {
             return new Rectangle(this);
         }
     }

     public static Builder<?> builder() {
         return new Builder();
     }

     protected Rectangle(Builder builder) {
         super(builder);
         this.height = builder.height;
     }

     public static void main(String[] args) {
         Rectangle r = Rectangle.builder().opacity(0.5).height(250).build();
     }
}
</code>```

答:
The ? symbol is a type variable. It's an unnamed one, meaning you can't refer to it in code, but the compiler still is going to use it, and substitute it with the actual type your Builder works with (such as Rectangle). The compiler can then use this additional type information, including the proper resolution of the opacity method.

Without <?>, this additional compile-time type information is lost, thus compiler needs to assume it works with plain Object. As a result, you'd explicit casting to invoke any method that Object class does not have.

Title: Java Method Returns Unbounded Type


答:
I would say "all three".

Show() and Hide() tend to be easier to grok than SetVisible(true) and SetVisible(false). However, when you want to set visibility logically it is better to have a method taking a bool rather than constructing an if around that bool.

You can support all three without duplicating logic and minimal boilerplate:

```<code>void Show() {
    foo.Show();
    bar.Show();
}

void Hide() {
    foo.Hide();
    bar.Hide();
}

void SetVisible(bool visible) {
    if (visible) {
        Show();
    } else {
        Hide();
    }
}
</code>```

Alternatively, if the things you are wrapping have a more SetVisible-ish API:

```<code>void Show() {
    SetVisible(true);
}

void Hide() {
    SetVisible(false);
}

void SetVisible(bool visible) {
    foo.SetVisible(visible);
    bar.SetVisible(visible);
}
</code>```

Title: Is better Show() + Hide() or SetVisible(bool visible)?

Body:
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions

Body:
I would say "all three".

Show() and Hide() tend to be easier to grok than SetVisible(true) and SetVisible(false). However, when you want to set visibility logically it is better to have a method taking a bool rather than constructing an if around that bool.

You can support all three without duplicating logic and minimal boilerplate:

void Show() {
    foo.Show();
    bar.Show();
}

void Hide() {
    foo.Hide();
    bar.Hide();
}

void SetVisible(bool visible) {
    if (visible) {
        Show();
    } else {
        Hide();
    }
}

Alternatively, if the things you are wrapping have a more SetVisible-ish API:

void Show() {
    SetVisible(true);
}

void Hide() {
    SetVisible(false);
}

void SetVisible(bool visible) {
    foo.SetVisible(visible);
    bar.SetVisible(visible);
}


问:
How can I deal with a slow API in PHP?
I'm writing a public web app to get stock data from a magento store. I've accessed the data, but it turns out that i have to query each product individually for stock data. With thousands of items this is a resource hog and takes lots of time. This cannot be avoided. It's just how their API works and I have to do it this way.

How can I code something in php that runs in the background, harvesting the api data by nibbling it in a calmer more friendly manner, and not hammer their shops with SOAP api calls?

Am I right in thinking that I need to use a background process like this:
    $pid = shell_exec(sprintf('%s > /dev/null 2>&1 & echo $!', $command));

...and then query that $pid? Store them in a database? Are there any examples of background process managers?

答: Taking Mike and Thorsten's comment - if this data is not time sensitive - you can create a cron job that will get these data and put it in your own SQL table and then have your App pull from it. Majority of good API calls typically have a pull all API request handler with a delimiter so that you can retrieve bulk data as they don't want you to hammer them because depending on their firewall configuration it might end up being a brute force spam program that wants to poll if you are polling too often. So in conclusion - it might not be you but them.</p>

Title: How can I deal with a slow API in PHP?