问:
Why use an opaque "handle" that requires casting in a public API rather than a typesafe struct pointer?
I'm evaluating a library whose public API currently looks like this:

libengine.h

```<code>/* Handle, used for all APIs */
typedef size_t enh;

/* Create new engine instance; result returned in handle */
int en_open(int mode, enh *handle);

/* Start an engine */
int en_start(enh handle);

/* Add a new hook to the engine; hook handle returned in h2 */
int en_add_hook(enh handle, int hooknum, enh *h2);
</code>```

Note that enh is a generic handle, used as a handle to several different datatypes (engines and hooks).

Internally, most of these APIs of course cast the "handle" to an internal structure which they've malloc'd:

engine.c

```<code>struct engine
{
    // ... implementation details ...
};

int en_open(int mode, *enh handle)
{
    struct engine *en;

    en = malloc(sizeof(*en));
    if (!en)
        return -1;

    // ...initialization...

    *handle = (enh)en;
    return 0;
}

int en_start(enh handle)
{
    struct engine *en = (struct engine*)handle;

    return en->start(en);
}
</code>```

Personally, I hate hiding things behind typedefs, especially when it compromises type safety. (Given an enh, how do I know to what it's actually referring?)

So I submitted a pull request, suggesting the following API change (after modifying the entire library to conform):

libengine.h

```<code>struct engine;           /* Forward declaration */
typedef size_t hook_h;    /* Still a handle, for other reasons */

/* Create new engine instance, result returned in en */
int en_open(int mode, struct engine **en);

/* Start an engine */
int en_start(struct engine *en);

/* Add a new hook to the engine; hook handle returned in hh */
int en_add_hook(struct engine *en, int hooknum, hook_h *hh);
</code>```

Of course, this makes the internal API implementations look a lot better, eliminating casts, and maintaining type safety to/from the consumer's perspective.

libengine.c

```<code>struct engine
{
    // ... implementation details ...
};

int en_open(int mode, struct engine **en)
{
    struct engine *_e;

    _e = malloc(sizeof(*_e));
    if (!_e)
        return -1;

    // ...initialization...

    *en = _e;
    return 0;
}

int en_start(struct engine *en)
{
    return en->start(en);
}
</code>```

I prefer this for the following reasons:

Added type safety

Improved clarity of types and their purpose

Removed casts and typedefs

It follows the recommended pattern for opaque types in C

However, the owner of the project balked at the pull request (paraphrased):

Personally I don't like the idea of exposing the struct engine. I still think the current way is cleaner & more friendly.

Initially I used another data type for hook handle, but then decided to switch to use enh, so all kind of handles share the same data type to keep it simple. If this is confusing, we can certainly use another data type.

Let's see what others think about this PR.

This library is currently in a private beta stage, so there isn't much consumer code to worry about (yet). Also, I've obfuscated the names a bit.

How is an opaque handle better than a named, opaque struct?

Note: I asked this question at Code Review, where it was closed.

答:
Here are a situation where opaque handle is needed;

```<code>struct SimpleEngine {
    int type;  // always SimpleEngine.type = 1
    int a;
};

struct ComplexEngine {
    int type;  // always ComplexEngine.type = 2
    int a, b, c;
};

int en_start(enh handle) {
    switch(*(int*)handle) {
    case 1:
        // treat handle as SimpleEngine
        return start_simple_engine(handle);
    case 2:
        // treat handle as ComplexEngine
        return start_complex_engine(handle);
    }
}
</code>```

When the library has two or more struct types that have a same header part of fields, like "type" in the above, these struct types can be considered having a common parent struct (like a base class in C++).

You can define the header part as "struct engine", like this;

```<code>struct engine {
    int type;
};

struct SimpleEngine {
    struct engine base;
    int a;
};

struct ComplexEngine {
    struct engine base;
    int a, b, c;
};

int en_start(struct engine *en) { ... }
</code>```

But it's a optional decision because type-casts are needed regardless of using struct engine.

Conclusion

In some case, there are reasons why opaque handles are used instead of opaque named structs.

Body:
Here are a situation where opaque handle is needed;

struct SimpleEngine {
    int type;  // always SimpleEngine.type = 1
    int a;
};

struct ComplexEngine {
    int type;  // always ComplexEngine.type = 2
    int a, b, c;
};

int en_start(enh handle) {
    switch(*(int*)handle) {
    case 1:
        // treat handle as SimpleEngine
        return start_simple_engine(handle);
    case 2:
        // treat handle as ComplexEngine
        return start_complex_engine(handle);
    }
}

When the library has two or more struct types that have a same header part of fields, like "type" in the above, these struct types can be considered having a common parent struct (like a base class in C++).

You can define the header part as "struct engine", like this;

struct engine {
    int type;
};

struct SimpleEngine {
    struct engine base;
    int a;
};

struct ComplexEngine {
    struct engine base;
    int a, b, c;
};

int en_start(struct engine *en) { ... }

But it's a optional decision because type-casts are needed regardless of using struct engine.

Conclusion

In some case, there are reasons why opaque handles are used instead of opaque named structs.


问:
Possible way to make java class builder more abstract by using interface required keys
I'm looking for a more abstract pattern for builders that handles required
fields without the need of writing a validator that checks if all requried fields are set.

I like this builder. But is there a way to make the interfaces more abstract
so that I don't need to create a new interface for each required field?

```<code>public class Example {

    private String first;
    private String second;
    private String third;
    private String fourth;
    private String fifth;

    public static RequiredSecond builder(String first) {
        return new ExampleBuilder(first);
    }

    public interface RequiredSecond {
        RequiredThird withSecond(String second);
    }

    public interface RequiredThird {
        RequiredFourth withThird(String third);
    }

    public interface RequiredFourth {
        Build withFourth(String fourth);
    }

    public interface Build {
        Build withFifth(String fifth);

        Example build();
    }

    private static class ExampleBuilder implements RequiredSecond, RequiredThird, RequiredFourth, Build {
        Example example = new Example();

        public ExampleBuilder(String first) {
            example.setFirst(first);
        }

        @Override
        public Build withFifth(String fifth) {
            example.setFifth(fifth);
            return this;
        }

        @Override
        public Example build() {
            return example;
        }

        @Override
        public Build withFourth(String fourth) {
            example.setFourth(fourth);
            return this;
        }

        @Override
        public RequiredFourth withThird(String third) {
            example.setThird(third);
            return this;
        }

        @Override
        public RequiredThird withSecond(String second) {
            example.setSecond(second);
            return this;
        }
    }

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getSecond() {
        return second;
    }

    public void setSecond(String second) {
        this.second = second;
    }

    public String getThird() {
        return third;
    }

    public void setThird(String third) {
        this.third = third;
    }

    public String getFourth() {
        return fourth;
    }

    public void setFourth(String fourth) {
        this.fourth = fourth;
    }

    public String getFifth() {
        return fifth;
    }

    public void setFifth(String fifth) {
        this.fifth = fifth;
    }

    @Override
    public String toString() {
        return "Example [first=" + first + ", second=" + second + ", third=" + third + ", fourth=" + fourth +
                ", fifth=" + fifth + "]";
    }

}
public class Labb {

    public static void main(String[] args) {
        // All required including optional
        Example ex1 = Example.builder("first").withSecond("second").withThird("third").withFourth("fourth").withFifth("optional fith").build();
        System.out.println(ex1);
        // Output: Example [first=first, second=second, third=third, fourth=fourth, fifth=optional fith]

        // All required excluding optional
        Example ex2 = Example.builder("first").withSecond("second").withThird("third").withFourth("fourth").build();
        System.out.println(ex2);
        // Output: Example [first=first, second=second, third=third, fourth=fourth, fifth=null]
    }
}
</code>```

答:
I like this builder.

Do you really need a Builder in your case ? Liking a pattern is not enough to justify its use.

Upto 4-5 arguments, creating instances of your class directly by the constructor greatly simplify your code, plus allows you to make your class immutable.

```<code>public final class Example {
    private final String first;
    private final String second;
    private final String third;
    private final String fourth;
    private final String fifth;

    public Example(final String first, final String second, final String third, final String fourth, final String fifth) {
        ...
    }

    @Override
    public final String toString() {
        return "Example [first=" + first + ", second=" + second + ", third=" + third + ", fourth=" + fourth + ", fifth=" + fifth + "]";
    }

    public final String getFirst() {
        return first;
    }

    ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I like this builder.

Do you really need a Builder in your case ? Liking a pattern is not enough to justify its use.

Upto 4-5 arguments, creating instances of your class directly by the constructor greatly simplify your code, plus allows you to make your class immutable.

public final class Example {
    private final String first;
    private final String second;
    private final String third;
    private final String fourth;
    private final String fifth;

    public Example(final String first, final String second, final String third, final String fourth, final String fifth) {
        ...
    }

    @Override
    public final String toString() {
        return "Example [first=" + first + ", second=" + second + ", third=" + third + ", fourth=" + fourth + ", fifth=" + fifth + "]";
    }

    public final String getFirst() {
        return first;
    }

    ...
}


问:
Will issues arise packaging libc and pthread with your C apps?
The issue I hit, is that I am packaging shared libraries with my code in order to load GNUTLS, except for libc, because I figured any system will have it. Most of them don't have the required 2.14 for it(except for Ubuntu or others with daunting upgrades and repo butchering). I know it's bad form to be dependent like that, but I need a very recent build of GNUTLS, so it was the only solution I thought of.

In order to solve the libc issue, is it safe to package libc & pthread(another dependent), with my program? My program is Java, using JNI to load these libraries if that's relevant. This is also all for Linux.

答:
libc is so central to Linux systems (see also nnsswitch.conf(5)) that I would avoid shipping my own one. Most systems have GNU libc (latest version is 2.22 since august 2015; my stable Debian/Jessie has a 2.19 GNU libc; another computer running Linux/Mint has a 2.17 GNU libc). So I feel that a 2.14 GNU libc (published in 2011) is quite ancient these days. Some Linux distributions might use other C standard libraries like musl-libc

Did you consider instead having some installation procedure (perhaps just make install) which check first that the libc is recent enough, and otherwise fail with a meaningful error message?

The current version of GNUTLS is 3.3.17 (since august 2015). You could ship it if so needed.

Pthreads are part of GNU libc (even if sometimes GNU libc also install a separate libpthread.so library) since NPTL.

BTW if you are developing free software, you might publish it as source code, package it for a one or two distributions, and put the burden of packaging it for other distributions on them.


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答:
Often I use my own because I built it before I discovered the pre-existing one, and I am too lazy to go find and replace every instance. Also, I fully understand my own method while I might not understand a pre-existing one. And finally, because I do not fully understand the pre-existing one I cannot verify that it does absolutely everything that my current one does.

There's a lot to code, and I don't get a lot of time to go back and re-code something unless it impacts production.

In fact, one asp web app that is still used today has a fully functional chart which displays data in a tabular format and allows sorting/editing, however it is not a datagrid. It was built a few years back when I was first learning asp.net and didn't know of datagrids. I am kind of scared of the code since I have no clue what I was doing back then, but it works, is accurate, is easy to modify, doesn't crash, and the users love it

ContentLicense: CC BY-SA 2.5


问:
When to use generics in interface design
I have some interfaces that I intend third-parties to implement in the future, and I provide a base implementation myself. I'll only be using a couple to show the example.

Currently, they are defined as

Item:

```<code>public interface Item {

    String getId();

    String getName();
}
</code>```

ItemStack:

```<code>public interface ItemStackFactory {

    ItemStack createItemStack(Item item, int quantity);
}
</code>```

ItemStackContainer:

```<code>public interface ItemStackContainer {

    default void add(ItemStack stack) {
        add(stack, 1);
    }

    void add(ItemStack stack, int quantity);
}
</code>```

Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future. ItemStackContainer could also be extended in the future, but not in ways that I can foresee, outside my provided default implementation.

Now, I'm trying to make this library as robust as possible; this is still in the early-stages (pre-pre-alpha) so this may be an act of over engineering (YAGNI). Is this an appropriate place to use generics?

```<code>public interface ItemStack<T extends Item> {

    T getItem();

    int getQuantity();
}
</code>```

And

```<code>public interface ItemStackFactory<T extends ItemStack<I extends Item>> {

    T createItemStack(I item, int quantity);
}
</code>```

I fear that this may end up making implementations and usage more difficult to read and understand; I think it's the recommendation to avoid nesting generics wherever possible.

答:
I think that using generics in your situation is too complex.

If you choice generics version of interfaces, the design indicates that

ItemStackContainer contains a single type of stack, A. (i.e. ItemStackContainer can't contain multiple types of stack.)

ItemStack is dedicated to a specific type of item. So there is no abstraction type of all kind of stacks.

You need to define a specific ItemStackFactory for each type of items. It's considered too fine as Factory Pattern.

Write more difficult code such as ItemStack< ? extends Item >, decreasing maintainability.

These implicit assumptions and restrictions are very important things to decide carefully. So especially in early-stage, these premature designs should not be introduced. Simple, easy to understand, common design is desired.

Body:
I think that using generics in your situation is too complex.

If you choice generics version of interfaces, the design indicates that

ItemStackContainer< A > contains a single type of stack, A. (i.e. ItemStackContainer can't contain multiple types of stack.)

ItemStack is dedicated to a specific type of item. So there is no abstraction type of all kind of stacks.

You need to define a specific ItemStackFactory for each type of items. It's considered too fine as Factory Pattern.

Write more difficult code such as ItemStack< ? extends Item >, decreasing maintainability.

These implicit assumptions and restrictions are very important things to decide carefully. So especially in early-stage, these premature designs should not be introduced. Simple, easy to understand, common design is desired.


问:
Why override a static method of an abstract base class?
I'm working on C# code where a static method of an abstract base class is being overridden by the class that inherits the base class. Why is this being done? I thought that only a virtual method of an abstract base class should be overridden. What purpose does it serve to make the base method static, or is it the case that what I'm encountering is a suboptimal or incorrect practice? The code is allowed by the compiler.

My understanding is that a static method allows the method to be called without the encompassing type being instantiated as an object. I've only used static methods previously in static classes, and I've viewed abstract classes as simply being inheritable classes that aren't supposed to be instantiated. In this case, I wouldn't expect a static method of the abstract class to be overrideable but made virtual, as a virtual method could still contain a default implementation, and I would think that a virtual method better hides the implementation details.

答:
Overloading of static methods should not be compared to overriding of instance methods. They are fundamentally different concepts.

Overriding is when implementations of a virtual method are selected at runtime based on the instance. Overloading is when one of multiple methods with the same name are selected at compile time. Overriding is a fundamental feature of object oriented polymorphism, while overloading is more like a convenience.

On the surface, overloading static methods may look like overriding. If the compiler does not find a static method in the specified class, it looks up in the inheritance hierarchy until a matching method is found. The important difference is that the method is resolved and fixed at compile time. This is why you cannot mark static methods as virtual or override (or new) since this is not real overriding.

Overriding should conform to the LSP (Liskov substitution principle) and more generally the behavior of an overriding method should conform to the contract of the virtual method. Overloaded static methods does not have such constraints, and should really be though of as distinct methods which just happen to have the same name.


答:
I'd say it depends mainly on this question: If someone needs to extend the functionality of Item and ItemStackFactory,

will they just overwrite methods and so instances of their subclases will be used just like the base classes, just behave differently?

or will they add members and use the subclasses differently?

In the first case, there is no need for generics, in the second, there probably is.

Title: When to use generics in interface design

Body:
I have some interfaces that I intend third-parties to implement in the future, and I provide a base implementation myself. I'll only be using a couple to show the example.

Currently, they are defined as

Item:

```<code>public interface Item {

    String getId();

    String getName();
}
</code>```

ItemStack:

```<code>public interface ItemStackFactory {

    ItemStack createItemStack(Item item, int quantity);
}
</code>```

ItemStackContainer:

```<code>public interface ItemStackContainer {

    default void add(ItemStack stack) {
        add(stack, 1);
    }

    void add(ItemStack stack, int quantity);
}
</code>```

Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future. ItemStackContainer could also be extended in the future, but not in ways that I can foresee, outside my provided default implementation.

Now, I'm trying to make this library as robust as possible; this is still in the early-stages (pre-pre-alpha) so this may be an act of over engineering (YAGNI). Is this an appropriate place to use generics?

```<code>public interface ItemStack<T extends Item> {

    T getItem();

    int getQuantity();
}
</code>```

And

```<code>public interface ItemStackFactory<T extends ItemStack<I extends Item>> {

    T createItemStack(I item, int quantity);
}
</code>```

I fear that this may end up making implementations and usage more difficult to read and understand; I think it's the recommendation to avoid nesting generics wherever possible.


问:
Where does the term "Red/Black Tree" come from?
A Red/Black Tree is one way to implement a balanced binary search tree.  The principles behind how it works make sense to me, but the chosen colors don't.  Why red and black, as opposed to any other pair of colors or of attributes in general?  When I hear "red and black," the first things that come to mind are checkerboards and Les Misérables, neither of which seems particularly applicable in this context.</p>

答:
In Coursera, Red-Black BSTs (2012), Robert Sedgewick says this:

A lot of people ask why did we use the name red–black. Well, we
  invented this data structure, this way of looking at balanced trees,
  at Xerox PARC which was the home of the personal computer and many
  other innovations that we live with today entering[sic] graphic user
  interfaces, ethernet and object-oriented programmings[sic] and many
  other things. But one of the things that was invented there was laser
  printing and we were very excited to have nearby color laser printer
  that could print things out in color and out of the colors the red
  looked the best. So, that’s why we picked the color red to distinguish
  red links, the types of links, in three nodes. So, that’s an answer to
  the question for people that have been asking.


答:
I think the case of a developer knowingly reinventing the wheel "because he prefers his own method" is pretty rare. Mostly it's done out of ignorance, and sometimes out of stubbornness.

Is it all that bad? Yes. Why? Because the existing wheel has most likely been crafted over time and has already been tested in lots of circumstances and against lots of different kinds of data. The developer(s) of the existing wheel have already encountered the edge-cases and difficulties that the reinventor can't even imagine yet.

Title: Is reinventing the wheel really all that bad?

Body:
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?


答:
In addition to @JacquesB-s excelent (+1) answer

Why override overload a static method?

I have seen usecases in java where there were static factory methods

```<code>public class Customer {
   public static Customer newInstance(String name) {} ....

public class BusinessCustomer extends Customer  {
   public static BusinessCustomer  newInstance(String name) {} ....
</code>```

The reason for overloading is that both newInstance() versions have the same signature so they can be easily exchanged in sourcecode.

```<code>Customer customer1 = Customer.newInstance("peter");
Customer customer2 = BusinessCustomer.newInstance("paul");
</code>```

Title: Why override a static method of an abstract base class?

Body:
I'm working on C# code where a static method of an abstract base class is being overridden by the class that inherits the base class. Why is this being done? I thought that only a virtual method of an abstract base class should be overridden. What purpose does it serve to make the base method static, or is it the case that what I'm encountering is a suboptimal or incorrect practice? The code is allowed by the compiler.

My understanding is that a static method allows the method to be called without the encompassing type being instantiated as an object. I've only used static methods previously in static classes, and I've viewed abstract classes as simply being inheritable classes that aren't supposed to be instantiated. In this case, I wouldn't expect a static method of the abstract class to be overrideable but made virtual, as a virtual method could still contain a default implementation, and I would think that a virtual method better hides the implementation details.

Body:
In addition to @JacquesB-s excelent (+1) answer

Why override overload a static method?

I have seen usecases in java where there were static factory methods

public class Customer {
   public static Customer newInstance(String name) {} ....

public class BusinessCustomer extends Customer  {
   public static BusinessCustomer  newInstance(String name) {} ....

The reason for overloading is that both newInstance() versions have the same signature so they can be easily exchanged in sourcecode.

Customer customer1 = Customer.newInstance("peter");
Customer customer2 = BusinessCustomer.newInstance("paul");


问:
What are your favorite version control systems?
This is more a discussion question than an actual attempt to determine the "best", since that clearly varies by the needs of the organization. I'm more curious about the arguments in favor of different systems across categories (centralized vs distributed, open vs proprietary, etc).

So, what do you think is the best version control system?

答:
I don't have a single "best" version control system, but rather a single best VCS paradigm.

I have used multiple different centralized version control systems and multiple different distributed version control systems. And I can say without hesitation that noone should ever inflict a CVCS upon themselves.

I don't care which DVCS you choose (my particular favorite is Git), but please do yourself a favor and use a DVCS. For one: you will be much more flexible. DVCSs can trivially emulate a CVCS workflow (just never fork the repository, and treat your local repositories only as a chache instead of an independent fork), whereas the converse is impossible. And while logically, doing this emulation should carry some overhead (and indeed it does), I still find it easier to use (not to mention much more performant due to the local caching) than any of the CVCSs I have used.


答:
There are two sorts of efficiency - processing / speed (that is how quickly it executes) which it may match and development speed which it almost certainly won't.  That's the first reason - for any problem of reasonable complexity where existing solutions are available it will almost certainly be faster to research and implement an existing library than to code your own.

The second reason is that the existing library (assuming it's mature) is tested and is proven to work - probably in a far wider range of scenarios than a developer and a test team will be able to put a newly written routine through and this comes at zero effort.

Thirdly, it's way easier to support.  Not only does someone else supports and improves it (whoever wrote the library / component), but it's far more likely that other developers will be familiar with it and be able to understand and maintain the code going forward, all of which minimises on-going costs.

And all that assumes functional equivalence, which isn't normally the case.  Frequently libraries will offer functionality which you would find useful but could never justify building in, all of which is suddenly available for free.

There are reasons to roll your own - largely where you want to do something the built in function can't do and where there is a genuine advantage to be gained by doing so, or where the readily available options aren't mature - but they're less common than many developers would have you believe.

Besides, why would you want to spend your time solving problems that have already been solved?  Yes it's a great way to learn but you shouldn't be doing that at the cost of the right solution for production code which is what I'm assuming we're talking about.


问:
Java serialization - advantages and disadvantages, use or avoid?
Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me
what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ?

This question came to my mind after seeing DZone article Is Object Serialization Evil?

And these are the lines that gave rise to my question:

If you look at Java and its session objects, pure object serialization is used. Assuming that an application session is fairly short-lived, meaning at most a few hours, object serialization is simple, well supported and built into the Java concept of a session. However, when the data persistence is over a longer period of time, possibly days or weeks, and you have to worry about new releases of the application, serialization quickly becomes evil. As any good Java developer knows, if you plan to serialize an object, even in a session, you need a real serialization ID (serialVersionUID), not just a 1L, and you need to implement the Serializable interface. However, most developers do not know the real rules behind the Java deserialization process. If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.

Now, may developers reading this may say that they would never write code that would have this problem. That may be true, but what about a library that you use or some other developer no longer employed by your company? Can you guarantee that this problem will never happen? The only way to guarantee that is to use a different serialization method.

答:
Short answer to "when to use Java serialization" and "when to avoid Java serialization"

Use Java serialization if

few coding should be necessary

it doesnt matter that binary data is not human readable

searching in serialized data is not neccessary (database-like query is not possible)

either

serialized data structure does not change or

it doesn-t matter if stored serialized data is not readable after "data structure change" any more (i.e. session-data in a web app)

In all other situations "Binary Java serialization" is bad

Alternatives

xml serialisation

nosql database

relational database with ORM


问:
How to encourage code review with team members working on different projects and platforms
With the previous team I used to work with, we used to work on the same project at the time. Or at least we used to use the same platform/programming languages. Code review was almost daily routine and established procedure. However, when I joined my new team as a senior developer, there was no code review followed at all. One of things I was asked to introduce to the team, is code review.

The problem is, my current team works on different projects, mostly using different platforms and different programming languages. For example, these couple of weeks I'm writing in PL/SQL and doing some ORACLE APEX development. Another team member is developing a mobile App using some hybrid App platform (jQuery, JavaScript, CSS ... etc). A third one is setting up IVR/OVMS system that barely has any code written except for some basic MySQL DB. We rotate usually in future projects, so everybody will get to understand the platforms. But we do not work on the same platform at the same time.

I understand this way of distributing work is not really the best (It might be for this company, but I do not think I have the privilege to discuss this, at least not just yet). The problem is, When I assign code review to a team member in a language that he has not touched for couple of weeks (maybe months), it is very hard to comment or make any useful understanding of it. When I spent my whole day writing in Javascript, and at the end of the day I'm asked to review some complex logic in PL/SQL, it is really not an easy task.

So my question: Is there any methods followed in similar cases? How can I facilitate the process and make the best use of code review given the team work load?

答:
It depends what you expect from a code review, and how you do it.

If the point of the code review is to find stupid things (like breaking naming and coding standard conventions), then find a tool to do it, and stop wasting time of your colleagues.

If you do proper code review, it shouldn't take long. Overly complex code should fail the review anyway.

And if you use a tool (codestriker or similar), then the reviewer can do it when they have time.

I guess you could even ask people from the previous team, if you are in the same company.

The point is to find someone, who can really help you improve the code. If you think someone is not going to be able to help - then just don't invite them.

The best is to talk to people in the team. See first if they want to do it. Talk to your boss, and see if you can get some time to do code review.


问:
What happens if a feature merged into develop is postponed by management?
We recently had a problem whereby a feature for our webapp (automatic signup) was postponed by management because they felt the start was too "cold" but they wanted all the other features we had been working on to go live.

The problem is that this functionality had been merged into develop when it was finished along with all the other features that we expected to push live on the next release so we couldnt just merge dev -> test -> master like we usually do.

How could we have avoided this issue?

答:
One approach is feature flagging it. It can live in the code base but be disabled by configuration.

Another option it to make a revert commit that reverts the feature merge so that it's not in develop any more. A new branch can be made which reverts the revert, and be left pending to merge later. If you're using Github pull requests, you can do this easily with the "revert merge" button on a merged pull request.


答:
How could we have avoided this issue?

From a process perspective, figure out:

Who was the decision maker to start this work?

Why did the decision to release this feature change?

Missed expectations?

Miscommunication?

Inadequate business support?

No customer involvement?

More than likely there were drops in communication along the way. This is important to have because when it doesn't work, your development process(es) will be based on false and wrong understandings of business requirements.

Title: What happens if a feature merged into develop is postponed by management?

Body:
We recently had a problem whereby a feature for our webapp (automatic signup) was postponed by management because they felt the start was too "cold" but they wanted all the other features we had been working on to go live.

The problem is that this functionality had been merged into develop when it was finished along with all the other features that we expected to push live on the next release so we couldnt just merge dev -> test -> master like we usually do.

How could we have avoided this issue?


问:
Approaches for storing and analysing large amounts of time-based data
I've been asked to develop a "telemetry" application that records data generated by a hardware device, which I read every 100ms.

There are approx 250 data points (32-bit values), but only a subset of these (say 30-50) will be returned by each 100ms read, so it will take several reads before I've got all 250 data points. Out of the data point values read, only a small number are likely to have changed since those same data points were last read - some change every 100ms, others perhaps every few seconds, while others very infrequently (or even never).

The main requirements for the system are:-

The ability to plot one or more data points over time, at 100ms resolution

The ability to view the values of all 250 data points at a particular point in time

The application needs to store the last 60 hours worth of data

I'm looking for some thoughts on how best to tackle this, particularly how to store the data in a way that supports the required reporting. So far I'm veering towards this idea:-

I maintain a "dictionary" of all 250 data points, updating the values after each read. Every 100ms I would write all 250 values to my data store. It's easy to implement and easy to query the data to satisfy the requirements. The downside is that it's not a particularly efficient use of storage (but hey - disk space is cheap nowadays).

Alternatively, ever 100ms, I could store only values that have changed since they were last read, however this becomes more difficult to implement, especially when it comes to querying. E.g. for requirement #2, I would have to construct a "snapshot" by traversing back through the data from the required point in time, looking for each data point's last stored value.

Now I've written all this out I think I've answered my own question. The "write everything" approach seems to be a no-brainer. However I've had no experience of this kind of mass data storage and analysis so I would be interested to hear what others think.

答:
What you want to implement is called an historian in the industrial world.
You should have a look at openTSDB which is an open source historian built on top of HBase. There are also commercial products like Wonderware Historian, GE Proficy Historian and Kepware’s Industrial Data Forwarder (IDF) for Splunk.
Yes, compression is mandatory to effectively store all your measurements. I think another challenge is to have the value when you don't have an exact match for the timestamp. This can also happen is the acquisition of your 250 signals is not perfectly synchronized. That's when interpolation comes into play. </p>


答:
If there's a working component that does what you need then why spend the time writing and debugging your own version? Similarly, if you've already written code to fulfill a similar function previously, why re-write it?

Joel wrote an article on Not-invented-here that speaks volumes about when re-writing code and software isn't and isn't useful.


答:
Forget for a moment the issue with your management, and imagine you had the "automatic signup feature" already in your latest production release, deeply integrated into your codebase. Now you get the new requirement to add an "off-switch" for "automatic signup". How would you handle this in your Git workflow?

I guess you would declare "disabling of automatic signup by configuration" simply as an additional feature (it is just a form of Feature Toggle), so this should integrate smoothly into your workflow. You can estimate the effort, if you like you can use a feature branch for it (or not, if you do not use feature branches for such issues). And you can definitely use the usal "merge dev -> test -> master" flow you described.

And that is actually the way you can handle this in your current situation. From the viewpoint of the git workflow, it should not matter if the change request comes from management for release 1.0, or if the change request is a new customer wish for release 2.0.


问:
Is localStorage under The Cookie Law?
I'd like to avoid having the cookies banner on my websites where possible. Could I store session id's in localStorage to bypass implementing the banner?</p>

答:
The cookie law is not actually about cookies (and its not actually called the cookie law). Its about tracking users, storing and sharing the information with third parties. Cookies are just the most popular method to track users.

If you don't want to show the "cookie warning" then just don't track the users beyond the session and don't share traffic data with third parties.

The actual directive.

Title: Is localStorage under The Cookie Law?


问:
Class design, responsibility granulation, efficiency and performance
I am in a design dilemma. I have a set of data that can be interpreted in numerous ways, but I cannot really decide how finely grained should it be. To illustrate it with some simple code:

class Base {
    Datamembers data;
    virtual void doStuff() = 0;
};

class T1 : public Base {
    void doStuff() {
        // do T1 stuff
    }
};

class T2 : public Base {
    void doStuff() {
        // do T2 stuff
    }
};

class ...

// ---------------------------

class Master {
    enum Role {
        T1, T2 ...
    };

    Role r;
    Datamembers data;

    void doStuff() {
        switch (r) {
        case T1:
            // do T1 stuff
            return;
        case T2:
            // do T2 stuff
            return;
        case ...
        }
    }
};
```

In reality the number of responsibilities is much higher than 2, currently still in the two digit range, but may grow further. Also, it is not one, but several doStuff()s at play.

In the first case, the data is encapsulated in a base class, and doStuff() is a pure virtual, which each derived class implements. Each responsibility is encapsulated in its own, dedicated type.

In the second case doStuff() is not a virtual function, and the responsibility is stored as an extra member in a Role, and the method switches the role and executes the appropriate code.

The two designs achieve the same goal in a different way, but what are the consequences?

Code maintenance:

The first approach seems cleaner, but even though usually clean implies maintainable, I feel it is kind of fragmented, which may end up reducing the ease of maintenance.

In the second approach all the code for the different responsibilities is crammed in the same place, which may sound dirty, but in many cases having it all in the same place may actually be easier, since all you have to do is scroll rather than jump around different files. But then again... it is still a big wall of code, not obvious in the example code above, but in practice it will be 4-5 digit lines of code. Although there is an easy remedy for that, just implement a function for each case that takes this as a parameter to access the data and force inlining to eliminate the overhead of extra function calls (even if not virtual).

Performance:

In my case, I deal with massive trees of objects, where doStuff() will be executed in tight loops, traversing that tree.

In approach one, the method is virtual, this means I get penalty for the indirection. Also, the code is spread across multiple types, which may end up fragmenting it in memory, reducing cache efficiency.

In the second approach the method is not virtual, and all code is essentially in a single function, which means it will be tighter in memory, and potentially more cache friendly. There is the switching penalty vs the indirection and fragmentation of the first approach.

Memory usage:

Although it is missing from the example code above, the hierarchy does have a constructor with plenty of arguments. Meaning that in the first approach each derived class will have its own constructor with the same parameters, redirecting those to the base class constructor. This, aside from tedious to implement for each type, also adds some code bloat. And there is the overhead of the v-tables. Both the extra constructors and v-tables are avoided in the second approach.

Obviously, I've made some considerations, and had this been a smaller undertaking, I'd do both and compare. But it is actually a lot of work and it is not really possible, so I'd appreciate some experienced opinions - are my considerations valid, am I missing something, is there another, better way to do it?

As it seems the scale of the problem isn't entirely clear, I will just summarize it. I am talking about an object tree, potentially tens of millions of nodes big, a responsibility hierarchy of currently 30 roles, expected to grow to over 100. Right now I have approximately about 200 lines of code per role, although the number varies. Parallelization is not an option, since node result depends on parent or children nodes results, so I am limited to a single thread traversing the tree, currently processing 200-300k nodes a second.

答:
You've possibly already seen some variant of Donald Knuth's "premature optimization" quote:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

This is a good quote, but it's equally accurate if you replace "premature" with "misplaced". You talk about traversing large trees and executing code in tight loops so thinking about performance certainly isn't premature, but I think the optimization you're thinking of may well be a bit misplaced.

If you're about to execute over 10,000 lines of code, it seems extremely unlikely that whether you enter into those lines via a method call or switch statement is going to have a noticeable effect on the overall performance. If you're in such a tight, performance-intensive situation that the nanosecond-to-microsecond range cost of a method call is important, then your 10,000 line statement already means you're screwed.

So unless I'm misunderstanding your question, I think that the focus of your optimization is misplaced. A much more important concern will be whether running the contents of the doStuff methods in a tight loop will have acceptable performance. If not, you'll have to consider higher-level strategies like caching results or parallelizing. It's hard to comment on these without knowing the specifics of your situation better.

Only once the contents of those doStuff methods run on a timescale comparable to the time savings you might get from in-lining the method should you consider doing that. Otherwise it's misplaced optimization and you should put performance out of your head while making that design decision.


问:
Add GPL to an existing application
Me and 2 of my friends been working on a small app. The source code of the app is on a private repository on BitBucket but now we would like to make the code of our app public under the terms of GPL.

The problem is, when we started the application, we did not put in the classes or anywhere for that mater the copyright as stated in the GNU manual on how to apply the terms to your new programs

My question is:
Can we annotate the classes now and make a commit with them and the app is under gpl license.(even if our previous commits did not include any of the copyright text.
Or we should make a new repository and upload the software with the updated gnu license text.

We would prefer the first method if possible, but if it is a must we can make a new repository.

答:
If you and your two friends are all in agreement on this course of action, and the three of you created 100% of the codebase, you can change its licensing without any legal trouble.

If you've accepted any outside submissions, that's when things get complicated.  The outside authors may hold copyright to the code they wrote, and you're using it under the terms of the license as it existed when they contributed their code, so unilaterally changing the licensing out from under them may upset them.  If so, you'd need to clear it with all of your contributors first.  But if you don't have any external contributors, then it's your code. License it however you want.

WRT license notifications, it's no different from any other software licensing: the end user is bound by the terms of the license that they received.  If they downloaded your software or your code without the new license, they don't have to comply with it.  If they later update to the new version with the new license, then they will have to comply with the terms of the new license.  But you can't go back and "change history" by changing the license.

Title: Add GPL to an existing application


答:
If your repository was private, unlicensed code, and now you want to make the code public under an open-source license, then what's the problem?

You can't retroactively apply changes to license terms. Otherwise, nobody would be able to rely on a particular license, because it would be subject to change at any time.  But since the code currently has no license and no rights of use, adding a license to add rights of use and distribution is how the licensing process is supposed to work.

Make sure you ask any contributors to either agree to the new licensing terms or assign copyright to the project, so that there are no licensing or distribution problems later on.  Whether the code is in a different repository or not doesn't matter.

Title: Add GPL to an existing application

Body:
Me and 2 of my friends been working on a small app. The source code of the app is on a private repository on BitBucket but now we would like to make the code of our app public under the terms of GPL.

The problem is, when we started the application, we did not put in the classes or anywhere for that mater the copyright as stated in the GNU manual on how to apply the terms to your new programs

My question is:
Can we annotate the classes now and make a commit with them and the app is under gpl license.(even if our previous commits did not include any of the copyright text.
Or we should make a new repository and upload the software with the updated gnu license text.

We would prefer the first method if possible, but if it is a must we can make a new repository.


答:
Where you're going to gain with the granular approach is if you have to configure your program where you need a different six roles at different times. This would keep you from having to load or even think about the other 24. And if you need another 30 roles, it's much easier to add those as individual classes than have another 6000 lines in your switch statement. See the Zero one infinity rule--the switch statement imposes an exact limit on how many cases you can handle.

If your Master Class needs to do anything else other than your 30 cases, then it's going to get really crowded in there, really fast, especially if you embrace the switch statement approach for all of those things.

Title: Class design, responsibility granulation, efficiency and performance

Body:
I am in a design dilemma. I have a set of data that can be interpreted in numerous ways, but I cannot really decide how finely grained should it be. To illustrate it with some simple code:

class Base {
    Datamembers data;
    virtual void doStuff() = 0;
};

class T1 : public Base {
    void doStuff() {
        // do T1 stuff
    }
};

class T2 : public Base {
    void doStuff() {
        // do T2 stuff
    }
};

class ...

// ---------------------------

class Master {
    enum Role {
        T1, T2 ...
    };

    Role r;
    Datamembers data;

    void doStuff() {
        switch (r) {
        case T1:
            // do T1 stuff
            return;
        case T2:
            // do T2 stuff
            return;
        case ...
        }
    }
};
```

In reality the number of responsibilities is much higher than 2, currently still in the two digit range, but may grow further. Also, it is not one, but several doStuff()s at play.

In the first case, the data is encapsulated in a base class, and doStuff() is a pure virtual, which each derived class implements. Each responsibility is encapsulated in its own, dedicated type.

In the second case doStuff() is not a virtual function, and the responsibility is stored as an extra member in a Role, and the method switches the role and executes the appropriate code.

The two designs achieve the same goal in a different way, but what are the consequences?

Code maintenance:

The first approach seems cleaner, but even though usually clean implies maintainable, I feel it is kind of fragmented, which may end up reducing the ease of maintenance.

In the second approach all the code for the different responsibilities is crammed in the same place, which may sound dirty, but in many cases having it all in the same place may actually be easier, since all you have to do is scroll rather than jump around different files. But then again... it is still a big wall of code, not obvious in the example code above, but in practice it will be 4-5 digit lines of code. Although there is an easy remedy for that, just implement a function for each case that takes this as a parameter to access the data and force inlining to eliminate the overhead of extra function calls (even if not virtual).

Performance:

In my case, I deal with massive trees of objects, where doStuff() will be executed in tight loops, traversing that tree.

In approach one, the method is virtual, this means I get penalty for the indirection. Also, the code is spread across multiple types, which may end up fragmenting it in memory, reducing cache efficiency.

In the second approach the method is not virtual, and all code is essentially in a single function, which means it will be tighter in memory, and potentially more cache friendly. There is the switching penalty vs the indirection and fragmentation of the first approach.

Memory usage:

Although it is missing from the example code above, the hierarchy does have a constructor with plenty of arguments. Meaning that in the first approach each derived class will have its own constructor with the same parameters, redirecting those to the base class constructor. This, aside from tedious to implement for each type, also adds some code bloat. And there is the overhead of the v-tables. Both the extra constructors and v-tables are avoided in the second approach.

Obviously, I've made some considerations, and had this been a smaller undertaking, I'd do both and compare. But it is actually a lot of work and it is not really possible, so I'd appreciate some experienced opinions - are my considerations valid, am I missing something, is there another, better way to do it?

As it seems the scale of the problem isn't entirely clear, I will just summarize it. I am talking about an object tree, potentially tens of millions of nodes big, a responsibility hierarchy of currently 30 roles, expected to grow to over 100. Right now I have approximately about 200 lines of code per role, although the number varies. Parallelization is not an option, since node result depends on parent or children nodes results, so I am limited to a single thread traversing the tree, currently processing 200-300k nodes a second.


问:
DVCS and different versions of the same Product
Let's say that we have an application, with two (or more) different versions. E.g. Professional and Lite editions.

What would be the best way to keep the source under version control (DVCS in particular). The assumption here is that some or most of the code is common, but the Professional edition has some extra code as well.

What would be the optimum way of versioning the code with a system like git or Mercurial?

答: Not much idea about the git or Mercurial. The common feeling is you should have common part in one branch, and other versions in separate branches. When you are building, your build should be intelligent enough to check out code from appropriate branches and compile. </p>


问:
How does recursive backtracking work ?
I am trying to figure out recursive backtracking, i have good understanding of recursion and till some extent the concept of backtracking too but i am having difficulty understand the chronological order of how things are working when for loop is being used in following code. </p>

```<code>public static void diceRolls(int dice) {
    List<Integer> chosen = new ArrayList<Integer>();
    diceRolls(dice, chosen);
}

// private recursive helper to implement diceRolls logic
private static void diceRolls(int dice,List<Integer> chosen) {
     if (dice == 0) {
          System.out.println(chosen); // base case
       } else {
          for (int i = 1; i <= 6; i++) {
               chosen.add(i); // choose
               diceRolls(dice - 1, chosen); // explore
               chosen.remove(chosen.size() - 1); // un-choose
      }
  }
}
</code>```

<p>Now i am having problem understand that for example we pass 3 in diceRolls function, it calls the helper method, inside the for loop we add all the value of i (ie 1) after that it calls the method again so does the for loop complete itself before recursing or the method diceRolls(2,chosen) is passed now ? Because if 2 is passed then also the loop would only run once before recursing itself.   </p>

答:
Just follow it line by line, and when you hit a function call imagine copying and pasting the entirety of that function code in its place.

Therefore chosen.remove() will be called after the previous function calls have ended and therefore the other chosen.removes shall be called prior to it.

Google how to use a debugger put breaks in your work and then find what the variables are at different points of your code it will help your understanding a lot more than trying to get someone to explain it.

Title: How does recursive backtracking work ?


答:
Square wheels have to be reinvented. Efforts that suck have to be duplicated. Maybe there's a lack of documentation for the method, and the other programmer feels it's easier just writing their own rather than trying to figure it out. Maybe the way the method is being called is awkward and doesn't fit into the idiom of the programming language.

Just ask him what the deficiency is.


问:
Why is it the caller's responsibility to ensure thread safety in GUI programming?
I have seen, in many places, that it is canonical wisdom1 that it is the responsibility of the caller to ensure you are on the UI thread when updating UI components (specifically, in Java Swing, that you are on the Event Dispatch Thread).

Why is this so? The Event Dispatch Thread is a concern of the view in MVC / MVP / MVVM; to handle it anywhere but the view creates a tight coupling between the view's implementation, and the threading model of that view's implementation.

Specifically, let's say I have an MVC architected application that uses Swing. If the caller is responsible for updating components on the Event Dispatch Thread, then if I try to swap out my Swing View implementation for a JavaFX implementation, I must change all the Presenter / Controller code to use the JavaFX Application thread instead.

So, I suppose I have two questions:

Why is it the caller's responsibility to ensure UI component thread safety? Where is the flaw in my reasoning above?

How can I design my application to have loose coupling of these thread safety concerns, yet still be appropriately thread-safe?

Let me add some MCVE Java code to illustratrate what I mean by "caller responsible" (there are some other good practices here that I'm not doing but I'm trying on purpose to be as minimal as possible):

Caller being responsible:

public class Presenter {
  private final View;

  void updateViewWithNewData(final Data data) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        view.setData(data);
      }
    });
  }
}
```

<pre class="lang-java prettyprint-override"><code>public class View {
  void setData(Data data) {
    component.setText(data.getMessage());
  }
}
</code>```

View being responsible:

public class Presenter {
  private final View;

  void updateViewWithNewData(final Data data) {
    view.setData(data);
  }
}
```

<pre class="lang-java prettyprint-override"><code>public class View {
  void setData(Data data) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        component.setText(data.getMessage());
      }
    });
  }
}
</code>```

1: The author of that post has the highest tag score in Swing on Stack Overflow. He says this all over the place and I have also seen it being the caller's responsibility in other places, too.

答:
Because making the GUI lib thread safe is a massive headache and a bottleneck.

Control flow in GUIs often goes in 2 directions from the event queue to root window to the gui widgets and from the application code to the widget propagated up to the root window.

Devising a locking strategy that isn't lock the root window (will cause a lot of contention) is difficult. Locking bottom up while another thread is locking top down is a great way to achieve instant deadlock.

And checking if the current thread is the gui thread each time is costly and can cause confusion about what is actually happening with the gui, especially when you are doing a read update write sequence. That needs to have a lock on the data to avoid races.


答:
Threadedness (in a shared memory model) is a property that tends to defy abstraction efforts. A simple example is a Set-type: while Contains(..) and Add(...) and Update(...) is a perfectly valid API in a single threaded scenario, the multi-threaded scenario needs a AddOrUpdate.

The same thing applies to the UI - if you want to display a list of items with a count of the items on top of the list, you need to update both on every change.

The toolkit can't solve that problem as locking doesn't make sure the order of operations stays correct.

The view can solve the problem, but only if you allow the business rule that the number on top of the list has to match the number of items in the list and only update the list through the view. Not exactly what MVC is supposed to be.

The presenter can solve it, but needs to aware that the view has special needs with regards to threading.

Databinding to a multi-threading capable model is another option. But that complicates the model with things that should be UI-concerns.

None of those looks really tempting. Making the presenter responsible for handling threading is recommended not because it is good, but because it works and the alternatives are worse.

Title: Why is it the caller's responsibility to ensure thread safety in GUI programming?

Body:
I have seen, in many places, that it is canonical wisdom1 that it is the responsibility of the caller to ensure you are on the UI thread when updating UI components (specifically, in Java Swing, that you are on the Event Dispatch Thread).

Why is this so? The Event Dispatch Thread is a concern of the view in MVC / MVP / MVVM; to handle it anywhere but the view creates a tight coupling between the view's implementation, and the threading model of that view's implementation.

Specifically, let's say I have an MVC architected application that uses Swing. If the caller is responsible for updating components on the Event Dispatch Thread, then if I try to swap out my Swing View implementation for a JavaFX implementation, I must change all the Presenter / Controller code to use the JavaFX Application thread instead.

So, I suppose I have two questions:

Why is it the caller's responsibility to ensure UI component thread safety? Where is the flaw in my reasoning above?

How can I design my application to have loose coupling of these thread safety concerns, yet still be appropriately thread-safe?

Let me add some MCVE Java code to illustratrate what I mean by "caller responsible" (there are some other good practices here that I'm not doing but I'm trying on purpose to be as minimal as possible):

Caller being responsible:

public class Presenter {
  private final View;

  void updateViewWithNewData(final Data data) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        view.setData(data);
      }
    });
  }
}
```

<pre class="lang-java prettyprint-override"><code>public class View {
  void setData(Data data) {
    component.setText(data.getMessage());
  }
}
</code>```

View being responsible:

public class Presenter {
  private final View;

  void updateViewWithNewData(final Data data) {
    view.setData(data);
  }
}
```

<pre class="lang-java prettyprint-override"><code>public class View {
  void setData(Data data) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        component.setText(data.getMessage());
      }
    });
  }
}
</code>```

1: The author of that post has the highest tag score in Swing on Stack Overflow. He says this all over the place and I have also seen it being the caller's responsibility in other places, too.


答:
You may imageine backtrack as if you were walking through a dungeon and you must explore all the paths in the dungeon (the dungeon is acyclic - you will never come back to the same place regardless the path you choose). When you come to a place which forks to multiple paths, you choose only one and follow it. Only after you come to an end, you go back to the last fork and choose the next path. When you explored all paths, you go back to previous fork and repeat until you come back to the beginning of the dungeon.

In the code, the for cycle is like the fork in dungeon (in this case with 6 different path where you can continue), the recursive call to diceRolls represents choosing one of the possible paths, the end of a dungeon is when you stop the recursion (you don't stop the execution, you just come one step back). Every time you jump out of the diceRolls function, you continue with the for loop and call diceRolls again.

You end up with interrupting the for loop by a recursive call in the first iteration in the beginning, printing 111, then going one step back and continuing the loop you will get 112, then 113, ...116, and the you go even one step back and get 121, 122, 123,... until you get 661, 662, 666. At that point all your loops and recursive calls finished and the computation ends.

Title: How does recursive backtracking work ?

Body:
I am trying to figure out recursive backtracking, i have good understanding of recursion and till some extent the concept of backtracking too but i am having difficulty understand the chronological order of how things are working when for loop is being used in following code. </p>

```<code>public static void diceRolls(int dice) {
    List<Integer> chosen = new ArrayList<Integer>();
    diceRolls(dice, chosen);
}

// private recursive helper to implement diceRolls logic
private static void diceRolls(int dice,List<Integer> chosen) {
     if (dice == 0) {
          System.out.println(chosen); // base case
       } else {
          for (int i = 1; i <= 6; i++) {
               chosen.add(i); // choose
               diceRolls(dice - 1, chosen); // explore
               chosen.remove(chosen.size() - 1); // un-choose
      }
  }
}
</code>```

<p>Now i am having problem understand that for example we pass 3 in diceRolls function, it calls the helper method, inside the for loop we add all the value of i (ie 1) after that it calls the method again so does the for loop complete itself before recursing or the method diceRolls(2,chosen) is passed now ? Because if 2 is passed then also the loop would only run once before recursing itself.   </p>


问:
Why does ISO 8859-1 contain letter-free diacritics?
ISO 8859-1 contains a few letter-free diacritics: The diaeresis (¨), the acute accent (´), the cedilla (¸) and the macron (¯).¹

Why were they included? As far as I know (please correct me if I am wrong), the ISO 8859 encodings do not support combining diacritical marks like Unicode, so you cannot even use them to create fancy new letters like Ÿ, ś, ŗ and ī; you can just use them stand-alone like this: a¨b.  What's the point of that? Surely, the designers of ISO 8859-1 were very smart people and had very good reasons. What were they?

¹ The backtick/grave accent ` and the circumflex ^ should probably be in this list as well, but the reason for them being included in the ISO 8859 encodings seems fairly obvious to me: backwards compatibility to 7-bit ASCII.

答:
Note: when some important missing characters (such as the Euro symbol €) were added to the character set to create ISO8859-15, some mostly unused characters had to go, and this included the letter-free diacritics. So, the designers of ISO8859-1 may have been very smart people and may have had good reasons, but apparently nobody understood them!

However, your characterization that you can't create combined characters is not exactly true: if you have a terminal and/or printer that supports control characters, you can print YBACKSPACE¨ to get Ÿ. (That's of course different to how combined characters work in Unicode.)

Different to what backspace does today, the original meaning is to move the cursor back one space, and everything that gets printed then is printed on top of what was there before. That's how you would get boldface, strikethrough, or underlined text, for example:

HEYBACKSPACEBACKSPACEBACKSPACEHEY = HEY

HEYBACKSPACEBACKSPACEBACKSPACE--- = HEY


答:
Try running the following:

```<code>public static void diceRolls(int dice) {
    List<Integer> chosen = new ArrayList<Integer>();
    diceRolls(dice, chosen);
}

// private recursive helper to implement diceRolls logic
private static void diceRolls(int dice,List<Integer> chosen) {
System.out.println("Entering diceRolls with dice="+dice);
     if (dice == 0) {
          System.out.println(chosen); // base case
       } else {
          for (int i = 1; i <= 6; i++) {
               System.out.println("Starting for loop. i="+i+", dice="+dice);
               chosen.add(i); // choose
               diceRolls(dice - 1, chosen); // explore
               chosen.remove(chosen.size() - 1); // un-choose
               System.out.println("Ending for loop. i="+i+", dice="+dice);
           }
           System.out.println("Exiting diceRolls with dice="+dice);
       }
}
</code>```

For each iteration of the for loop, a new call will be made to diceRolls(int dice,List chosen) with dice being one less than it was before. If dice is not equal to 0, then that new call will result in six more calls being made.

The idea of backtracking is that you want to perform a depth first search across all possible solutions to a problem. Let's say you're trying to roll a dice N times and you're trying to get increasing numbers for each roll. Let [1,2,3] denote a roll of 1 then 2 then 3. Your initial state of the problem will be [], with no rolls performed yet. You can roll a standard dice six different ways, and so after your first roll you will have [1], [2], [3], [4], [5], [6]. For each one of these states, you can roll a dice an addition six ways for a total of 36 possible states: [1,1], [1,2], [1,3], [1,4], [1,5], [1,6], [2,1], [2,2]...[6,5], [6,6]. However, we can 'prune' states that are already invalid such as [2,1] and [6,5] as they are not increasing rolls. In this way, we can perform one addition change to each partial solution to the problem until we get all possible solutions to a problem, pruning at each step to reduce the problem size.

Title: How does recursive backtracking work ?

Body:
Try running the following:

public static void diceRolls(int dice) {
    List<Integer> chosen = new ArrayList<Integer>();
    diceRolls(dice, chosen);
}

// private recursive helper to implement diceRolls logic
private static void diceRolls(int dice,List<Integer> chosen) {
System.out.println("Entering diceRolls with dice="+dice);
     if (dice == 0) {
          System.out.println(chosen); // base case
       } else {
          for (int i = 1; i <= 6; i++) {
               System.out.println("Starting for loop. i="+i+", dice="+dice);
               chosen.add(i); // choose
               diceRolls(dice - 1, chosen); // explore
               chosen.remove(chosen.size() - 1); // un-choose
               System.out.println("Ending for loop. i="+i+", dice="+dice);
           }
           System.out.println("Exiting diceRolls with dice="+dice);
       }
}

For each iteration of the for loop, a new call will be made to diceRolls(int dice,List chosen) with dice being one less than it was before. If dice is not equal to 0, then that new call will result in six more calls being made.

The idea of backtracking is that you want to perform a depth first search across all possible solutions to a problem. Let's say you're trying to roll a dice N times and you're trying to get increasing numbers for each roll. Let [1,2,3] denote a roll of 1 then 2 then 3. Your initial state of the problem will be [], with no rolls performed yet. You can roll a standard dice six different ways, and so after your first roll you will have [1], [2], [3], [4], [5], [6]. For each one of these states, you can roll a dice an addition six ways for a total of 36 possible states: [1,1], [1,2], [1,3], [1,4], [1,5], [1,6], [2,1], [2,2]...[6,5], [6,6]. However, we can 'prune' states that are already invalid such as [2,1] and [6,5] as they are not increasing rolls. In this way, we can perform one addition change to each partial solution to the problem until we get all possible solutions to a problem, pruning at each step to reduce the problem size.


答:
ISO based Latin-1 on ECMA-094, which based it on the DEC Multinational Character Set so Europeans could use the DEC VT220.  The first 128 code points of every 8-bit character set had to be the same as ASCII for backward-compatibility.  Indeed, back in the bad old days, misconfigured network hardware often interpreted the high bit as an error-correction code and turned extended characters into 7-bit ASCII, so character sets had to be able to fall back to ASCII if this happened.  This is why Russians adopted KOI8-R, which produced readable fallback transliterations, over the ISO standard for Cyrillic.

ASCII had them because the keys existed on teletype terminals.  The keys existed on teletypes because, as Jörg mentioned, people would write à on an old-fashioned manual typewriter by typing a backspace `.  (I typed it on my Linux box just now as: a <em>right-alt</em> `.)  IBM based the keyboard of its PC on its typewriters, so it had those keys too, and since they exist, but have no meaning in any natural language, people started using them for markup.  Here, for example, they denote code fragments.

Title: Why does ISO 8859-1 contain letter-free diacritics?

Body:
ISO 8859-1 contains a few letter-free diacritics: The diaeresis (¨), the acute accent (´), the cedilla (¸) and the macron (¯).¹

Why were they included? As far as I know (please correct me if I am wrong), the ISO 8859 encodings do not support combining diacritical marks like Unicode, so you cannot even use them to create fancy new letters like Ÿ, ś, ŗ and ī; you can just use them stand-alone like this: a¨b.  What's the point of that? Surely, the designers of ISO 8859-1 were very smart people and had very good reasons. What were they?

¹ The backtick/grave accent ` and the circumflex ^ should probably be in this list as well, but the reason for them being included in the ISO 8859 encodings seems fairly obvious to me: backwards compatibility to 7-bit ASCII.


答:
Depends..

As with everything, it's about context:

It's Good when:

Framework or library is too heavy, and you only require limited functionality. Rolling your own extremely light-weight version that suits your requirement is a better approach.

When you want to understand and learn something complex, rolling your own makes sense.

You have something different to offer, something others' implementations do not have. Maybe a new twist, new feature etc.

It's Bad when:

Functionality already exists and is stable and well known (popular).

Your version adds nothing new.

Your version introduces bugs or limitations (e.g. your version is not thread-safe).

Your version is missing features.

Your version has worse documentation.

Your version is lacking unit tests compared to what it is replacing.

ContentLicense: CC BY-SA 4.0


问:
Testing a windows game application against older versions of windows
If I were to build a game using Visual Studio 2015 and (Most likely) SDL2, I think I'm right in assuming that in order for that game to run, the user's target windows version needs to have Visual C++ Redistributable for Visual Studio 2015 installed, which according to this page (https://www.microsoft.com/en-us/download/details.aspx?id=48145) is compatible on all these targets: Windows 10 , Windows 7 Service Pack 1, Windows 8, Windows 8.1, Windows Server 2003 Service Pack 2, Windows Server 2008 R2 SP1, Windows Server 2008 Service Pack 2, Windows Server 2012, Windows Vista Service Pack 2, Windows XP Service Pack 3

My question is: Is it standard practice to just auto install the required runtime when the game is installed and hope it works, or do you install and test your game on a real installation of all the various Windows versions? Either virtual machines or maybe a multi - boot?

Of course I could use VS2010, with the assumption that the redistributable for VS2010 would be installed in most modern machines. And the chances of it working correctly up to and including windows 10 would be very good. But I think there is still no guarantee unless you test the game on the actual windows versions you intend to target.

答:
Yes, package and install the runtime with your application. Everyone seems to do that already and I have never seen it hurt anything. If you want fancy you could use a network installer that only downloads it as needed.

As for testing you should never "just hope it works." At least try it on virtual machines for the latest XP service pack, Vista and 7. I assume you are developing on 8 or 10.

If your games use DX10,11,12 then virtual machines probably won't work for you (But then you couldn't be supporting XP either). I'd recommend buying some old used gaming laptops (should be cheap) and testing on those. New hardware running old OS's gets into weird problems like not having drivers for USB 3 or the GPU. I think XP had problems with hard drives bigger than 2 TB as well.

Also, pet peeve, please check that your DPI awareness is correct. If you don't deal with it make sure the manifest does not claim that you do.


问:
How do I use type assertions in Go when returning an interface type?
A struct I'm working on called fieldDefinition holds metadata about a field used by an object in my web app. One of the fields on fieldDefinition (it does get a bit confusing) looks something like this:

```<code>type fieldDefinition struct {
    id string
    apiName string
    label string
    fieldType uint //Defined by a list of constants.
    defaultValue interface{}
}
</code>```

I also have a function* on the struct to retrieve the default value (setting it requires a bit of logic) which currently literally just returns the interface{} type. Depending on the value of fieldType I would like there to be some indication that the value returned is useable as the type fieldType says it should be.

For example, if fieldType == FT_GEOLOCATION, then I want to make sure the interface value returned is of my Geolocation struct. I was looking at type assertions but I can't see any examples of it being used in a similar situation to learn from, and I don't think I'm 100% sure of how they actually work.

How could I benefit from type assertions here, and is there any better/more accepted way of doing this, or do I just have to accept that interface{} types are difficult to ensure validity with?

答:
It sounds like you want a type switch statement.

Each switch case could check that the fieldType is set correctly.


问:
Is initializing a char[] with a string literal bad practice?
I was reading a thread titled "strlen vs sizeof" on CodeGuru, and one of the replies states that  "it's anyways [sic] bad practice to initialie [sic] a char array with a string literal."

Is this true, or is that just his (albeit an "elite member") opinion?

Here is the original question:

```<code>#include <stdio.h>
#include<string.h>
main()
{
    char string[] = "october";
    strcpy(string, "september");

    printf("the size of %s is %d and the length is %d\n\n", string, sizeof(string), strlen(string));
    return 0;
}
</code>```

right. the size should be the length plus 1 yes?

this is the output

the size of september is 8 and the length is 9

size should be 10 surely. its like its calculating the sizeof string before it is changed by strcpy but the length after.

Is there something wrong with my syntax or what?

Here is the reply:

It's anyways bad practice to initialie a char array with a string literal. So always do one of the following:

```<code>const char string1[] = "october";
char string2[20]; strcpy(string2, "september");
</code>```

答:
I think the "bad practise" idea comes from the fact that this form :

```<code>char string[] = "october is a nice month";
</code>```

makes implicitly a strcpy from the source machine code to the stack.

It is more efficient to handle only a link to that string. Like with :

```<code>char *string = "october is a nice month";
</code>```

or directly :

```<code>strcpy(output, "october is a nice month");
</code>```

(but of course in most code it probably doesn't matter)

Body:
I think the "bad practise" idea comes from the fact that this form :

char string[] = "october is a nice month";

makes implicitly a strcpy from the source machine code to the stack.

It is more efficient to handle only a link to that string. Like with :

char *string = "october is a nice month";

or directly :

strcpy(output, "october is a nice month");

(but of course in most code it probably doesn't matter)


答:
Toward the end of his failed dream essay, Graham Hamilton (a major Java architect) mentions if developers "are to preserve the equivalence
with an event queue model, they will need to follow various
non-obvious rules," and having a visible and explicit event queue model "seems to help people to more reliably follow the model and thus construct GUI programs that work reliably."

In other words, if you try to put a multithreaded facade on top of an event queue model, the abstraction will occasionally leak in non-obvious ways that are extremely difficult to debug.  It seems like it will work on paper, but ends up falling apart in production.

Adding small wrappers around single components probably isn't going to be problematic, like to update a progress bar from a worker thread.  If you try to do something more complex that requires multiple locks, it starts getting really difficult to reason about how the multithreaded layer and the event queue layer interact.

Note that these kinds of issues are universal to all GUI toolkits.  Presuming an event dispatch model in your presenter/controller isn't tightly coupling you to only one specific GUI toolkit's concurrency model, it's coupling you to all of them.  The event queueing interface shouldn't be that hard to abstract.


问:
gitflow model with UAT releases is too chaotic, how to simplify?
At $DAYJOB, we have the following release/delivery pipeline:

Get new features, work on new features.

Once all features are completed, our own QA performs regressions, etc.

QA signs off on first UAT build, ships to customer UAT department (this is really customer's own QA force). This begins our initial version (e.g. v1.0)

Customer QA (UAT) finds issues, sends us back a list.

Development addresses the list of issues. Sometimes they might ask for non-defects, such as improvements or small features. We triage these on a case-by-case basis. Our own QA also verifies the fixes. They sign off, we ship a new build (this gets a version bump, like v1.1)

This "get list" and "work on the list" process cycles a few times, until customer signs off on the build (UAT Pass).

Signed-off build becomes "production". Now developers can start working on new features for the next release.

Some notes on this process:

We use a bastardized version of git-flow for this process (will explain in more detail later).

Regarding versioning, we do not differentiate between UAT releases and production releases. We have to assume any release to UAT might be signed off and go gold at any time. For us, each build "out the door" is treated as a "production release".

Developers work on branches off of develop for new features. We even work on features for the next release. However, we do not merge features until they are scheduled for release. This is because we do not create 'release' branches (more on this later).

Here is how our development process goes for both bugs and features:

Developer branches off develop and begins work.

Developer finishes work, performs code review

Code review passes, and we indicate to QA the branch is ready for testing. Our CI build system builds every branch in the remote repository, and QA can grab ad-hoc builds off of any branch. QA tests features in branches (and not off of develop) for a few reasons:

Builds on develop might include multiple features or bug fixes from multiple developers over the course of some time. When regressions occur, it becomes more difficult to track down what caused the regressions. The "test-each-branch" model allows us to isolate regressions to the changes on that branch (i.e. the one feature or bugfix).

All features must be tested on a branch because we do not merge them into develop until QA is happy with it. Also QA controls deployment schedule, so they know when develop is ready for new features.

We're tight on QA resources. At the moment we have a 4-to-1 ratio of developers to QA personnel. They simply can't keep up with the work we do.

Once QA is happy with the feature on the branch, they mark it as "verified".

Once verified, it sits there unchanged until someone with appropriate authority "approves" the feature or branch. At this point, a developer rebases/merges latest into the branch, fixes conflicts, then merges it into develop.

When we finally release software (new UAT build usually), we do a merge from develop directly into master.

Symptoms of the current system:

Tons of branches sitting around waiting to be merged. Over 100 at the moment, and the turnaround time is sometimes months before they are merged.

Process is complex and tightly controlled by QA

Throw submodules into the mix and you've got a recipe for disaster and complexity.

The reason we don't use the release branches right now is because we've had a bad experience with them. UAT process can sometimes take months. Sometimes they request features, unreasonably, and upper management allows it. We've had our release branches become numerous, long-lived, with huge parity issues (in other words, they accumulate tons of changes over their lifetime).

This whole thing is pretty chaotic and tough to manage. However, QA gives us a ton of great feedback on this process because our releases are super stable. This is because QA touches every branch before it is merged, whereas before developers merged all day long to develop and QA couldn't keep up with the changes, so a bunch of stuff went untested in releases.

Now that I've explained our process and situation, some questions:

How can we simplify this process?

How should release branches be handled when you have UAT process in the middle? Ideally we want to be able to continue active development on develop after UAT starts.

答:
Many familiar issues that I've also seen at many organizations.

My suggestions are as follows:

Branch off master for feature branches

Have QA do the merge back into master and push it

Release master weekly and tag each release with the release date

That's code and workflow-wise.

The harder parts are likely to be:

changing the culture

There are probably a diversity of opinion on what is wrong and why it is.  You'll need to have buy in and championing from the highest (relevant) level of the organization.  You'll need to explain and sell the advantages of such a slimmed down system.  Explain the simplicity and the rapid turnaround.  Make sure your (probably) agile process is not just lip service but fully thought out from actual agile practices and, when possible, scrum masters.

changing the existing workflow
You'll need to put together the new workflow and then develop a plan that will let you transition to it.

Other thoughts:

consider implementing a comprehensive feature switch system that will let your merge in (some) changes but have the features turns on/off through an admin gui.

in your deliver pipeline rather than finishing the feature and passing to QA, consider involving QA through the design, implementation and testing so that their final ok is a pass thru of well understood and agreed on assumptions.  You don't want QA surprised by an implementation and you don't want developers surprise by how QA decides to test.

Have a weekly release meeting with all parties involved and go thru all the tickets.  This can easily be 50-100 tickets.  Touch base on each one for: release implications to the business, pre release steps, post release steps, downtimes, etc.


答:
I read a really good blog some time ago which discuss this issue (mentioned by Karl Bielefeldt), what it basically says is that it is very dangerous to try and make the UI kit thread safe, as it introduces possible deadlocks and depending on how it's implemented, race conditions into the framework.

There is also a performance consideration. Not so much now, but when Swing was first released it was heavily criticised for it's performance (been bad), but that wasn't really Swing's fault, it was people's lack of knowledge with how to use it.

SWT enforces the concept of thread safety by throwing exceptions if your violate it, not pretty, but at least you're made aware of it.

If you look into the painting process, for example, the order in which elements are painted is very important.  You don't want the painting of one component to have a side effect on any other part of the screen.  Imagine if you could update a label's text property, but it was painted by two different threads, you could end up with a corrupted output.  So all painting is done within a single thread, normally based on the order of requirements/requests (but sometimes condensed to reduce the number of actual physical paint cycles)

You mention changing from Swing to JavaFX, but you'd have this problem with just about any UI framework (not just thick clients, but web as well), Swing just seems to be the one which highlights the problem.

You could design a intermediate layer (a controller of a controller?) whose job it is to ensure that calls to the UI are synchronised correctly. It's impossible to know exactly how you might design your non-UI parts of your API from the perspective of the UI API and most developers would complain that any thread protection implemented into the UI API was to restrictive or didn't meet their needs. Better to allow you to decide how you want to solve this issue, based on your needs

One of the biggest issues you need to consider is the ability to justify a given order of events, based on known inputs.  For example, if the user resizes the window, the Event Queue model guarantees that a given order of events will occur, this might seem simple, but if the queue allowed events to triggered by other threads, then you can no longer guarantee the order in which the events might occur (a race condition) and all of sudden you have to start worrying about different states and not doing one thing until something else happens and you start having to share state flags around and you end up with spaghetti.

Okay, you might solve this by having some kind of queue which ordered the events based on the time they were issued, but isn't that what we already have?  Besides, you could still no guarantee that thread B would generate it's events AFTER thread A

The main reason people get upset about having to think about their code, is because they are made to think about their code/design.  "Why can't it be simpler?"  It can't be simpler, because it's not a simple problem.

I remember when the PS3 was been released and Sony was up-talking the Cell processor and it's ability to perform separate lines of logics, decode audio, video, load and resolve model data.  One game developer asked, "That's all awesome, but how do you synchronize the streams?"

The problem the developer was talking about was, at some point, all those separate streams would need to be synchronized down to single pipe for output.  The poor presenter simply shrugged as it wasn't a issue they were familiar with.  Obviously, they've had solutions to solve this problem now, but it has funny at the time.

Modern computers are taking a lot of input from a lot of different places simultaneously, all that input needs to be processed and delivered to the user in away which doesn't interfere with the presentation of other information, so it's a complex problem, with out a single simple solution.

Now, having the ability to switch frameworks, that's not an easy thing to design for, BUT, take MVC for a moment, MVC can be multi layered, that is, you could have a MVC which deals directly with managing the UI framework, you could then wrap that, again, in a higher layer MVC which deals with interactions with other (potentially multi threaded) frameworks, it would be the responsibility of this layer to determine how the lower MVC layer is notified/updated.

You would then use coding to interface design patterns and factory or builder patterns to construct these different layers.  This means, that you multithreaded frameworks become decoupled from the UI layer through the use of a middle layer, as an idea.


问:
How to find the closest right neighbour in a tree?
Given a class:

```<code>public class Node
{
  public List nodes[];
  public Node right;   //NULL for now
}
</code>```

What's the best way to fill the "right" element of all tree nodes?

```<code>                        N
                        |
                        |
                      / | \
                    /   |   \
                  C1--->C2-->C3
                  / \         \
                 /   \         \
                C11->C12 -----> C31
</code>```

答:
You can do normal BFS where at each level you determine the right of each node, something like this pseudocode.

```<code>while(queue of nodes is not empty) {
  get size of queue into curLevelNodes
  while(curLevelNodes is not zero) {
    get current node into curNode
    if there is a next node in the same level get it into nxtNode
    curNode->right = nxtNode

    don't forget to push the children of curNode to the queue

    remove curNode from the queue

    decrement curLevelNodes by one
  }
}
</code>```

I would say make the variable right as a pointer.

The only problem here is that there is no guarantee of which node will right of which node, it will only follow the order of insertion.

Body:
You can do normal BFS where at each level you determine the right of each node, something like this pseudocode.

while(queue of nodes is not empty) {
  get size of queue into curLevelNodes
  while(curLevelNodes is not zero) {
    get current node into curNode
    if there is a next node in the same level get it into nxtNode
    curNode->right = nxtNode

    don't forget to push the children of curNode to the queue

    remove curNode from the queue

    decrement curLevelNodes by one
  }
}

I would say make the variable right as a pointer.

The only problem here is that there is no guarantee of which node will right of which node, it will only follow the order of insertion.


问:
How are complex programs made?
I know a few languages, and can program in them. How do multiple languages blend together in a single program? For ex. https://github.com/facebook/watchman. This uses C, PHP, Python, Javascript, etc. How exactly do these languages combine to give a single result? How do they interact with each other? How do I learn to do this?

And I have seen this question but I don't think this is the same: How to use multiple programming languages together in the same program? As my question is about the exact way these things interact and how to learn it whereas the above question is just about how they interact, which also has no detailed answers.

答:
Notice that a complex program does not need to be coded in several languages. For example, the Linux kernel is a complex program (of more than ten millions source lines of C code with a bit of assembly). And the GCC compiler has more than ten millions lines of C++ code (it was C code before 4.5, and switched to C++ in GCC 4.8), some of them being generated by internal utilities.

Then, mixing multiple languages is implementation specific (often related to foreign function interface) but most language implementations offer the ability to call foreign C code. The point is that a computer system has a convention called application binary interface (ABI, such as the x86-64 SVR4 ABI), and language implementations are generally following that ABI convention, notably for calling conventions (perhaps with the help of libffi).

And a software can be running on several processes which are somehow communicating using some inter-process communication (IPC), e.g. for distributed computing (such as cloud computing). Details are Operating System specific. On Linux, read about pipe(7), socket(7), shm_overview(7), sem_overview(7) etc... so read Advanced Linux Programming. Some programs are running in a process having several threads (e.g. to run on several cores in parallel of a multi-core processor).

Distributed or parallel or concurrent computing is difficult. You'll need years of study and experience to understand and somehow master it.

A common way to combine partial results in a distributed computation is MapReduce.

Title: How are complex programs made?