答:
The must-have Java books:

Effective Java By Josh Bloch

Java Concurrency in Practice By Brian Goetz, et. al.

Java Puzzlers By Josh Bloch, Neal Gafter

Title: If you could only have one programming related book on your bookshelf what would it be and why?

Body: One per answer please. I'll add my favourite as an answer.</p>


问:
What is idiomatic way in f# to express sequence of if statements with overlapping conditions
Let's say I got code like this:

```<code>if(conditionA)
    do something
if(conditionA && conditionB)
    do something more
</code>```

Obviously, I could nest the ifs (although when there are more complicated conditions this is not readable for me) like below:

```<code>if(conditionA)
    do something
    if(conditionB)
        do something more
</code>```

How can I write similar code in f# idiomatically. I assume if statement isn't considered idiomatic in functional programming (am I wrong?)

I could write two subsequent match expressions or nested match expression to mimic above code but doing so seems pretty ugly to me.

答:
F# is an expression-oriented language so, as Karl Bielefeldt points out, having if/else expressions that don't actually return any value is unidiomatic already.

Another aspect of idiomatic functional code is to make it explicit that all possible branches are being addressed.
That's one of the reasons why pattern matching with discriminated unions is so popular -- the compiler will warn you if you have forgotten a case.

The if/else by itself is perfectly acceptable, but it sounds like you are doing something a bit more complicated, when you have complex conditions like this.
If I was looking at this code, I would ask what happens if not conditionA holds? The code does not make that clear.

If this set of nested conditions occurs frequently, or is a critical piece of code that requires clarity, then I personally would replace the various conditions with a discriminated union to make it obvious to the reader what is going on.

```<code>type Keypress =
    | AOnly
    | AAndB
    | NeitherANorB
</code>```

(Obviously, the names are ugly -- you should rename the cases according to your needs!)

Then create a translator function that turns the input into one of the Keypress cases:

```<code>let inputToKeypress input =
    if conditionA then
        if conditionB then AAndB else AOnly
    else
        NeitherANorB
</code>```

Finally, your main code can pattern match in an obvious way.

```<code>let mainCode keypress =
   match keypress with
   | AOnly -> do something
   | AAndB -> do something; do something more;
   | NeitherANorB -> () // ignore
</code>```

An additional advantage of this approach is that if you add or remove cases in your union type, your code will fail to compile. Not so with nested if expressions.

ContentLicense: CC BY-SA 3.0

Body:
F# is an expression-oriented language so, as Karl Bielefeldt points out, having if/else expressions that don't actually return any value is unidiomatic already.

Another aspect of idiomatic functional code is to make it explicit that all possible branches are being addressed.
That's one of the reasons why pattern matching with discriminated unions is so popular -- the compiler will warn you if you have forgotten a case.

The if/else by itself is perfectly acceptable, but it sounds like you are doing something a bit more complicated, when you have complex conditions like this.
If I was looking at this code, I would ask what happens if not conditionA holds? The code does not make that clear.

If this set of nested conditions occurs frequently, or is a critical piece of code that requires clarity, then I personally would replace the various conditions with a discriminated union to make it obvious to the reader what is going on.

type Keypress =
    | AOnly
    | AAndB
    | NeitherANorB

(Obviously, the names are ugly -- you should rename the cases according to your needs!)

Then create a translator function that turns the input into one of the Keypress cases:

let inputToKeypress input =
    if conditionA then
        if conditionB then AAndB else AOnly
    else
        NeitherANorB

Finally, your main code can pattern match in an obvious way.

let mainCode keypress =
   match keypress with
   | AOnly -> do something
   | AAndB -> do something; do something more;
   | NeitherANorB -> () // ignore

An additional advantage of this approach is that if you add or remove cases in your union type, your code will fail to compile. Not so with nested if expressions.


问:
Naming classes, methods, functions and variables
There are 3 important naming conventions:

with_underscores

PascalCased

camelCased

Other variants are not important because they are not commonly used.

For variables it seems that the one with underscores is the most used by developers so I'll stick with that. I think it's the same for functions.

But what about class, and method names? Which of these 3 is the most used by developers for such constructs? (personally, it's 3. for methods and 2. for classes)

Please do not post things like "use what you feel is right", because the code I'm writing is API for other developers, and I'd like to adopt the most popular coding style :)

答:
I personally find camelcase to be more natural when coding variables, but because variables in PHP are case sensitive, and it's no fun hunting through code looking for a variable you forgot to make camelcase, I always use snake case for variables.

While its true that the conventions are mutable, coding after someone that has used camelcase on variables, and trying to be sure you always use their convention for THAT variable, can be frustrating.


问:
Should you test development features?
Is it a good practice to test features that only run in a development environment, or just a waste of time?

Specifics: The item that is prompting this question is a line of code that dynamically re-compiles style sheets. For production it compiles them once, then puts them in ./build/. As for research, I did some googling, but couldn't find anything. I am new to testing, so I might just not be looking right.

答:
I added a short answer saying that the answer is the same as for the question "do you care if the feature has bugs in it". A moderator didn't like that answer and deleted it, so I'll elaborate.

Anytime you write code there is a chance it will have bugs. To help possibly uncover these bugs, you should test the code. Now, in some cases it doesn't matter if the code has bugs or not. For example, internal code such as that in the question often carries very low risk - low risk for bugs because it is uncomplicated code, and because the cost to fix bugs is low. Other software, such as for medical equipment, has a very high risk, and bugs can be costly.

To decide if you should test software --any software-- you need to ask yourself if it matters if the code has bugs. Will a bug cause irreparable harm, or harm that is expensive to fix? Is a bug simply a minor inconvenience? Where does your software lie on that continuium? Answering that goes a long way toward answering if you should test your code.

Of course, testing won't guarantee your software is bug free, but even simple tests can raise your level of confidence high enough to know if you can depend on the code.

So, in your specific case, what is the cost of the dynamic re-compiling failing? Will it cause developers to potentially introduce bugs because they are running old code? Or, is it just a minor inconvenience because they can always run a manual step?

Title: Should you test development features?


问:
int * vs int [N] vs int (*)[N] in functions parameters. Which one do you think is better?
When programming in C (or C++) there are three different ways to specify the parameter in a function that takes an array.

Here is an example (implementing std::accumulate from C++ in C) that shows you what I mean.

I can write it like this:

```<code>int accumulate(int n, int *array)
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

This can also be written to this (which means the very same thing):

```<code>int accumulate(int n, int array[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

I can also write it like this:

```<code>int accumulate(int n, int (*array)[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += (*array)[i];
    }
    return sum;
}
</code>```

All these options are very similar and generate the same executable code but they have a slight difference which is how the caller passes the arguments.

This is how the first two options gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), a));
    return 0;
}
</code>```

This is how the thrid option gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), &a));
    return 0;
}
</code>```

Note that the third option requires to user to explicitly specify the address of a
with &a. The first two options does not require this because arrays implicitly gets converted into pointers to the same type in C.

I have always preferred the third approach.

This is why:

It is more consistent with how other types are passed by pointers.

```<code>int draw_point(struct point *p);

int main()
{
    struct point p = {3, 4};
    draw_point(&p); // Here is the 'address of' operator required.
}
</code>```

It makes it possible to use macros like ARRAY_LENGTH to get the amount of elements in the array.

```<code>#include <stdio.h>
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))

void this_works(int (*array)[10])
{
    /* This works! */
    printf("%d\n", ARRAY_LENGTH(*array));
}

void this_is_invalid_and_dangerous(int array[10])
{
    /* This does NOT work because `array` is actually a pointer. */
    printf("%d\n", ARRAY_LENGTH(array));
}
</code>```

The only advantage I see with int array[] (and int *array) is that you get to write array[X] instead of (*array)[X] when you wish to grab an index.

What are your professional thoughts on this? Which approach do you think is better and why? Do you ever mix the two? If so when do you choose what?

Like I said have I always preferred using int (*array)[N] but I see that the other two approaches are quite common as well.

答:
The first declaration also allows you write the function differently:

```<code>int accumulate(int n, int *array)
{
    int sum = 0;
    while (n-- > 0) sum += *array++;
    return sum;
}
</code>```

so you don't need the variable i.

Whatever's idiomatic to the code base should be preferred, followed by whatever's the easiest to understand, followed at some distance by whatever's the most performant. The second declaration is the easiest to understand.

Body:
The first declaration also allows you write the function differently:

int accumulate(int n, int *array)
{
    int sum = 0;
    while (n-- > 0) sum += *array++;
    return sum;
}

so you don't need the variable i.

Whatever's idiomatic to the code base should be preferred, followed by whatever's the easiest to understand, followed at some distance by whatever's the most performant. The second declaration is the easiest to understand.


问:
How would a modern website like Reddit divide up its website into Django apps?
Django uses apps to divide projects into manageable and reusable chunks. All examples in tutorials use polls or articles in unrelatable circumstances. In a modern example like Reddit (or even Amazon or Ebay), how would Django apps be used to break up the website?</p>

答:
"App" is a particularly odd term for this concept, specific to Django.  Consider this quote from the documentation:

It is important to understand that a Django application is just a set of code that interacts with various parts of the framework. There’s no such thing as an Application object. However, there’s a few places where Django needs to interact with installed applications, mainly for configuration and also for introspection. That’s why the application registry maintains metadata in an AppConfig instance for each installed application.

This means, basically, that an app is simply a module with a certain amount of special, framework-conferred status (in terms of configuration and introspection). In practice, this is often used for aspects of the project that are conceptually distinct—an example, in Reddit, might be ads. It's difficult to identify anything else without seeing their code base; most of the rest of the site's functionality is based on your user account, which, in Django terms, would be a shared model, and thus would preclude the idiomatic use of Django apps.


问:
Which components/phases of a JIT compiler are different from a traditional ahead of time compiler?
Besides a faster register allocation algorithm and some trade-off in control and data-flow analysis for optimization purposes, which components/phases of a JIT compiler are different from a traditional ahead of time compiler?</p>

答:
The main differences between an AOT and a JIT compiler are resources and information.

An AOT compiler has infinite resources. It can use as much RAM as it likes, and take as much time as it wants. (Note that this is only theoretically true. Pragmatically, people don't like long time compiles. Plus, compilers are now typically embedded into IDEs, where they provide instant feedback while-you-type, so that at least lexing, parsing, semantic analysis, type inference, type checking, macro expansion, etc., basically everything except the actual code generation and optimization have to happen very fast and with low memory usage.)

A JIT compiler OTOH has to "steal" its resources from the running application. (Again, theoretically. Pragmatically, the JIT compiler has to work hardest, when a lot of new code is introduced into the system, this is typically when the application starts, at which point the loading of configuration files and setting up of object graphs is the bottleneck, not the JIT compiler.)

A JIT compiler has much more information available than an AOT compiler, and it doesn't have to work hard to get it. An AOT compiler can only get static information about the code. Static analysis algorithms are usually very expensive (often at least O(n2) in at least one of time and space, sometimes exponential) and they don't even reliably work, because many of them are equivalent to solving the Halting Problem (Class Hierarchy Analysis, Escape Analysis, Dead Code Elimination, for example).

A JIT compiler OTOH doesn't run into the Halting Problem, because it doesn't do static analysis. And it doesn't have to run expensive algorithms: want to know whether a method is being overridden or not so that you can potentially inline it? Don't need to run Class Hierarchy Analysis, just look at the classes, they're all there. Or even better yet: don't even bother, just inline it anyway, and if it turns out you were wrong about it not being overridden, un-inline it again. Want to know whether a reference escapes a local scope or not so that you can potentially allocate it on the stack? Don't bother, just allocate it on the stack, tag it, and when the tag shows up somewhere else, re-allocate on the heap. And since you only compile code when it is running, Dead Code Elimination is totally trivial because dead code will never run and thus never be compiled.

So, the basic difference is that the analysis in a JIT compiler can be simpler, because it has a lot of information available that an AOT compiler doesn't have, and the optimization and code generation must be simpler, because it has a lot less resources available. Note, however, that a JIT compiler can nonetheless perform much more aggressive optimizations than an AOT compiler can, because it doesn't necessarily have to prove the optimizations correct. If it turns out an optimization is wrong, it can always de-optimize again. (Not all JITs do this (the CLR JIT for example, is incapable of de-optimizing), but for example the HotSpot JIT in the Oracle JDK does.) Speculative Inlining is one such optimization that is only possible in a de-optimizing JIT.

One thing that is peculiar about JITs is that very often the languages they compile are designed to be easily compilable by a machine (e.g. JVM bytecode, CPython bytecode, Rubinius bytecode, LLVM IR, CLI CIL, Dalvik bytecode), whereas the languages that a typical AOT compiler compiles are designed to be easily readable by humans (e.g. Ruby, Python, Java). But I understood your question to be about an AOT vs. a JIT for the same language, so none of this applies. Obviously, if you compare compilers for different languages, there will be a lot of differences, and many of those will be totally unrelated to the difference between JIT and AOT and more related to the differences between the two languages.


问:
Does this Haskell pattern have a name?
I recently found use for the following Haskell functions:

```<code>feed :: (a -> (a, b)) -> a -> Int -> (a, [b])
feed f input 0 = (input, [])
feed f input n
  | n < 0 = error "feed f input n: n < 0"
  | otherwise = (final, out:prev)
    where (next, out) = f input
      (final, prev) = feed f next $ pred n

nest :: (a -> a) -> a -> Int -> a
nest f x 0 = x
nest f x n
  | n < 0 = error "nest f x n: n < 0"
  | otherwise = f $ nest f x $ pred n
</code>```

feed cycles a function through some input a, with the function returning a new input for the next call, as well as "emitting" an output, which is collected. nest works the same way, but doesn't let functions emit anything.

This looks awfully "Monadic" to me, and it seems to me like something from Control.Monad should already be doing this (I've caught myself trying to re-implement stuff like sequence, mapM, etc., out of necessity before, since I'm a beginner with Haskell and I don't quite know what's in the library and what's not.

Does something like the above (perhaps in a more general setting?) already exist? I've looked through the docs (at least the one's I'm familiar with), and can't find anything, though this seems like a common pattern. Example usage:

```<code>let pick10 rng = feed (swap . randomR (1, 10)) rng 10
</code>```

答:
After some more digging it finally came to me. Indeed, there is such a generalization, and it was staring at me the whole time. The awfully monadic feeling I was getting was there because there really was a monad, simulated with tuples, lurking in the backgroud.

For those in suspense, it's replicateM along with Control.Monad.Random (for my example).

Note: I'll post a more detailed answer when I have time; just wanted to resolve the question to save viewers some effort.

Title: Does this Haskell pattern have a name?


答:
Note: This answer might be a bit more basic than you are looking for. Maybe someone will find it useful.

feed is a bit like Data.List.unfoldr. It's not constrained to Ints. You could generalize yours over Enums if you wanted. iterate is similar, but produces an infinite list.

```<code>Main Data.List> unfoldr (\x -> if x > 9 then Nothing else Just (x, x + 1)) 0
[0,1,2,3,4,5,6,7,8,9]
Main Data.List> feed (\x -> (x + 1, x)) 0 10
(10,[0,1,2,3,4,5,6,7,8,9])
</code>```

nest is a bit like iterate because of infinite lists. Again, not constrained by the Int type.

```<code>*Main Data.List> iterate (+ 1.5) 2.7 !! 10
17.7
*Main Data.List> nest (+ 1.5) 2.7 10
17.7
</code>```

As for Monadic, I'm not sure. [a] is one built-in Monad, and of course unfoldr f for whatever f is a nice a -> [a]. I do think you could define a Monad instance for your type (a, [b]) that left a trail and continued with the 'new' seed. There's probably an instance laying around that does that (Oop! You found it as I was writing this) - and, as always, these 'simple' things take just a few lines to write when you want them.

Title: Does this Haskell pattern have a name?

Body:
I recently found use for the following Haskell functions:

```<code>feed :: (a -> (a, b)) -> a -> Int -> (a, [b])
feed f input 0 = (input, [])
feed f input n
  | n < 0 = error "feed f input n: n < 0"
  | otherwise = (final, out:prev)
    where (next, out) = f input
      (final, prev) = feed f next $ pred n

nest :: (a -> a) -> a -> Int -> a
nest f x 0 = x
nest f x n
  | n < 0 = error "nest f x n: n < 0"
  | otherwise = f $ nest f x $ pred n
</code>```

feed cycles a function through some input a, with the function returning a new input for the next call, as well as "emitting" an output, which is collected. nest works the same way, but doesn't let functions emit anything.

This looks awfully "Monadic" to me, and it seems to me like something from Control.Monad should already be doing this (I've caught myself trying to re-implement stuff like sequence, mapM, etc., out of necessity before, since I'm a beginner with Haskell and I don't quite know what's in the library and what's not.

Does something like the above (perhaps in a more general setting?) already exist? I've looked through the docs (at least the one's I'm familiar with), and can't find anything, though this seems like a common pattern. Example usage:

```<code>let pick10 rng = feed (swap . randomR (1, 10)) rng 10
</code>```

Body:
Note: This answer might be a bit more basic than you are looking for. Maybe someone will find it useful.

feed is a bit like Data.List.unfoldr. It's not constrained to Ints. You could generalize yours over Enums if you wanted. iterate is similar, but produces an infinite list.

Main Data.List> unfoldr (\x -> if x > 9 then Nothing else Just (x, x + 1)) 0
[0,1,2,3,4,5,6,7,8,9]
Main Data.List> feed (\x -> (x + 1, x)) 0 10
(10,[0,1,2,3,4,5,6,7,8,9])

nest is a bit like iterate because of infinite lists. Again, not constrained by the Int type.

*Main Data.List> iterate (+ 1.5) 2.7 !! 10
17.7
*Main Data.List> nest (+ 1.5) 2.7 10
17.7

As for Monadic, I'm not sure. [a] is one built-in Monad, and of course unfoldr f for whatever f is a nice a -> [a]. I do think you could define a Monad instance for your type (a, [b]) that left a trail and continued with the 'new' seed. There's probably an instance laying around that does that (Oop! You found it as I was writing this) - and, as always, these 'simple' things take just a few lines to write when you want them.


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
Bubble Sort !

Bubble sort is not as bad as Bogosort. That is why I vote for the Bubble sort.

ContentLicense: CC BY-SA 2.5


问:
Decorator design pattern in swift
I'm reading "Head first design patterns" (here you can find exact example mentioned in book)

While going through Decorator design pattern, everything was crisp and clear until I stumbled into this

They are explaining decorator using

Extensions.
I don't think extending a class through 'Extensions' results in decorator design pattern since we can't add properties to classes. As I understand, key to decorator is it ability to wraps other objects infinity, this is not possible here, although we can add functionality to existing class without inheriting it.

Delegation.
Delegation here is completely out of context. Isn't delegation itself a design pattern?

答:
I think the book “Head first design patterns” is correct.

As per Wikipedia, this pattern “allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class”. 'Extensions' are adding capability to an object statically and behaviors can be added by adding methods only, it may not need a new property (that is not a compulsory condition here). This stackoverflow question discussed similar stuff.

Delegation can be considered as a pattern and can be utilized to add a behaviors to an existing object as per decorator pattern. Have a look on following links:
https://stackoverflow.com/questions/3929996/gof-explanation-of-the-decorator-pattern-is-confusing-or-just-plain-wrong and http://lgiordani.com/blog/2014/05/19/method-overriding-in-python/

Hope it will help. Thanks.

ContentLicense: CC BY-SA 4.0

Title: Decorator design pattern in swift


问:
How do I avoid cascading refactorings?
I've got a project. In this project I wished to refactor it to add a feature, and I refactored the project to add the feature.

The problem is that when I was done, it turned out that I needed to make a minor interface change to accommodate it. So I made the change. And then the consuming class can't be implemented with its current interface in terms of the new one, so it needs a new interface as well. Now it's three months later, and I've had to fix innumerable virtually unrelated problems, and I'm looking at solving issues that were roadmapped for a year from now or simply listed as won't fix due to difficulty before the thing will compile again.

How can I avoid this kind of cascading refactorings in the future? Is it just a symptom of my previous classes depending too tightly on each other?

Brief edit: In this case, the refactor was the feature, since the refactor increased the extensibility of a particular piece of code and decreased some coupling. This meant that external developers could do more, which was the feature I wanted to deliver. So the original refactor itself should not have been a functional change.

Bigger edit that I promised five days ago:

Before I began this refactor, I had a system where I had an interface, but in the implementation, I simply dynamic_cast through all the possible implementations that I shipped. This obviously meant that you couldn't just inherit from the interface, for one thing, and secondly, that it would be impossible for anybody without implementation access to implement this interface. So I decided that I wanted to fix this issue and open up the interface for public consumption so that anybody could implement it and that implementing the interface was the entire contract required- obviously an improvement.

When I was finding and killing-with-fire all the places that I had done this, I found one place that proved to be a particular problem. It depended upon implementation details of all the various deriving classes and duplicated functionality that was already implemented but better somewhere else. It could have been implemented in terms of the public interface instead and re-used the existing implementation of that functionality. I discovered that it required a particular piece of context to function correctly. Roughly speaking, the calling previous implementation looked kinda like

```<code>for(auto&& a : as) {
     f(a);
}
</code>```

However, to get this context, I needed to change it into something more like

```<code>std::vector<Context> contexts;
for(auto&& a : as)
    contexts.push_back(g(a));
do_thing_now_we_have_contexts();
for(auto&& con : contexts)
    f(con);
</code>```

This means that for all operations that used to be a part of f, some of them need to be made a part of the new function g that operates without a context, and some of them need to be made of a part of the now-deferred f. But not all methods f call need or want this context- some of them need a distinct context that they obtain through separate means. So for everything that f ends up calling (which is, roughly speaking, pretty much everything), I had to determine what, if any, context they needed, where they should get it from, and how to split them from old f into new f and new g.

And that's how I ended up where I am now. The only reason that I kept going is because I needed this refactoring for other reasons anyway.

答:
Refactoring is a structured discipline, distinct from cleaning up code as you see fit.  You need to have unit tests written before starting, and each step should consist of a specific transformation that you know should make no changes to functionality.  The unit tests should pass after every change.

Of course, during the refactoring process, you will naturally discover changes that should be applied that may cause breakage.  In that case, try your best to implement a compatibility shim for the old interface that uses the new framework.  In theory, the system should still work as before, and the unit tests should pass.  You can mark the compatibility shim as a deprecated interface, and clean that up at a more suitable time.

Title: How do I avoid cascading refactorings?


答:
Last time I tried to start a refactoring with unforeseen consequences, and I could not stabilize the build and / or the tests after  one day, I gave up and reverted the codebase to the point before the refactoring.

Then, I started to analyze what went wrong and developed a better plan how to do the refactoring in smaller steps. So my advice for avoiding cascading refactorings is just: know when to stop, don't let things run out of your control!

Sometimes you have to bite the bullet and throw away a full day of work - definitely easier than to throw away three months of work. The day you loose is not completely in vain, at least you have learned how not to approach the problem. And to my experience, there are always possibilities to make smaller steps in refactoring.

Side note: you seem to be in a situation where you have to decide if you are willing to sacrifice full three months of work and start over again with a new (and hopefully more successful) refactoring plan. I can imagine that is not an easy decision, but ask yourself, how high is the risk you need another three months not just to stabilize the build, but also to fix all unforeseen bugs you probably introduced during your rewrite you did the last three months? I wrote "rewrite", because I guess that is what you really did, not a "refactoring". It is not unlikely that you can solve your current problem quicker by going back to the last revision where your project compiles and start with a real refactoring (opposed to "rewrite") again.

Title: How do I avoid cascading refactorings?

Body:
I've got a project. In this project I wished to refactor it to add a feature, and I refactored the project to add the feature.

The problem is that when I was done, it turned out that I needed to make a minor interface change to accommodate it. So I made the change. And then the consuming class can't be implemented with its current interface in terms of the new one, so it needs a new interface as well. Now it's three months later, and I've had to fix innumerable virtually unrelated problems, and I'm looking at solving issues that were roadmapped for a year from now or simply listed as won't fix due to difficulty before the thing will compile again.

How can I avoid this kind of cascading refactorings in the future? Is it just a symptom of my previous classes depending too tightly on each other?

Brief edit: In this case, the refactor was the feature, since the refactor increased the extensibility of a particular piece of code and decreased some coupling. This meant that external developers could do more, which was the feature I wanted to deliver. So the original refactor itself should not have been a functional change.

Bigger edit that I promised five days ago:

Before I began this refactor, I had a system where I had an interface, but in the implementation, I simply dynamic_cast through all the possible implementations that I shipped. This obviously meant that you couldn't just inherit from the interface, for one thing, and secondly, that it would be impossible for anybody without implementation access to implement this interface. So I decided that I wanted to fix this issue and open up the interface for public consumption so that anybody could implement it and that implementing the interface was the entire contract required- obviously an improvement.

When I was finding and killing-with-fire all the places that I had done this, I found one place that proved to be a particular problem. It depended upon implementation details of all the various deriving classes and duplicated functionality that was already implemented but better somewhere else. It could have been implemented in terms of the public interface instead and re-used the existing implementation of that functionality. I discovered that it required a particular piece of context to function correctly. Roughly speaking, the calling previous implementation looked kinda like

```<code>for(auto&& a : as) {
     f(a);
}
</code>```

However, to get this context, I needed to change it into something more like

```<code>std::vector<Context> contexts;
for(auto&& a : as)
    contexts.push_back(g(a));
do_thing_now_we_have_contexts();
for(auto&& con : contexts)
    f(con);
</code>```

This means that for all operations that used to be a part of f, some of them need to be made a part of the new function g that operates without a context, and some of them need to be made of a part of the now-deferred f. But not all methods f call need or want this context- some of them need a distinct context that they obtain through separate means. So for everything that f ends up calling (which is, roughly speaking, pretty much everything), I had to determine what, if any, context they needed, where they should get it from, and how to split them from old f into new f and new g.

And that's how I ended up where I am now. The only reason that I kept going is because I needed this refactoring for other reasons anyway.


问:
What kind of applications are built using C
I studied C programming about ten years ago, whiles in Uni,however I would like to pick it up again.
I'm looking at developing secure applications that utilize cryptography.
Would C be the right language to use?
What types of applications are developed using C? </p>

答:
C nowadays is used primarily in situations in which a fast compiled language is required that is not overly complicated (classes not required).  This includes:

Hardware drivers

Pixel shaders (variant of C, Cg)

In general, programs in which speed is critical

Knowing C well is paramount for knowing how programming languages work with the operating system, and it is literally impossible to know how to program C well and not have a thorough understanding of how such things work underneath.  C++ is almost as fast as C, and in fact many of the same applications of C you will see C++ used for having all the benefits of C++ and very little slowup as a consequence.  (pixel shader being an exception).

Often you will see programs written in other languages refer to libraries written in C for CPU-intensive operations and generally a large software company will have at least one C programmer for such work.

That said, I think you should also learn some higher-level language to counter-balance if you want to be a well-rounded programmer.  You could use C for cryptography, though most languages have support for cryptography, and such support is already generally written in C or C++.  In general, writing the entire applciation in C, you risk to reinvent a lot of things which already exist in existing languages, so I would encourage you to use it only to tweak otherwise slower parts of your program.

I hope that answers your question.


答:
You cannot directly add attributes and methods in a class, but you can do that in the decorator. Since a decorator is a composition of its supertype, you can state that the decorator is a basic object, with additional methods and attributes. Exactly like a sub-class is its super-class, with additional or modified methods and attributes.

In typical decorator, a part of the behaviour is simply identical to what is defined in the associated basic object. So you implement the methods reifying this behaviour by simply call the same method in the associated object. That's why you can say that the Decorator Design Pattern can be used as a delegation mechanism.

It is relatively common to find (a part of) a pattern in an other one. You could for instance consider the decorator as a special kind of proxy.

Title: Decorator design pattern in swift

Body:
I'm reading "Head first design patterns" (here you can find exact example mentioned in book)

While going through Decorator design pattern, everything was crisp and clear until I stumbled into this

They are explaining decorator using

Extensions.
I don't think extending a class through 'Extensions' results in decorator design pattern since we can't add properties to classes. As I understand, key to decorator is it ability to wraps other objects infinity, this is not possible here, although we can add functionality to existing class without inheriting it.

Delegation.
Delegation here is completely out of context. Isn't delegation itself a design pattern?


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: "This DLL you wrote is only 17kb. Can you add some code to make it bigger?  The client is paying us a lot of money, and we want them to get their money's worth."</p>


答:
Brute Force Algorithm !

Many people underestimate this brute force algorithm. Actually it is mostly used to solve problems having no pattern. I love it much!

Title: Which are the significant algorithms for humankind in past decades?

Body:
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...


答:
C may be selected as a development language for any number of reasons:

Ecosystem

C is the development language of choice on some operating systems - notably Unix platforms and their variants.

Low level integration

If you need to inline assembler for whatever reason, C would be a natural choice.

Cross-platform

C can be used to write platform independent code although this has largely been superseded by Java in this respect.

Raw speed

To my mind, there is still no better high level language in terms of speed so if performance is of the essence, C would be a natural choice.

If your application is sufficiently complex, you will of course need classes. C++ may seem to be the obvious choice here, but there are a growing number of C variants which provide OO functionality. Objective-C being the main one that springs to mind but there are many others (see here).

Title: What kind of applications are built using C

Body:
I studied C programming about ten years ago, whiles in Uni,however I would like to pick it up again.
I'm looking at developing secure applications that utilize cryptography.
Would C be the right language to use?
What types of applications are developed using C? </p>


问:
Lookup pattern as a way of passing global references
I am looking at some legacy code in java that uses the Service Locator pattern as a way of passing global references as opposed to passing them over and over again through method arguments and I am looking to refactor this approach. First of all this is a good approach or does it indicate code smell ? If it is code smell Would the best way to refactor this code is by introducing Dependency Injection either constructor injection or setter injection ? </p>

答:
Yes, many people consider Service Locator to be an anti-pattern. Depending on how it is implemented it can be difficult to unit test code that uses it, it reduces flexibility because clients can only have a single implementation of each interface, and it relies on run-time type testing so various errors can only be detected at run-time (often  only during execution, if clients defer locating services until they are needed).

Dependency injection via constructor parameters is the most common preference. It makes the dependencies of a class an explicit part of its interface. In a statically typed language it allows the compiler to verify that all dependencies are satisfied (unless using a framework that uses reflection, in which case the language runtime ensures this during the container initialisation). And testing in isolation is trivial.

You probably don't need a DI framework. They can save some work, but doing DI by hand gives you the benefit of static type checking, which is worth the extra work a lot of the time.


问:
Which Design Pattern Is Best Suited?
I have been studying Design Patterns and I am looking to implement them into my latest project.

I am working on a Windows Service that regularly checks a database table for a new entry.
Depending on the entry found, the service will perform a number of processes.

Possible processes include:

1) Generate report and send email with report attached

2) Run query and log data to another table

3) Send notification email

What design pattern is best suited? I have been considering the Factory Pattern.

My design process so far...

1) Create Interface

2) Create Abstract class which implements the Interface

3) Abstract Methods:

```<code>- CheckTable()
- GenerateReport()
- SendEmail()
</code>```

4) Factory Design Pattern:

```<code>- The client(windows service) asks the Factory for a new object (based of the database entry found)
- The factory instantiates this and returns to the client
- The client then calls the relevant methods to send email or run query.
</code>```

Does this look correct? Or am I making this more difficult than it is?

Or should I be using the Observor Pattern?

UPDATE:

OK. I have taken your advice and looked for the simplest way of doing this.

Is the below correct? I have created an Interface and then a class to implement this Interface.

There could be a number of different reports/emails to generate. Should these be added as new methods in the Interface?

Do I need an Abstract class?

```<code>// interface
internal interface IJobs
{
    void SendEmail();
    void PublishData();
    void GenerateTestReport(string userID, DateTime period);
}

// concrete class
public sealed class JobsFactory : IJobs
{
    #region SINGLETON

    private static JobsFactory INSTANCE;

    private JobsFactory() { }

    public static JobsFactory GetInstance()
    {
        if (INSTANCE == null)
        {
            INSTANCE = new JobsFactory();
        }
        return INSTANCE;
    }

    #endregion

    private readonly WorkbookFactory _workbookFactory = WorkbookFactory.GetInstance();

    #region IJobs Members

    public void SendEmail()
    {
        // send email
    }

    public void PublishData()
    {
        // publish data
    }

    public void GenerateTestReport(string userID, DateTime period)
    {
        string reportTestFilePath = this._workbookFactory.BuildTestReportWorkbook(userID, period);
    }

    #endregion
}
</code>```

答:
Since you need to do what seems to be polling, you could take a look at the Observer Pattern. This would allow your service to call your methods so that they can take appropriate action.

That being said, as it has been mentioned in the comments, you seem to have design patterns the other way round. The task should lead you to a design pattern. Trying to wrap your requirements around a particular design pattern is not the best way to approach design.

Title: Which Design Pattern Is Best Suited?


问:
Dependency Inversion & Decoupling
I'm wondering if someone might explain the last paragraph written in this example on Dependency Inversion & Decoupling.

http://www.springbyexample.org/examples/core-concepts.html

Following the example code, understanding the reasoning behind decoupling classes by implementing a base class is fine.

What I would like some clarification on is the last paragraph:

However, there is one problem with this implementation. We don’t have a main method. We > definitely need one in order to run our
  application, and somewhere in this main method we will need to
  instantiate the LocalVoteRecorder.

By instantiating the LocalVoteRecorder in our main method, we would
  break Rule #1 of Dependency Inversion. We have coded to the
  abstraction, we have integrated our changes, but our application would
  still have a dependency on a lower level class.

Does this mean it is not possible to create a truly decoupled application? How can it be that one could write a 100% decoupled application? Is it even necessary, and are there any best practices I could read up on.

Many thanks

答:
Tight coupling is bad. Loose coupling is what need. And nothing works in complete Isolation, so dependency (to interface) is inevitable.

The best practices is to create decoupled components as described here to avoid the disadvantages of tightly coupled application as mentioned on this Wikipedia page. Consider below lines too as they metioned here:

A module is closed if it has a well defined stable interface that all
  other modules must use and that limits the interaction and potential
  errors that can be introduced into one module by changes in another.

Thanks.

Title: Dependency Inversion & Decoupling


答:
I'll tell you a story. Many years ago, when I was a young, inexperienced programmer and GoF had not long before published their Design Patterns book, and Java was a new language and the only user interface library generally available for it was AWT, and AWT applications all looked ugly as hell, my company decided to switch development from C++ to Java. But AWT was out of the question: our applications were required to look and feel like native Win 32 apps, and you simply couldn't achieve that with AWT back then. So, I was tasked with learning JNI and implementing a framework that would let us build native windows user interfaces using Java.

I had not long before read about Design Patterns, and was eager to use them, so I looked at my project and thought about which ones would fit where. The idea I was most proud of was this: I'd have a native Window object that encapsulated a win32 window handle, but in order to allow the application to attach behaviours to the window, I'd use Chain of Responsibility. This would let applications use existing behaviours and combine them in new ways, and everything would be great.

So I implemented Chain of Responsibility, and it was a bit more complex than just having a single Behaviour object that managed everything, but I wrote a handful of tests using it and everything worked beautifully.

Then we deployed the framework and started to write real applications using it, and you know what? Not once did we ever use the facility to chain multiple behaviours in a single window.

The lesson here is simple: don't start by using the Design Pattern catalogue to shop for extra flexibility in your application. Start by thinking about what flexibility you are really likely to need, and then about how you can implement that flexibility. It might be that a standard pattern is the best way to achieve that. It might be there's a simpler, more direct way. It may even be the case that you have a rigid, well-defined problem that is small enough that you can design the entire solution simply without needing any scope to change behaviour later, in which case anything even approximating a design pattern would likely be overkill.

To borrow a phrase from Kent Beck, "do the simplest thing that could possibly work". If that happens to end up looking like a pattern, that's great. But don't worry if it doesn't.

Title: Which Design Pattern Is Best Suited?

Body:
I have been studying Design Patterns and I am looking to implement them into my latest project.

I am working on a Windows Service that regularly checks a database table for a new entry.
Depending on the entry found, the service will perform a number of processes.

Possible processes include:

1) Generate report and send email with report attached

2) Run query and log data to another table

3) Send notification email

What design pattern is best suited? I have been considering the Factory Pattern.

My design process so far...

1) Create Interface

2) Create Abstract class which implements the Interface

3) Abstract Methods:

```<code>- CheckTable()
- GenerateReport()
- SendEmail()
</code>```

4) Factory Design Pattern:

```<code>- The client(windows service) asks the Factory for a new object (based of the database entry found)
- The factory instantiates this and returns to the client
- The client then calls the relevant methods to send email or run query.
</code>```

Does this look correct? Or am I making this more difficult than it is?

Or should I be using the Observor Pattern?

UPDATE:

OK. I have taken your advice and looked for the simplest way of doing this.

Is the below correct? I have created an Interface and then a class to implement this Interface.

There could be a number of different reports/emails to generate. Should these be added as new methods in the Interface?

Do I need an Abstract class?

```<code>// interface
internal interface IJobs
{
    void SendEmail();
    void PublishData();
    void GenerateTestReport(string userID, DateTime period);
}

// concrete class
public sealed class JobsFactory : IJobs
{
    #region SINGLETON

    private static JobsFactory INSTANCE;

    private JobsFactory() { }

    public static JobsFactory GetInstance()
    {
        if (INSTANCE == null)
        {
            INSTANCE = new JobsFactory();
        }
        return INSTANCE;
    }

    #endregion

    private readonly WorkbookFactory _workbookFactory = WorkbookFactory.GetInstance();

    #region IJobs Members

    public void SendEmail()
    {
        // send email
    }

    public void PublishData()
    {
        // publish data
    }

    public void GenerateTestReport(string userID, DateTime period)
    {
        string reportTestFilePath = this._workbookFactory.BuildTestReportWorkbook(userID, period);
    }

    #endregion
}
</code>```


答:
It is very hard (although in a language that has reflection not entirely impossible) to create a 100% decoupled application. With reflection, we can use this to allow the user to specify concrete classes for each object needed in the application at runtime (perhaps through a configuration file), thus achieving complete decoupling at the expense of increased complexity.

But a more important question to ask is why you would want to.

We try to decrease coupling in most of our code because coupling makes change harder, by causing a single change to have consequences for all of the code that is coupled to the module that was changed.

But if we group together all of the coupling in a single location, this problem is mitigated. A change to a module's behaviour may also require a change to the code that initialises the module, but because all such code is kept together no further changes propagate out of that initialisation code, so we don't experience the negative effects. This is good enough for almost all applications.

Title: Dependency Inversion & Decoupling

Body:
I'm wondering if someone might explain the last paragraph written in this example on Dependency Inversion & Decoupling.

http://www.springbyexample.org/examples/core-concepts.html

Following the example code, understanding the reasoning behind decoupling classes by implementing a base class is fine.

What I would like some clarification on is the last paragraph:

However, there is one problem with this implementation. We don’t have a main method. We > definitely need one in order to run our
  application, and somewhere in this main method we will need to
  instantiate the LocalVoteRecorder.

By instantiating the LocalVoteRecorder in our main method, we would
  break Rule #1 of Dependency Inversion. We have coded to the
  abstraction, we have integrated our changes, but our application would
  still have a dependency on a lower level class.

Does this mean it is not possible to create a truly decoupled application? How can it be that one could write a 100% decoupled application? Is it even necessary, and are there any best practices I could read up on.

Many thanks


问:
What are the differences between server-side and client-side programming?

I've seen questions (mainly on Stack Overflow), which lack this basic
  knowledge. The point of this question is to provide good information
  for those seeking it, and those referencing to it.

In the context of web programming, what are the differences between Server-side programming and Client-side programming? Which languages belong to which, and when do you use each of them?

答:
Other answers have focused on what is client-side and server-side programming: what languages are mostly used, what tasks have to be accomplished, etc.

This is absolutely right, but I miss a bit of focus on what are the differences between both types of programming, in the context of web programming.  Let me try to address that.

Security and permissions

In client-side programming, you do not have access to the full system, because of security concerns.  The user does not necessarily trust each and every piece of code that is downloaded from the web and executed on his machine, and this is the main design goal of the client-side environment (the browser and JavaScript engine): to provide an isolated environment where client code can execute but cannot access anything outside the allowed scope.

In server-side programming, it is good practice to also limit the access of each application to the underlying system, but this is much less enforced on you, since in the end, you or your company are in control of that system.  This 'isolated cage' design is not built-in into the server-side programming tools and languages, but is accomplished through installation setup (using dedicated users with restricted permissions, choosing ports that require or do not require root permissions, etc).

Deployment and platform

In server-side programming, deployment has to happen from outside your code, using some kind of tool (even if it is make install or a git clone), and this deployment is usually manual — or at least, it is expected to happen in a semi-supervised way.  The system (meaning the OS) on which you deploy is usually uniform across a number of machines, but it can be heavily customized to your needs.

In client-side programming, deployment happens from your server-side code, which serves the clients automatically and without supervision.  The underlying system (meaning mainly the browser) can be very different across a much larger number of machines.  In order to make deployment feasible at all, standards have to be kept, and there is a much stronger trend to a single language and environment.

This is why copying server-side code from one machine to another can take weeks, while client-side code is usually trivial to execute in different machines.

State and secondary effects

(Disclaimer: this is by far the most subjective point of all.  Probably there are many wrong aspects to my argumentation.  It is just an interesting hypothesis, in my view. )

In server-side programming, state is a much bigger concern, meaning how to retrieve and update data at the request of the user with the possibility of conflicts due to concurrency.  Even if most of this complexity is offloaded to a database server, it is the server-side code's responsibility to allow the database to keep its guarantees on data integrity by using its interface correctly (e.g. not use a cache for updates that are never seen by the DB), while it is also a goal of the server-side code not to overload the database with work and keep the user waiting for response.

In client-side programming, presenting the results to the user is a much bigger concern, and this implies secondary effects (mostly printing to the screen).  This is not to say that there is no state involved (e.g. cookies), only that the main goal of the code is to actually interface with the user, and this cannot happen without secondary effects.

This is why client-side programming usually requires (at some point) looking at the screen with a demo, to check that all colors and layout are right, while server-side programming can happen almost exclusively in a text-oriented environment, where automated tests check that the logic is still doing what it is supposed to do.


问:
Is there any value in writing a unit test that is a subset of another test?
To give a slightly contrived example, let's say I want to test that a function returns two numbers, and that the first one is smaller than the second one:

```<code>def test_length():
    result = my_function()
    assert len(result) == 2

def test_order()
    a, b = my_function()
    assert a < b
</code>```

Here, if test_length fails, then test_order will fail too. Is it a best practice to write test_length, or to skip it?

EDIT: note that in this situation, both tests are mostly independent from each other, each one can be run in isolation, or they could be run in reverse order, this does not matter. So none of these former questions

How should I test the functionality of a function that uses other functions in it?

Do I need unit test if I already have integration test?

How to structure tests where one test is another test's setup?

How to manage success dependency between unit tests

is a duplicate of the one above.

答:
There can be value, but this is a bit of a smell. Either your tests aren't well isolated (since test_order really tests two things) or you're being too dogmatic in your testing (making two tests testing the same logical thing).

In the example, I would merge the two tests together. Yes, it means you have multiple asserts. Too bad. You're still testing a single thing - the result of the function. Sometimes in the real world that means doing two checks.


答:
Your tests should be explicit. It's not completely inferred that if text_length fails test_order fails.

I'm not sure how it goes in Python which you've posted, but if len(result) is 3 then the first will fail but the second may pass (and if not in Python, then in languages like JavaScript for sure).

Like you said, you want to test that the function return two numbers and that they are in order. Two tests it is.

Title: Is there any value in writing a unit test that is a subset of another test?

Body:
To give a slightly contrived example, let's say I want to test that a function returns two numbers, and that the first one is smaller than the second one:

```<code>def test_length():
    result = my_function()
    assert len(result) == 2

def test_order()
    a, b = my_function()
    assert a < b
</code>```

Here, if test_length fails, then test_order will fail too. Is it a best practice to write test_length, or to skip it?

EDIT: note that in this situation, both tests are mostly independent from each other, each one can be run in isolation, or they could be run in reverse order, this does not matter. So none of these former questions

How should I test the functionality of a function that uses other functions in it?

Do I need unit test if I already have integration test?

How to structure tests where one test is another test's setup?

How to manage success dependency between unit tests

is a duplicate of the one above.


问:
Class as resource handle & Bad Copy
I am reading Bjarne Stroustrup's book titled "A tour of C++".

The following section is confusing to me:

When a class is a resource handle – that is, when the class is responsible for an object accessed through a pointer – the default member wise copy is typically a disaster.

Member wise copy would violate the resource handle’s invariant. For example, the default copy would leave a copy of a Vector referring to the same elements as the original:

```<code>void bad_copy(Vector v1)
{
    Vector v2 = v1;
    // copy v1’s representation into v2
    v1[0] = 2;
    // v2[0] is now also 2!
    v2[1] = 3;
    // v1[1] is now also 3!
}
</code>```

In particular, I do not understand the following:

When Vector v1 is passed as a value, not as a reference, how come v2 and v1 both refer to the same memory address.

What does the sentence "When a class is a resource handle" means ?

答:
What does the sentence "When a class is a resource handle" mean?

It means that the classes members are not actually the interesting data, but only pointers, references or other kinds of handles for it.

Thus, copying them does not copy the interesting data, meaning a member-by-member-copy is flat-out wrong.

Which also answers your other question.

For ensuring that you copy things right, take a look at "the rule of three" and its evolution "the rule of five".

Though if you have the choice (which is nearly always), follow "the rule of zero".

Title: Class as resource handle & Bad Copy


问:
When writing object-oriented code, should I always be following a design pattern?
Is there a conceivable design pattern for any object-oriented program? I ask this because recently I saw an implementation of a Door class with a Lock. It was part of a test and the answer said that the code is following the Null Object pattern:

class Lock
{
public:
    virtual void close() = 0;
    virtual void open() = 0;
    virtual bool is_open() const = 0;
    virtual ~Lock() { }
};

class DummyLock
    : public Lock
{
private:
    DummyLock();
    DummyLock(const DummyLock&) = delete;
    DummyLock& operator=(const DummyLock&) = delete;

private:
    void close() { }
    void open() { }
    bool is_open() const { return true; }

public:
    static DummyLock m_instance;
};

class Door
{
public:
    Door() : m_lock(DummyLock::m_instance) { }
    Door(Lock &lock) : m_lock(lock) { }

public:
    Lock& get_lock() const { return m_lock; }

private:
    Lock &m_lock;
};
```

This made me think: This code follows a good design pattern even though the description is so simple (this class is designing a door class with a lock), so if I am writing more complex code, should there always be some design pattern that I am following?

答:
When I am writing code, I do not plan on deliberately using as many design patterns as I can. But, I guess, sub-consciously, when I get a coding problem, one of the design patterns seems to fit, and I just use it. And sometimes nothing fits. What is more important to me is writing code that does the job and is easy to maintain and grow.

Here is an article on applying OOD principles using design patterns, and it has code examples as well (in C++). It shows how and when to apply some of the design patterns to write clean code.


答:
I'd just start out using no patterns.

```<code>var records = CheckTable();
foreach(var record in records)
{
    GenerateReport(record);
    SendEmail(record);
}
</code>```

Start simple, not everything needs a pattern.  If you start doing a lot of different tasks, or allow tasks to be configurable in the order and the number of tasks run per record, then think about abstracting it out by refactoring.

Title: Which Design Pattern Is Best Suited?

Body:
I'd just start out using no patterns.

var records = CheckTable();
foreach(var record in records)
{
    GenerateReport(record);
    SendEmail(record);
}

Start simple, not everything needs a pattern.  If you start doing a lot of different tasks, or allow tasks to be configurable in the order and the number of tasks run per record, then think about abstracting it out by refactoring.


答:
It sounds like (especially from the discussions in comments) you've boxed yourself in with self-imposed rules that mean that this "minor" change is the same amount of work as a complete rewrite of the software.

The solution has to be "don't do that, then". This is what happens in real projects. Plenty of old APIs have ugly interfaces or abandoned (always null) parameters as a result, or functions named DoThisThing2() which does the same as DoThisThing() with an entirely different parameter list. Other common tricks include stashing information in globals or tagged pointers in order to smuggle it past a large chunk of framework. (For example, I have a project where half the audio buffers contain only a 4-byte magic value because that was much easier than changing how a library invoked its audio codecs.)

It's hard to give specific advice without specific code.

Title: How do I avoid cascading refactorings?


答:
I am going to answer in opposite order, to make it clearer.

What does the sentence "When a class is a resource handle" means ?

A resource can be anything, from piece of memory, up to a file. Handling a resource means, opening a resource, providing access to it, closing it at the end.

For example, next class is going to allocate some memory in the constructor, release it in destructor, and provide a method to access it (I used c functions on purpose) :

```<code>class MemoryHandler
{
public:
    MemoryHandler() : mem( malloc(10) )
    {
    }
    ~MemoryHandler()
    {
        free(mem);
    }
    void* Access(){ return mem;}
    void* mem;
};
</code>```

So, what happens when you copy such object? If you are lucky, the program will crash.

```<code>void DoSomething( MemoryHandler m )
{
  // do something
}

MemoryHandler m;
DoSomething( m );
</code>```

Why it will crash? Because the function DoSomething will take the object by value, i.e. will create a new object using copy constructor, which is going to be released at the end of the scope. The default copy constructor will just blindly copy the pointer. Therefore, the cause of the crash will be double memory release.

The default copy constructor looks like this :

```<code>MemoryHandler( const MemoryHandler& object ) : mem( object.mem )
{
}
</code>```

How to solve this particular problem, depends on what you need. See std::shared_ptr if you want to make the class copyable, or std::unique_ptr to make your class movable.

When Vector v1 is passed as a value, not as a reference, how come v2 and v1 both refer to the same memory address.

You didn't say what vector is, but I assume that it looks something like in the above example.

To solve your problem, learn what Rule of five is, and apply it.

Title: Class as resource handle & Bad Copy

Body:
I am reading Bjarne Stroustrup's book titled "A tour of C++".

The following section is confusing to me:

When a class is a resource handle – that is, when the class is responsible for an object accessed through a pointer – the default member wise copy is typically a disaster.

Member wise copy would violate the resource handle’s invariant. For example, the default copy would leave a copy of a Vector referring to the same elements as the original:

```<code>void bad_copy(Vector v1)
{
    Vector v2 = v1;
    // copy v1’s representation into v2
    v1[0] = 2;
    // v2[0] is now also 2!
    v2[1] = 3;
    // v1[1] is now also 3!
}
</code>```

In particular, I do not understand the following:

When Vector v1 is passed as a value, not as a reference, how come v2 and v1 both refer to the same memory address.

What does the sentence "When a class is a resource handle" means ?

Body:
I am going to answer in opposite order, to make it clearer.

What does the sentence "When a class is a resource handle" means ?

A resource can be anything, from piece of memory, up to a file. Handling a resource means, opening a resource, providing access to it, closing it at the end.

For example, next class is going to allocate some memory in the constructor, release it in destructor, and provide a method to access it (I used c functions on purpose) :

class MemoryHandler
{
public:
    MemoryHandler() : mem( malloc(10) )
    {
    }
    ~MemoryHandler()
    {
        free(mem);
    }
    void* Access(){ return mem;}
    void* mem;
};

So, what happens when you copy such object? If you are lucky, the program will crash.

void DoSomething( MemoryHandler m )
{
  // do something
}

MemoryHandler m;
DoSomething( m );

Why it will crash? Because the function DoSomething will take the object by value, i.e. will create a new object using copy constructor, which is going to be released at the end of the scope. The default copy constructor will just blindly copy the pointer. Therefore, the cause of the crash will be double memory release.

The default copy constructor looks like this :

MemoryHandler( const MemoryHandler& object ) : mem( object.mem )
{
}

How to solve this particular problem, depends on what you need. See std::shared_ptr if you want to make the class copyable, or std::unique_ptr to make your class movable.

When Vector v1 is passed as a value, not as a reference, how come v2 and v1 both refer to the same memory address.

You didn't say what vector is, but I assume that it looks something like in the above example.

To solve your problem, learn what Rule of five is, and apply it.


答:
...I refactored the project to add the feature.

As said @Jules, Refactoring and adding features are two very different things.

Refactoring is about changing the program's structure without altering its behavior.

Adding a feature, on the other hand, is augmenting its behavior.

...but indeed, sometimes you need to change the inner workings to add your stuff, but I'd rather call it modifying rather than refactoring.

I needed to make a minor interface change to accommodate it

That's where things get messy. Interfaces are meant as bounderies to isolate the implementation from how it's used. As soon as you touch interfaces, everything on either side (implementing it or using it) will have to be changed as well. This can spread far as you experienced it.

then the consuming class can't be implemented with its current interface in terms of the new one, so it needs a new interface as well.

That one interface requires a change sounds fine ...that it spreads to another implies changes spread even further. It sounds like some form of input/data requires to flow down the chain. Is that the case?

Your talk is very abstract, so it's difficult to figure out. An example would be very helpful. Usually, interfaces should be pretty stable and independent from each other, making it possible to modify part of the system without harming the rest ...thanks to the interfaces.

...actually, the best way to avoid cascading code modifications are precisely good interfaces. ;)

Title: How do I avoid cascading refactorings?


答:
Sort of.  You can't avoid the coupling altogether.  The best you can do is trade one kind of coupling for a generally more desirable kind.  Instead of two concrete objects coupled with each other, they are each coupled to an abstract interface.

Also, you have to depend on a concrete implementation at some point.  Just because those dependencies are not resolved until runtime doesn't mean they don't exist.  Sometimes the programmer doesn't care which concrete implementation is used, but usually they need a way to specify it somehow, which means a configuration file.

So, while you can have a program without any concrete dependencies at compile time, usually it's not worth it unless you have some specific need to substitute specific classes at runtime.

Title: Dependency Inversion & Decoupling


问:
How to report progress on code research progress?
I am given a task which I need to do research on codebase and report my progress.

The dev environment is not set up. I can only read the code and analyze it, e.g. the workflow of user account creation.

There is a lot of uncertainty as my understanding on the code may not reflect the actual execution of the code.

I understand increase the visibility of my progress for everyone is good. But I don't know how to do it.

Thanks.

答:
Take notes.

Think about why you have been asked to do this? Are you a new hire, tasked with becoming familiar before you do actual development? Are you a consultant? Is this a project for school?

Think about the reason you have been tasked to do this, and write down (in a Word document or similar) the information that is most relevant to the task at hand. If you are really only doing this for yourself - e.g. because you are a new hire that they want to self-train before they give you programming tasks - write down the information that you will find most useful as a reference guide when you actually do have to do development.

Things you can write down:

Class structure and separation of concerns - try to figure out which major pieces go where.

Revelant API calls for the development you need to be doing

Things you would improve given the change, classes that need work, methods which should be refactored, performance bottlenecks.

Questions you would like to ask (thanks @rwong)


问:
ActiveRecord equivalent in Java
My question is fairly simple.. What is the closest ORM to ActiveRecord that I'd be able to find for Java?

In other words, in terms of thinking patterns and knowledge, with limted development time, what ORM should I use for Java, coming from a Rails + ActiveRecord background? Which one is both good enough and would be easy/quick enough to learn?

答:
ActiveRecord, the Ruby ORM, relies quite heavily on features of Ruby that are not available in Java, particularly the "method_missing" method and ability to create member variables dynamically. Implementations of Active Record, the pattern, on Java are therefore harder to work with than in Ruby. Typically, you have to accept one of the following shortcomings:

fields of your object are accessed via a generic "get(fieldName)" method rather than directly, thus meaning you lose type safety, the primary benefit of using Java rather than Ruby, or

you use generated code for your model classes, thus are restricted to having an "anemic model", which many consider an antipattern.

For this reason, most Java ORMs use the Repository or Data Access Object patterns, which make it easier to avoid these problems when working in a static language. The Active Record pattern is most commonly used by hand-coded persistence code, rather than ORMs.

I would recommend learning how to use the Repository pattern; it is slightly more complex than Active Record, requiring one extra object per model class, but is more flexible in the long run.

Title: ActiveRecord equivalent in Java


答:
I'm wondering if someone might explain the last paragraph:

The author says that having "Dependency Inversion & Decoupling" alone is not enought.

He means that "wiring the applicaton" by implementing a "main" method that constructs all classes is one option tu use the "independant modules"

In the next chapter he introduces, how to make "wiring the applicaton by code" a lot easier by introducing "Dependency Injection"

And later he introduces the spring-ioc that can do most of the wirining for you.

Does this mean it is not possible to create a truly decoupled application?

No but a ioc like spring can make it a lot easier if you have understood the principles behind.

Title: Dependency Inversion & Decoupling


问:
Questions for Architecture with Ruby and Java
I am in the research phase of a project that needs to make use of 3rd party libraries that are in Java so I am stuck using Java to at least a small degree.

I am considering implementing Ruby as the front-end layer.  That would leave me with the option of calling the Java classes as a web service by hitting a certain URL, is that correct?

Is that generally a solid approach to things?

Also, how would it affect my build environment when I create the .war file using Ant? should I have src/java and src/ruby code, or do the ruby files go somewhere else?

Any tips and pitfalls on this?  I am a little bit new to Ruby so advice would be appreciated.

Also, I considered JRuby, but it seemed like a less mature tool that just has a JVM for a smoother calling of Java classes, correct?  I am concerned with the maturity of that tool and its bein neither Java nor Ruby.

答:
From an architecture point of view, I like to separate entirely the two layers, through a communication layer (web services, rest services...), like a standard SOA architecture.

From my understanding, you have:

Frontend (Presentation Tier) which you plan to realize in Ruby

Backend (Business Tier) which you have to implement in Java

You may want to realize separate artifacts, so you may reach larger scale (e.g.: different servers for Presentation and Business Tier), and you may separate the business logic implementation to the rendering.


答:
The only value of test_length here is that, if everything passes, its very presence indicates that "length" has been tested.

So it's really unnecessary to have both these tests.  Keep only test_order but consider renaming it test_length_and_order.

Incidentally, I find the use of names that begin with test a bit clumsy.  I'm a strong advocate of test names that actually describe the condition that you're asserting.


问:
Is it normal for developers to make a lot of minute UX decisions?
To clarify, the UX professionals at my company are making the big decisions about what the general layout of the application should be, and they are providing wireframes which we follow as best we can whenever they make sense.

But when we go to implement a wireframe or feature request, it's extremely common to run into unexpected corner cases or details they simply forgot to specify. Then, one of the following happens:

1) If there's an obvious, simple solution that seems okay, we go with that. Sometimes UX asks for a more complicated solution later, but often they don't.

2) We explain the dilemma to UX so they can make the decision for us. Usually they answer the question, but often that answer isn't very detailed so we end up doing some of #1 or repeating #2.

3) The UX request is perfectly clear, but it's such a bad idea we do something else anyway. Usually they don't even notice, which we take as validation. Occasionally, they do ask for it to be "fixed" and then we begrudgingly do it anyway. Sometimes they change their mind after seeing it implemented.

Ideally, it seems like the UX professionals should be making all the UX decisions, i.e. we'd be doing #2 every single time. But we don't. In my opinion and/or experience, our UX people are good at overall designs but quite bad at thinking through the niggling little behavioral details that those designs imply, and most of our team seems to share that view. My team lead has even stopped me from doing #2 on a few occasions.

Is this a normal consequence of programmers and business/UX people having different skills and mindsets? Are we already handling this the right way? Should we be more obedient? Should we push them to give us more complete, well-thought out designs to begin with?

答:
Nice question :)

I fight through this question almost daily... Sometimes it may also happen that the wireframe is frankly not implementable in the time given!

For me, the only answer is friendly talk between UX specialist and programmers, before the wireframe is done and approved (after which, it can hardly be modified without raising an issue).

UX and programmers have different mindset (they sell "the Dream", while programmers have to deliver that...), which can produce a good work only if they are both contributing in the wireframe design and implementation, so, don't be afraid to ask for support during implementation, and offer support and review during wireframe design.


问:
Is WCF strictly an asynchonous comms platform?
Since I last had to do any comms/network programming, the field has exploded with acronyms. In fact, networking almost feels like it is now described by a whole new language.

The very name "Windows Communication Foundation" suggests it should be all things to all people... but I need to be sure I can program up some synchronous real-time* comms on a dedicated gigabit ethernet network. Can someone confirm that WCF is not a starter for this task... or if it is, which of the many confusing acronyms I should get familiar with?

* By real-time, I mean I need to reduce latencies down to an acceptably low level. For our application, which involves transmitting results of video & audio analyses continuously every few milliseconds,  I need to ensure 99% or better of those analyses are presented at the UI within (ideally) 0.5 seconds so that the user has time to respond before the originating network node deletes data out of its buffer to make way for subsequent analyses.

答: For real time programming needs the Microsoft solution is SignalR. Other options would be to use web sockets which are new in HTML 5 or good old fashioned socket programming. It sounds like you need to do video/audio streaming, in which case there are other libraries dedicated to that which could be more helpful. WCF is XML/JSON over HTTP which does have an overhead cost if you are planning to send lots of continuous data, it would be better to use a technology that works at a lower level to reduce that overhead.</p>


答:
Yes it is normal that once you start implementing a program following a written specification, you will discover lots of unclear, ambiguous and missing details in the spec. That will occur even sometimes when you have written the spec by yourself, but it will definitely occur when the spec was written by non-programmers, system analysts, or in your case UX people.

In fact, that is not a new insight into programming - it is just one of the main reasons why the "waterfall model" does not work (even though some non-programmers, system analysts, or UX people might have a different opinion).

Title: Is it normal for developers to make a lot of minute UX decisions?

Body:
To clarify, the UX professionals at my company are making the big decisions about what the general layout of the application should be, and they are providing wireframes which we follow as best we can whenever they make sense.

But when we go to implement a wireframe or feature request, it's extremely common to run into unexpected corner cases or details they simply forgot to specify. Then, one of the following happens:

1) If there's an obvious, simple solution that seems okay, we go with that. Sometimes UX asks for a more complicated solution later, but often they don't.

2) We explain the dilemma to UX so they can make the decision for us. Usually they answer the question, but often that answer isn't very detailed so we end up doing some of #1 or repeating #2.

3) The UX request is perfectly clear, but it's such a bad idea we do something else anyway. Usually they don't even notice, which we take as validation. Occasionally, they do ask for it to be "fixed" and then we begrudgingly do it anyway. Sometimes they change their mind after seeing it implemented.

Ideally, it seems like the UX professionals should be making all the UX decisions, i.e. we'd be doing #2 every single time. But we don't. In my opinion and/or experience, our UX people are good at overall designs but quite bad at thinking through the niggling little behavioral details that those designs imply, and most of our team seems to share that view. My team lead has even stopped me from doing #2 on a few occasions.

Is this a normal consequence of programmers and business/UX people having different skills and mindsets? Are we already handling this the right way? Should we be more obedient? Should we push them to give us more complete, well-thought out designs to begin with?


问:
Traversing an AST using Visitors
I'm writing a compiler for a C-like language, and I'm looking for an elegant way to traverse my abstract syntax tree. I'm trying to implement the Visitor pattern, although I'm not convinced that I'm doing it correctly.

```<code>struct Visitor {
    // Expressions
    virtual void visit(AsgnExpression&);
    virtual void visit(ConstantExpression&);
    ...
    virtual void visit(Statement&);
    ...

    virtual void finished(ASTNode&);

protected:
    virtual void visit(ASTNode&) = 0;
};
</code>```

visit is overloaded for each type, and by default each overload will call visit(ASTNode&) which subclasses are forced to implement. This makes it easier to do quick and dirty things, although defining a visit for each type is tedious. Each subclass of ASTNode must implement an accept method which is used to traverse the tree structure.

```<code>class ASTNode {
public:
    virtual ~ASTNode();
    virtual void accept(Visitor& visitor) = 0;
};
</code>```

However, this design is quickly becoming tedious because the accept methods are often very similar.

Who should be responsible for traversing the structure, the nodes or the visitor? I'm leaning towards having ASTNode provide an iterator for accessing its children, and then having the visitor traverse the structure. If you have any experience designing Abstract Syntax Trees, please share your wisdom with me!

答:
Different problems need different traversal strategies.  Therefore my suggestion would be to implement a separate Traverser using the strategy pattern.

The Visitor pattern can require alot of boilerplate code.  Its actually well-suited to automated code-generation (see Java's jaxb-visitor).   My suggestion is to implement a basic/default visitor that basically does nothing for every node type.  Any visitors that are going to do anything interesting should extend the base boilerplate visitor.   When a new node type is added to the visitor interface, you only have to provide the empty implementation in the base class.  Otherwise, every time you add a new node type you have to hunt-down all the implementations and add the new method.

Title: Traversing an AST using Visitors


问:
Ruby Terminology Question: Implicit Declaration or no declaration at all?
I have a question, because in most serious sources I read, all say the same No variable is ever declared in Ruby, but still I have doubts, because according to what I was taught in my university implicit declaration is when a variable is created via allocation, where you can specify the type of a variable through conventions established in the language.

This contrasts with explicit declaration, when the data type specified in its declaration, like C... or at least that's what I understood.

So I was taught wrong?, or I misunderstood something?

答:
What they said:

No variable is ever declared in Ruby

What they meant:

There is no keyword defining a line of code as declaring a variable. Variables can just be used, and at worst are nil.

If you have not previously assigned a value to a variable in Ruby, it becomes nil as soon as you retrieve its value.

```<code>class Foo
  def bar
    @bar
  end
end

a = Foo.new
puts a.bar
</code>```

You weren't taught wrong. They just describe it in a non academic way.

Body:
What they said:

No variable is ever declared in Ruby

What they meant:

There is no keyword defining a line of code as declaring a variable. Variables can just be used, and at worst are nil.

If you have not previously assigned a value to a variable in Ruby, it becomes nil as soon as you retrieve its value.

class Foo
  def bar
    @bar
  end
end

a = Foo.new
puts a.bar

You weren't taught wrong. They just describe it in a non academic way.


答:
I worked on a system that had a large Java application side, and a large Ruby side (both a Rails web site and JSON API). Beware the compatibility issues that can crop up when you keep two copies of domain models written in two different languages. You have to carefully plan your production releases so one application doesn't introduce data in the database that the other application finds problematic. What you are proposing is Distributing your Objects. More and more I like to heed Martin Fowler's advice here:

The first rule of distributing your objects is don't distribute your objects!

Source: Microservices and the First Law of Distributed Objects

If you need a set of web services, you need to ask yourself "Why?"

If you need to support both web and native mobile platforms, then you may have a use case for doing what you are proposing. If you want to create web services because you have to use Java, but you really want to use Ruby then you are adding layers of complexity and maintenance for the convenience of Ruby. From personal experience, this is not worth it.

More on Fowler's distaste for "distributed objects":

My objection to the notion of distributed objects was although you can encapsulate many things behind object boundaries, you can't encapsulate the remote/in-process distinction. An in-process function call is fast and always succeeds (in that any exceptions are due to the application, not due to the mere fact of making the call). Remote calls, however, are orders of magnitude slower, and there's always a chance that the call will fail due to a failure in the remote process or the connection.

Title: Questions for Architecture with Ruby and Java

Body:
I am in the research phase of a project that needs to make use of 3rd party libraries that are in Java so I am stuck using Java to at least a small degree.

I am considering implementing Ruby as the front-end layer.  That would leave me with the option of calling the Java classes as a web service by hitting a certain URL, is that correct?

Is that generally a solid approach to things?

Also, how would it affect my build environment when I create the .war file using Ant? should I have src/java and src/ruby code, or do the ruby files go somewhere else?

Any tips and pitfalls on this?  I am a little bit new to Ruby so advice would be appreciated.

Also, I considered JRuby, but it seemed like a less mature tool that just has a JVM for a smoother calling of Java classes, correct?  I am concerned with the maturity of that tool and its bein neither Java nor Ruby.


问:
Releasing updates to Windows Services and Websites from build
I've got an solution which consists of Windows Services and websites.  When updating the applications currently, the following steps are undertaken

Build of solution

Post build tasks copy the DLLs to a specific application folder

Build script is ran which gathers the DLLs relevant for each application (this is done via a text file containing a list of the DLLs per application, this needs to be changed if another DLL is added to the project). This is then stuffed in a release repository and pushed up to Github

Release repository is checked out on the server and a script is run to overwrite the DLLs and exes of both the Windows services and websites.  All of this is done via XCopy along with some Windows service commands to Start/Stop services.

I was wondering how to make this a bit easier? Or whether someone in a similar scenario does it differently?

答:
Yes and no.

Yes because it would not be hard to fix the pain points in step 2 or 3 without much trouble -- just redo your packaging to call msbuild on individual projects with a desired output directory so you don't have to maintain the file lists at least.

Yes because you could probably dodge the whole github package by perhaps deploying your built artifiacts to the machine.

No because your deployment script is probably just about what you'd need for your one-off app and it is getting the job done and there might not be a better way to get there as most of the new toys are cloud-facing and windows services implies not cloud-facing.

You might also want to look at using something like teamcity or jenkins to orchestrate, record and otherwise manage the process.


问:
Entry point constructor vs init(),run() etc
Lets suppose we have some Js Widget, that includes three objects view, controller, model.

```<code>var MyWidget=function(){
 this.setModel(new Model());
 this.setView(new View());
 this.setController(new Controller());
 ...
}
</code>```

And I create this widget this way widget=new MyWidget();

There must be some enty point to start this widget.My question is - what is the best practise (and why) to define entry point: in constructor or in some method (run,init,etc). I mean:

```<code>widget=new MyWidget(); //to create AND start widget
</code>```

vs

```<code>widget=new MyWidget() //to create
widget.run();  //to start
</code>```

答:
This depends on how complex the widget is. You can create and start a widget as long as you pass it all information and dependencies to make it operational. If you have a complex class that relies on many other classes to do specialized work, then you need to instantiate all those helper objects in the constructor function, or pass them in as arguments. This can become cumbersome as the external dependencies for a class start increasing. At some point a "widget" ends up with this basic life cycle:

Instantiation - Bring the object to life, e.g. call its constructor function

Configuration - Assign dependencies and give the object all the information it needs to operate

Initialization - The initial heavy lifting to start responding to the user. Things like event handlers are set up in this phase

Use - The object is available to interact with the user

Destruction - The widget is no longer needed and should be readied for garbage collection. In JavaScript, this is a manual process

If your widget doesn't need much from the outside world, then an "init" or "run" method is just extra typing.

If you want to leverage dependency injection and inversion of control, constructor injection becomes difficult to maintain, so you might need the multi step lifecycle outlined above.


答:
Instead of looking for better tools, did you try to get most of the tools you already have? In our environment, we often create scripts for such a process, and (that is the important point!) make them rock-solid:

Build of solution

You can do a build by calling devenv.exe or msbuild on the command line, so that's easily to put that into a script.

Build script is ran which gathers the DLLs relevant for each application

Fine, already automatic. Make sure that script you mentioned here returns an error code in case it fails.

This is then stuffed in a release repository and pushed up to Github

Should be simple to be scripted, using git from command line.

Release repository is checked out on the server and a script is run to overwrite the DLLs and exes of both the Windows services and websites. All of this is done via XCopy along with some Windows service commands to Start/Stop services.

So already scripted - perfect.

To give this process a certain robustness, you have to make sure your script contains full error checking after each step, and display which step failed in case of failure. For example, call "devenv.exe", pipe the output to a build.log and use the find command to check if it contains the line "0 errors" (or something similar). After each step, always check %ERRORLEVEL% and stop if it becomes different from 0.

Title: Releasing updates to Windows Services and Websites from build

Body:
I've got an solution which consists of Windows Services and websites.  When updating the applications currently, the following steps are undertaken

Build of solution

Post build tasks copy the DLLs to a specific application folder

Build script is ran which gathers the DLLs relevant for each application (this is done via a text file containing a list of the DLLs per application, this needs to be changed if another DLL is added to the project). This is then stuffed in a release repository and pushed up to Github

Release repository is checked out on the server and a script is run to overwrite the DLLs and exes of both the Windows services and websites.  All of this is done via XCopy along with some Windows service commands to Start/Stop services.

I was wondering how to make this a bit easier? Or whether someone in a similar scenario does it differently?