问:
Why does Node not support several event loops in one Process?
As the title says, why does Node not support several event loops in one Process? The idea, is that node spawns a user decided number of threads, which each have an event loop. When a new callback is added, it is scheduled to one of the threads loops. The reason, probably against this idea is because now each thread can cause mutation and other bad stuff, but you could make the user decide what threads share state and so have to be run on the same thread or have a message like event memory sharing concept. This would help with computationally heavy tasks, this would reduce the overhead of sharing data between node instances to achieve the same result and therefore achieve better performance for the hardware and more user requests.

To make it more clear, when I mean several event loops, then that would be like forking and creating several node instances to utilise multiple cores but instead node itself would spawn 4 threads all with one event loop, so there is a lower cost of communication because it is using threads instead if instances if you are doing lot's of data sharing, not workers that you spawn to do heavy work and have nothing to do with the event loop.

答:
As soon as you have several threads running in the same process and sharing the same virtual address space, you got synchronization issues and you'll probably need to have mutexes (e.g. to deal with the case of several thread loops accessing the same object concurrently).

(I am assuming a Linux operating system with pthreads below)

So you'll need to extend the Javascript language for that; either you'll transparently add mutexes into every object making them heavier (a pthread_mutext_t has 40 bytes on my Linux/Debian/x86-64) and slower (you'll need to call something like pthread_mutex_lock on every access), or you put that burden on the user, forcing him to add additional code, and adding a new way of undefined behavior, and possibility of deadlock.

At last, multi-threaded garbage collection is quite difficult. Read the GC handbook for more.

BTW, on many Linux systems, processes are nearly as efficient and easy and fast to start as threads (see clone(2) used by pthreads and sometimes as substitute to fork(2)...), so having several dozens of Node.js processes makes sense. Also, local IPC (e.g. thru pipe(7)-s or unix(7)-s sockets) is very efficient on Linux, so the communication costs can be quite low (usually more than ten times faster than Ethernet on a local network).


问:
In c/c++, are block-scope variables stacked only if the block is executed?
Suppose this:

```<code>void func()
{
 ...
 if( blah )
 {
  int x;
 }
 ...
}
</code>```

Is the space for x reserved on the stack immediately when func is entered, or only if the block is actually executed?

Or is it the compiler's choice?

Do C and C++ behave the same about this?

答:
Well, it is really the compiler's choice, but what I have observed is that when I compile without optimizations, (which is what we usually do in order to be able to debug our code,) the compiler tends to do things in a rather clear cut, deterministic, and reliable fashion:

The compiler does not optimize away any local variables.  (Except, perhaps, variables explicitly defined as register, but that's to be verified.)

Stack space for all local variables, no matter how they are nested, is reserved at once when the function is entered.

Stack space is not reused across separate nested scopes.  This means that void f(){ { int x; } { int y; } } will allocate space for two int variables; the space allocated for x will not be reused for y.

Of course, if you enable optimizations, all that Loki Astari wrote in the accepted answer is true.

ContentLicense: CC BY-SA 3.0


问:
Difference between trigger, handler and callback
It's current to see the terms callback, trigger and handler in some API documentations. It is just synonymous or each term correspond to a specific concept?

I used to think that this terms are just synonymous, but I must be wrong ...

Thanks !

答:
Handler, an asynchronous callback subroutine.  Handler implements interceptor design pattern.  Which is used to handle incoming or outgoing messages and manipulate its values.

A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at later time as in an asynchronous callback.

Callbacks implements in different ways Closure , lambda expressions and so on...

Triggers are rules, it executes on events.


问:
If I need to use a piece of memory throughout the lifespan of my program, is it really necessary to free it right before program termination?
In many books and tutorials, I've heard the practice of memory management stressed and felt that some mysterious and terrible things would happen if I didn't free memory after I'm done using it.

I can't speak for other systems (although to me it's reasonable to assume that they adopt a similar practice), but at least on Windows, the Kernel is basically guaranteed to cleanup most resources (with the exception of an odd few) used by a program after program termination. Which includes heap memory, among various other things.

I understand why you would want to close a file after you're done using it in order to make it available to the user or why you would want to disconnect a socket connected to a server in order to save bandwidth, but it seems silly to have to micromanage ALL your memory used by your program.

Now, I agree that this question is broad since how you should handle your memory is based on how much memory you need and when you need it, so I will narrow the scope of this question to this: If I need to use a piece of memory throughout the lifespan of my program, is it really necessary to free it right before program termination?

Edit:
The question suggested as a duplicate was specific to the Unix family of operating systems. Its top answer even specified a tool specific to Linux (e.g. Valgrind). This question is meant to cover most "normal" non-embedded operating systems and why it is or isn't a good practice to free memory that is needed throughout the lifespan of a program.

答:
Because it's very probable that in some time you'll want to alter your program, maybe integrate it with something else, run several instances in sequence or parallel. Then it'll become necessary to manually free this memory - but you won't be remembering the circumstances anymore and it'll cost you much more time to re-understand your program.

Do things while your understanding about them is still fresh.

It's a small investment that may yield big returns in the future.


问:
What is it exactly that makes programs platform dependent when they're using cross-platform APIs?
I understand that programming languages can either be run in a VM (Java, etc) on every OS that supports the VM natively or can be compiled to machine code (C, etc) for each platform.

What I don't necessarily understand is why programs (whether dealing with graphics APIs like OpenGL, DirectX12 or Mantle, or not dealing with any at all) aren't all cross-platform if it's as easy as cross-compiling?

What is it that keeps programs, games, APIs (for example OpenGL) from being compatible on all platforms (except that maybe the developers only wanted it on one platform)?

With the new graphics API, Vulkan, coming out soon, would it be theoretically possible if using a toolkit like wxWidgets, for native GUI, along with an API like Vulkan to create programs that run completely cross platform as long as the OS has a Vulkan driver? Any other insight on something I'm missing would be appreciated.

答:
APIs build atop one another by value addition. Hardware vendors have choices amongst standards, then there is firmware, then ABIs from interpreters and build toolchains, chosen by monitor/OS vendors, leading to line ending of scripts CRLF-NL combinations and ELF & COFF executables. Upcoming C++ 17 has modules proposal, but until then mangling of overloads has compelled vendors trying for up to date broad hardware coverage to favor system software vendors using C calling convention(or anything close enough clarity-wise). So many stakeholders trying to comply with so many different possibilities at once, if one solution software program were to cover many of these, then the executable payload would be bloated during times when disk space was precious... cause of platform dependence

Vulkan(for more insight), assuming all goes well, is expected to allow developers to work with graphics bypassing intermediate binding wrappers, when the value additions will be unused anyhow. Without committing career to C, similar earlier efforts used to be made via DCOM/XPCOM...


问:
Speeding up appending text in C#
I'm trying to append text to a large amount of strings (in the thousands), and also do some other string manipulations.

However, I have about 60 lines of if/else and string appending and it takes several minutes to go through so many lines of text.

It does several checks, but the main part of it uses:

```<code>newstring += appendText.Text + ' ' + inputTextBox.Lines[i];
</code>```

Is there a better way to do this that makes it faster?

答:
You are thinking correctly, appending text using plus operator is not optimal. Use StringBuilder for this, especially if conditionals are used:

(code from link above)

```<code>StringBuilder sb = new StringBuilder();

sb.Append("This is a sentence.");

for (int ctr = 0; ctr <= 10; ctr++) {
    sb.Append("This is an additional sentence.");
}
</code>```

Than call sb.ToString(); to show full string.

Note: There are at least 6 ways to concatenate a string in c# (all examples produce "a b"):

'+' operator: use for constant strings, when it makes visual sense in code

string interpolation (.net 4.6 and newer): var b = "b"; $"a {b}"

string.Concat: string.Concat("a", " b")

string.Format: string.Format("{0} b", "a")

string.Join:

string[] arr = { "a", "b" };
string.Join(" ", arr);

StringBuilder

Usually, if you use .net 4.6 you will want to use string interpolation for shorter ones, and StringBuilder for longer. Prior to .net 4.6 insted of interpolation, use string.Format().

Title: Speeding up appending text in C#

Body:
You are thinking correctly, appending text using plus operator is not optimal. Use StringBuilder for this, especially if conditionals are used:

(code from link above)

StringBuilder sb = new StringBuilder();

sb.Append("This is a sentence.");

for (int ctr = 0; ctr <= 10; ctr++) {
    sb.Append("This is an additional sentence.");
}

Than call sb.ToString(); to show full string.

Note: There are at least 6 ways to concatenate a string in c# (all examples produce "a b"):

'+' operator: use for constant strings, when it makes visual sense in code

string interpolation (.net 4.6 and newer): var b = "b"; $"a {b}"

string.Concat: string.Concat("a", " b")

string.Format: string.Format("{0} b", "a")

string.Join:

string[] arr = { "a", "b" };
string.Join(" ", arr);

StringBuilder

Usually, if you use .net 4.6 you will want to use string interpolation for shorter ones, and StringBuilder for longer. Prior to .net 4.6 insted of interpolation, use string.Format().


问:
Doesn't "always initialize variables" lead to important bugs being hidden?
The C++ Core Guidelines have the rule ES.20: Always initialize an object.

Avoid used-before-set errors and their associated undefined behavior. Avoid problems with comprehension of complex initialization. Simplify refactoring.

But this rule doesn't help to find bugs, it only hides them.

Let's suppose that a program has an execution path where it uses an uninitialized variable. It is a bug. Undefined behavior aside, it also means that something went wrong, and the program probably doesn't meet its product requirements. When it will be deployed to production, there can be a money loss, or even worse.

How do we screen bugs? We write tests. But tests don't cover 100% of execution paths, and tests never cover 100% of program inputs. More than that, even a test covers a faulty execution path - it still can pass. It's undefined behavior after all, an uninitialized variable can have a somewhat valid value.

But in addition to our tests, we have the compilers which can write something like 0xCDCDCDCD to uninitialized variables. This slightly improves detection rate of the tests.

Even better - there are tools like Address Sanitizer, which will catch all the reads of uninitialized memory bytes.

And finally there are static analyzers, which can look at the program and tell that there is a read-before-set on that execution path.

So we have many powerful tools, but if we initialize the variable - sanitizers find nothing.

```<code>int bytes_read = 0;
my_read(buffer, &bytes_read); // err_t my_read(buffer_t, int*);
// bytes_read is not changed on read error.
// It's a bug of "my_read", but detection is suppressed by initialization.
buffer.shrink(bytes_read); // Uninitialized bytes_read could be detected here.

// Another bug: use empty buffer after read error.
use(buffer);
</code>```

There is another rule - if program execution encounters a bug, program should die as soon as possible. No need to keep it alive, just crash, write a crashdump, give it to the engineers for investigation.

Initializing variables unnecessarily does the opposite - program is being kept alive, when it would already get a segmentation fault otherwise.

答:
An answer to your question needs to be broken down into the different types of variables that appear inside a program:

Local variables

Usually the declaration should be right at the spot where the variable first gets its value. Do not predeclare variables like in old style C:

```<code>//Bad: predeclared variables
int foo = 0;
double bar = 0.0;
long* baz = NULL;

bar = getBar();
foo = (int)bar;
baz = malloc(foo);

//Correct: declaration and initialization at the same place
double bar = getBar();
int foo = (int)bar;
long* baz = malloc(foo);
</code>```

This removes 99% of the need for initialization, the variables have their final value right from the off. The few exceptions are where initialization depends on some condition:

```<code>Base* ptr;
if(foo()) {
    ptr = new Derived1();
} else {
    ptr = new Derived2();
}
</code>```

I believe that it's a good idea to write these cases like this:

```<code>Base* ptr = nullptr;
if(foo()) {
    ptr = new Derived1();
} else {
    ptr = new Derived2();
}
assert(ptr);
</code>```

I. e. explicitly assert that some sensible initialization of your variable is performed.

Member variables

Here I agree with what the other answerers said: These should always be initialized by the constructors/initializer lists. Otherwise you are hard put to ensure consistency between your members. And if you have a set of members that does not seem to need initialization in all cases, refactor your class, adding those members in a derived class where they are always needed.

Buffers

This is where I disagree with the other answers. When people go religious about initializing variables, they frequently end up initializing buffers like this:

```<code>char buffer[30];
memset(buffer, 0, sizeof(buffer));

char* buffer2 = calloc(30);
</code>```

I believe this is almost always harmfull: The only effect of these initializations is that they render tools like valgrind powerless. Any code that reads more from the initialized buffers than it should is very likely a bug. But with the initialization, that bug cannot be exposed by valgrind. So don't use them unless you really rely on the memory being filled with zeros (and in that case, drop a comment saying what you need the zero's for).

I would also strongly recommend adding a target to your build system that runs the entire testsuite under valgrind or a similar tool to expose use-before-initialization bugs and memory leaks. This is more valuable than all preinitializations of variables. That valgrind target should be executed on a regular basis, most importantly before any code goes public.

Global Variables

You can't have global variables that are not initialized (at least in C/C++ etc.), so make sure that this initialization is what you want.

Body:
An answer to your question needs to be broken down into the different types of variables that appear inside a program:

Local variables

Usually the declaration should be right at the spot where the variable first gets its value. Do not predeclare variables like in old style C:

//Bad: predeclared variables
int foo = 0;
double bar = 0.0;
long* baz = NULL;

bar = getBar();
foo = (int)bar;
baz = malloc(foo);

//Correct: declaration and initialization at the same place
double bar = getBar();
int foo = (int)bar;
long* baz = malloc(foo);

This removes 99% of the need for initialization, the variables have their final value right from the off. The few exceptions are where initialization depends on some condition:

Base* ptr;
if(foo()) {
    ptr = new Derived1();
} else {
    ptr = new Derived2();
}

I believe that it's a good idea to write these cases like this:

Base* ptr = nullptr;
if(foo()) {
    ptr = new Derived1();
} else {
    ptr = new Derived2();
}
assert(ptr);

I. e. explicitly assert that some sensible initialization of your variable is performed.

Member variables

Here I agree with what the other answerers said: These should always be initialized by the constructors/initializer lists. Otherwise you are hard put to ensure consistency between your members. And if you have a set of members that does not seem to need initialization in all cases, refactor your class, adding those members in a derived class where they are always needed.

Buffers

This is where I disagree with the other answers. When people go religious about initializing variables, they frequently end up initializing buffers like this:

char buffer[30];
memset(buffer, 0, sizeof(buffer));

char* buffer2 = calloc(30);

I believe this is almost always harmfull: The only effect of these initializations is that they render tools like valgrind powerless. Any code that reads more from the initialized buffers than it should is very likely a bug. But with the initialization, that bug cannot be exposed by valgrind. So don't use them unless you really rely on the memory being filled with zeros (and in that case, drop a comment saying what you need the zero's for).

I would also strongly recommend adding a target to your build system that runs the entire testsuite under valgrind or a similar tool to expose use-before-initialization bugs and memory leaks. This is more valuable than all preinitializations of variables. That valgrind target should be executed on a regular basis, most importantly before any code goes public.

Global Variables

You can't have global variables that are not initialized (at least in C/C++ etc.), so make sure that this initialization is what you want.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答: I'm from INDIA and as far as I have noticed all the Indians code in English.</p>

ContentLicense: CC BY-SA 2.5


问:
When a class represents a property that might be invalid, how should the validation be done?
I have a Product class which has among others an attribute Ean13 that encapsulates an EAN13 code.

Here is a prototype of the Product class:

```<code>@Entity
@Table(name = "tb_produtos")
public class Product implements Serializable {

    public Product() {
    }

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "ID_FABRICANTE")
    private Manufacturer manufacturer;

    @Column(name = "DESCRICAO")
    private String description;

    @Column(name = "URL")
    private String url;

    @Embedded
    private Ean13 ean;

    @Transient
    private Keywords keywords;

    ... getters and setters.
}
</code>```

At first, I implement the EAN class as follows:

```<code>@Embeddable
public class Ean13 {
    private static final RuntimeException notValidEanException = new RuntimeException("NOT VALID EAN CODE");

    @Column(name = "ean_code", nullable = true, length = 13)
    private String code;

    public Ean13() {
    }

    public Ean13(String code) {
        validate(code);
        this.code = code;
    }

    private void validate(String code) {
        if (code == null || code.length() != 13) {
            throw notValidEanException;
        }
        if (!CharMatcher.DIGIT.matchesAllOf(code)) {
            throw notValidEanException;
        }
        String codeWithoutVd = code.substring(0, 12);
        int pretendVd = Integer.valueOf(code.substring(12, 13));
        int e = sumEven(codeWithoutVd);
        int o = sumOdd(codeWithoutVd);
        int me = o * 3;
        int s = me + e;
        int dv = getEanVd(s);
        if (!(pretendVd == dv)) {
            throw notValidEanException;
        }
    }

    private int getEanVd(int s) {
        return 10 - (s % 10);
    }

    //mover estes metodos para outra classe.
    //TODO: Java 8.
    private int sumEven(String code) {
        int sum = 0;
        for (int i = 0; i < code.length(); i++) {
            if (isEven(i)) {
                sum += Character.getNumericValue(code.charAt(i));
            }
        }
        return sum;
    }

    private int sumOdd(String code) {
        int sum = 0;
        for (int i = 0; i < code.length(); i++) {
            if (!isEven(i)) {
                sum += Character.getNumericValue(code.charAt(i));
            }
        }
        return sum;
    }

    private boolean isEven(int i) {
        return i % 2 == 0;
    }

    @Override
    public String toString() {
        return code;
    }
}
</code>```

As you can see, the way I implement the constructor throws a RuntimeException when the object is instantiated with an invalid code.

An explanation about the Product class:

In this particular case I will use this class to hold information about products in a crawler application, that crawl few web sites and collect information about these products. One of this information is the EAN code. In this case the product and EAN object will by instantiate in a service class. Some EAN codes the application grabs from the web site are not valid EAN codes (can be another code, or some other string). At first I want to save this products without any code until I created a way to store it. So at first I have to validate this EAN code before persist it.

As you can see in the code above, I implement the validation in the method 'validate' that is called by constructor. In the way it is implemented, the validation will work more or less as follow:

```<code>Product p = new Product ();
try {
    Ean13 e = new Ean13("somecode");
    p.setEan13 (e);
} catch (InvalidEanCodeRuntimeException e) {
    //Log invalid ean code and product information.
}
persist(p);
</code>```

But there would be other ways to validate it.

I can make implement a public method in the Ean13 class as follow:

```<code>Product p = new Product ();
Ean13 ean = new Ean13 ("somecode");
if (ean.isValidEan ()){
    p.setEan13(ean);
}
</code>```

or it could still be done as follows, putting the validation in an external util class:

```<code>Product p = new Product ();
String somecode = "somecode";
if (CodeUtil.isValidEan13 (somecode)){
    p.setEan13(new Ean13(somecode));
}
</code>```

Certainly there are many other ways to implement it would work. But I would like to implement this validation in the most correct way, clean and elegant as possible and / or promote a discussion on ways to implement this kind of validation.

答:
Well there is always a school of though that you should always instantiate your objects in a valid state, so your solution is actually a best practice. If you make your object immutable you will find it very hard to miss things up that way.

Moving validation outside of the constructor could cause a trouble if you forget to call it. Other developers might believe that the object was created successfully through its constructor and start using it directly.

On the other hand making the isValid() method public might be a good idea to reuse validation functionality of the EAN code itself (in the UI for example).


问:
Who is a CMS really for?
I have started lately discovering Content Management Systems, and I was wondering, who is really CMS for?

What I mean by that: is it only for companies, small businesses or individuals, that pays a contractor to make a website that it's users can just upload content through a easy interface.

Or is it used also by programmers, to build their own websites, projects? Would a Facebook, Twitter or StackExchange ever started by using a CMS, a very powerful one for example.

Would you as a programmer build your own "fancy" website on top of a CMS, for example like Typo3, or you would build it from scratch?

P.S
To be more clear is a summary:

What I mean to begin with is, would I as a developer choose a CMS to develop a website that can be scaled with a big base of users, be stuck if I choose to start with a CMS system. What if I build a website using CMS, and the website explodes in popularity, and then I wanted to add much more functionality that I have planed, is it possible that the CMS will limit the growth, because it might have not been build for that kind of scale?

答:
All large-scale websites that need regular use a CMS of some sort. It may be Wordpress, Drupal, Ghost or similar - and for much larger organisations it may be a custom CMS-system built form the ground up.

Essentially, a CMS is ideal for any website that has content that needs to be updated on a periodic basis. It is not essential, it just makes the process a lot easier and user-friendly.

I use Wordpress as my preferred CMS for almost all websites I build because it allows me to make significant changes without ever having to touch the original code. My clients also enjoy Wordpress because it gives them the feeling that they are independent and free from the need of my expertise when it comes to updating their 'About' page, for example.

Title: Who is a CMS really for?


答:
Looking at your code, I would suggest moving the validation to the constructor. It can be considered bad practice to have too much logic in the constructor, though, so if you're doing a lot of work then I would recommend looking at the factory pattern.

You can have a private constructor and a public static Create method with a String parameter which will throw if it isn't valid and return the object that you expect.

```<code>Ean ean = Ean.create("123");
</code>```

This makes more sense, as it is odd behaviour for a constructor to fail and have no object.

Title: When a class represents a property that might be invalid, how should the validation be done?

Body:
I have a Product class which has among others an attribute Ean13 that encapsulates an EAN13 code.

Here is a prototype of the Product class:

```<code>@Entity
@Table(name = "tb_produtos")
public class Product implements Serializable {

    public Product() {
    }

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "ID_FABRICANTE")
    private Manufacturer manufacturer;

    @Column(name = "DESCRICAO")
    private String description;

    @Column(name = "URL")
    private String url;

    @Embedded
    private Ean13 ean;

    @Transient
    private Keywords keywords;

    ... getters and setters.
}
</code>```

At first, I implement the EAN class as follows:

```<code>@Embeddable
public class Ean13 {
    private static final RuntimeException notValidEanException = new RuntimeException("NOT VALID EAN CODE");

    @Column(name = "ean_code", nullable = true, length = 13)
    private String code;

    public Ean13() {
    }

    public Ean13(String code) {
        validate(code);
        this.code = code;
    }

    private void validate(String code) {
        if (code == null || code.length() != 13) {
            throw notValidEanException;
        }
        if (!CharMatcher.DIGIT.matchesAllOf(code)) {
            throw notValidEanException;
        }
        String codeWithoutVd = code.substring(0, 12);
        int pretendVd = Integer.valueOf(code.substring(12, 13));
        int e = sumEven(codeWithoutVd);
        int o = sumOdd(codeWithoutVd);
        int me = o * 3;
        int s = me + e;
        int dv = getEanVd(s);
        if (!(pretendVd == dv)) {
            throw notValidEanException;
        }
    }

    private int getEanVd(int s) {
        return 10 - (s % 10);
    }

    //mover estes metodos para outra classe.
    //TODO: Java 8.
    private int sumEven(String code) {
        int sum = 0;
        for (int i = 0; i < code.length(); i++) {
            if (isEven(i)) {
                sum += Character.getNumericValue(code.charAt(i));
            }
        }
        return sum;
    }

    private int sumOdd(String code) {
        int sum = 0;
        for (int i = 0; i < code.length(); i++) {
            if (!isEven(i)) {
                sum += Character.getNumericValue(code.charAt(i));
            }
        }
        return sum;
    }

    private boolean isEven(int i) {
        return i % 2 == 0;
    }

    @Override
    public String toString() {
        return code;
    }
}
</code>```

As you can see, the way I implement the constructor throws a RuntimeException when the object is instantiated with an invalid code.

An explanation about the Product class:

In this particular case I will use this class to hold information about products in a crawler application, that crawl few web sites and collect information about these products. One of this information is the EAN code. In this case the product and EAN object will by instantiate in a service class. Some EAN codes the application grabs from the web site are not valid EAN codes (can be another code, or some other string). At first I want to save this products without any code until I created a way to store it. So at first I have to validate this EAN code before persist it.

As you can see in the code above, I implement the validation in the method 'validate' that is called by constructor. In the way it is implemented, the validation will work more or less as follow:

```<code>Product p = new Product ();
try {
    Ean13 e = new Ean13("somecode");
    p.setEan13 (e);
} catch (InvalidEanCodeRuntimeException e) {
    //Log invalid ean code and product information.
}
persist(p);
</code>```

But there would be other ways to validate it.

I can make implement a public method in the Ean13 class as follow:

```<code>Product p = new Product ();
Ean13 ean = new Ean13 ("somecode");
if (ean.isValidEan ()){
    p.setEan13(ean);
}
</code>```

or it could still be done as follows, putting the validation in an external util class:

```<code>Product p = new Product ();
String somecode = "somecode";
if (CodeUtil.isValidEan13 (somecode)){
    p.setEan13(new Ean13(somecode));
}
</code>```

Certainly there are many other ways to implement it would work. But I would like to implement this validation in the most correct way, clean and elegant as possible and / or promote a discussion on ways to implement this kind of validation.

Body:
Looking at your code, I would suggest moving the validation to the constructor. It can be considered bad practice to have too much logic in the constructor, though, so if you're doing a lot of work then I would recommend looking at the factory pattern.

You can have a private constructor and a public static Create method with a String parameter which will throw if it isn't valid and return the object that you expect.

Ean ean = Ean.create("123");

This makes more sense, as it is odd behaviour for a constructor to fail and have no object.


问:
Multi tenancy or multi instance?
I'm trying to build a web-based SaaS solution, and I hit a road where I'm not sure to use multi tenancy or multi instance. I will try to describe what I'm trying to achieve, and each approach advantages and disadvantages (my opinion, according to what I read). Please include your suggestions in case I missed anything in one approach over the other.

The application that I'm trying to build is, as I mentioned, a SaaS solution where companies can create their accounts, and each account/company has it's own users, customers, products, services...etc. Each user; who is a company employee; related to one account/company will have access only to his/her company customers, products, and services. Companies could have unlimited number of customers, products and services, thus each company should have it's own data center.

For that I decided to create a shared database (saving all users credentials for login purposes) and multiple databases shared schema (database per account/company). Basically, Multi Tenancy.

Then somebody suggested to use Multi Instance instead, where each company will have its own instance of the application (i.e. code, libraries, database, frameworks... etc) totally separated from the other companies. This sounds better as I don't have to take care of an extra layer where I need to make sure that each tenant's users have access only to their company's data. I think it's good to mention that I'm depending on Docker to achieve this approach (I've never used it before), but I think it lacks features (more on those later) I will need in the future (at least I didn't find them with a little bit of search).

However, each approach comes with pros and cons, so I couldn't make a decision with which approach to go. Here is a list, but bare with me as I lack the knowledge in them both, so there could be something that I'm not aware of, or a solution for a problem I didn't find on the web: [Each approach has an ordered list of which I followed a one by one comparison]

Multi Tenancy:

Shared host/hardware, shared code, and multi database.

It's easier to extend the functionality of the code and fix bugs (shared code).

It's harder to extend the hardware (could use a cloud service), or move the database of individual tenant to another system without doing changes to the code.

Most importantly, as I mentioned before, I need to add an extra layer to the system to make sure that the user is actually belongs to his/her company, and not accessing other company's information.

Multi Instance:

Shared or unshared host/hardware, code per instance, and database per instance.

It's harder to extend the functionality or fix bugs (I'm not sure if there is a way to do it in Docker where you can add functionality/feature to one instance or Docker container, and deploy it to the others).

It's easier to move the whole instance to a different host/hardware.

As the instance, I don't need to take care of that layer as each instance will have its own database.

All of the advantages and disadvantages are redundant in case I want to do anything manually (as creating an instance for each tenant manually), and that's why I doubt the Docker solution, unless there is a way to solve that, which is maybe the main reason of the question. I would appreciate it if you would answer the question with references to the solutions, and why do you think this approach is better than the other.

In case that would help (maybe?), we're using Laravel as the main framework for the back-end (all RESTfully).

答:
Supporting both options is possible also (a pool of tenants across multiple instances).

I favor multi-instance cause of the natural isolation. Each customer's instance runs in it's own processes and it's data is isolated in it's own database. You can upgrade instances to new versions on a per customer/instance basis when desired.

Tenant based systems come with a information security risk. Just consider how easy it is to forget a "WHERE tenantId = x" clause. The main reason to use a tenant capable system would be performance, processes are heavy weight, by sharing a process you can potentially get more out of one machine. This was more true I think in a 32-bit world then it is nowadays on 64 bits machines that have a lot more RAM.

A multi-instance system would perhaps need a bit more tooling to create and configure the environment such as databases and web application instances. One can argue you need to have this scripted anyhow also for your single instance deployments. Doing this has other perks also like the ability to set up development and testing environments

I would leave the tenant capabilities out until you can make a case for it (engineering cost vs money saved on (hardware) infrastructure through process sharing).

Title: Multi tenancy or multi instance?


问:
How to get around non-initialized objects in the `finally` block?
I like using final variables whenever possible. Often those variables have to be closed afterwards. Note that I'm currently working on Java 6 so there is not closeable interface, but the same applies to later Java versions as well. For example:

```<code>final InputStream in;

try{
    in=new InputStream(...);
    //...
}catch(...) {}
finally{
    in.close(); //whoops!
}
</code>```

At that point the IDE will point out that in might be uninitialized. Wrapping the close statement in an if like so

```<code>if(in!=null)
    in.close();
</code>```

doesn't work either, despite null being the default value for uninitialized objects. My solution so far is to forget about declaring them final in the first place, and initializing them as null at declaration.

Another solution is to place the declaration and close statement in the try block:

```<code>try{
    final InputStream in=new InputStream(...);
    //...
    in.close();
}catch(InputStreamRelatedException) {};
</code>```

which would leave in open (?) in case of non-InputStream related exception.

What is the preferred method?

答:
I agree with amon that there are two separate concerns but disagree with him/her over what those concerns are. By choosing a slightly different set of concerns you can write terser code. Also, amon's code block throws an IOException because in.close()'s IOException is not caught but my code does not so long as you catch the IOException in the catch block.

IMO the two concerns are:

an I/O error occurring at any point (in construction or use of the stream)

closing the stream

With that in mind, we can write code like:

```<code>try {
  final InputStream in = ... // assign in
  try {
    // use in
  } finally {
    in.close();
  }
} catch (...) {} // if you catch IOException here, the block throws no IOException
</code>```

Note that ideally you would put an additional try/catch around in.close() to stop any exception thrown there from superseding the exception in the outer block. But that is horribly verbose.

As an aside, please do not use the anti-pattern of assigning null to in and checking for null in the finally block. It complicates the code for no good reason.

Body:
I agree with amon that there are two separate concerns but disagree with him/her over what those concerns are. By choosing a slightly different set of concerns you can write terser code. Also, amon's code block throws an IOException because in.close()'s IOException is not caught but my code does not so long as you catch the IOException in the catch block.

IMO the two concerns are:

an I/O error occurring at any point (in construction or use of the stream)

closing the stream

With that in mind, we can write code like:

try {
  final InputStream in = ... // assign in
  try {
    // use in
  } finally {
    in.close();
  }
} catch (...) {} // if you catch IOException here, the block throws no IOException

Note that ideally you would put an additional try/catch around in.close() to stop any exception thrown there from superseding the exception in the outer block. But that is horribly verbose.

As an aside, please do not use the anti-pattern of assigning null to in and checking for null in the finally block. It complicates the code for no good reason.


问:
Why shouldn't a GET request change data on the server?
All over the internet, I see the following advice:

A GET should never change data on the server- use a POST request for that

What is the basis for this idea?

If I make a php service which inserts data in the database, and pass it parameters in the GET query string, why is that wrong? (I am using prepared statements, to take care of SQL Injection). Is a POST request in some way more secure?

Or is there some historic reason for this? If so how valid is this advice today?

答:
A GET should never change data on the server- use a POST request for
  that

That advice, and all of the answers here are wrong. Obviously I'm being overly dramatic, the other answers are excellent, but I believe the exact advice should be given as:

A GET should rarely change data on the server- use a POST request for
  that

To say "never" is too extreme, and although the other answers here accurately explain why you should "rarely" do it, there are some scenarios where it is perfectly reasonable to change data with a GET. An example is a one-time use email verification link. Typically these links contain a GUID that when accessed will have to change data. If correctly implemented subsequent identical GET requests will be ignored.

This is obviously an edge case, but certainly worth noting.


问:
Domain driven design - Entity is updateable in certain circumstances
Here is my business rule:

Anyone (anonymous users) can make an Application (as in to apply for something). Applications can be updated until they are reviewed and approved by an officer. Approved applications cannot be updated.

Therefore I created an abstract class

```<code>abstract class Application {
    //various fields of application form
    //fields do not have setters, but they have getters

    public enum State {APPROVED, UNAPPROVED};

    public abstract State getState();
}
</code>```

And since an Application can be in two states, I modeled them like:

```<code>public class ApprovedApplication extends Application{
    //an approved application can only be created from an unapproved application
    public ApprovedApplication(UnapprovedApplication ua) {
        //create it
    }

    public State getState() {
        State.APPROVED;
    }
}
</code>```

and

```<code>public class UnapprovedApplication extends Application{
    //only unapproved applications can be updated
    public void update(ApplicationDTO applicationDTO) {
        //do the updating
    }

    public State getState() {
        State.UNAPPROVED;
    }
}
</code>```

Am I on the right track here or is this complete garbage? And what about Officer approving the application? Getting a bit lost here.

```<code>UnapprovedApplication.approve(Officer o);
</code>```

or

```<code>Officer.approve(UnapprovedApplication ua); ?
</code>```

答:
If I am understanding correctly, an unapproved application is the default state, which means either Application or UnapprovedApplication is redundant (remove one).

If you lock yourself into a corner by having business logic tied directly to your entity it's going to get ugly real quick.  Usually we do the business logic in a Service Layer that lives outside the entity.

In your service layer you would have the method approve which in turn would build your state object and set it on the entity.

Remember, an entity should closely match your persisted data (think getters and setters only)

How you transition between the states is subjective (business logic) and that should ideally always be done outside of your entity


问:
Which algorithm is performant for matrix multiplication of 4x4 matrices of affine transformations
I am wondering what is a good, performant algorithm for matrix multiplication of 4x4 matrices. I am implementing some affine transformations and I am aware that there are several algorithms for efficient matrix multiplication, like Strassen. But are there some algorithms that are especially efficient for matrices that small? Most sources I had a glance at are looking at which are asymptotically the most efficient.</p>

答:
If you know for sure that you will only need to multiply 4x4 matrices, then you don't need to worry about a general algorithm at all. You can just take in two pointers, and use this:

(I would strongly recommend translating this in some automated fashion).

The compiler would then be optimally positioned to optimize this code (to reuse partial sums, reorder the math etc) as it can see everything, there are no dynamic loops, and no control flow.

Hard to imagine that this can be beat without using intrinsics.


问:
Can objects be implemented in terms of higher order functions?
Martin Odersky finished one online course on Scala with an unanswered question:

Can we implement one concept in terms of other ?

Objects in terms of higher order functions?

Higher order functions in terms of objects?

It is clear that high order functions can be implemented using objects but I am not sure if it works the other way round or at least while using static types.

Suppose that closure can contain encapsulated data as object does but it still has only one 'method' in its interface - applying itself. In dynamic languages (or in static ones if we use some broad type like Object or Any) we can pass and return anything from this function but is this really an object ?

答:
Looked from a functional programming perspective, "objects" look basically like this:

Record types, with one field for each public method or field;

The values of most of those fields are first class procedures;

All the procedures in an object are closures that scope over the same private bindings.

So with that said, let's turn to your confusion:

Suppose that closure can contain encapsulated data as object does but it still has only one 'method' in its interface - applying itself.

The part that's missing here is my #1—the part about record types.  I'd say that you ought to look at it in these terms: OOP languages are designed with a construct, the class, which amalgamates closures and record types.  In functional languages these are generally treated as orthogonal features.

In dynamic languages (or in static ones if we use some broad type like Object or Any) we can pass and return anything from this function but is this really an object?

Sometimes people translate the (hopelessly vague) OOP idea of "message passing" into these terms:

Messages then explicitly modeled as values.  (Tagged union types/case classes are excellent for this.)

An object, then, is a value whose principal operation is to accept messages and respond to them.

But I'd say that this, looked from a functional programming lens, is basically a degenerate version of the interpreter pattern.


问:
Execute code every hour
I need to create a web service that executes every hour.  It will be used to review data in a database and add alerts to a table in the same database if certain conditions are met/not met.    What we currently have is:

We have end devices that use Python to report to an Amazon Web Services (AWS) virtual server.  The AWS server takes that information and stores it in a MySQL database.  The AWS server is Linux running Django and Apache.  I need to be able to have some python code run every hour that verifies the data that has been stored by the end devices.  If certain conditions are not met then a record will be added to the alerts table in the database.

We originally contracted to have the above setup created.  I am new to Python, Django, and Apache.  However, I have already made several changes to the Python code that sends and also receives the data from the end devices.  I am a coder that is breaking into web programming.

Does anyone have any recommendations on how I can do this?

答:
The most likely the answer here is provided that you are running crontab with the default setting which means it is displaying the crontab SPOOL RATHER THAN THE FILES.

Meanwhile, it can be run also in AWS as it comes with cron pre-installed and configured, that allows for set up of a task that should be run hourly, daily, weekly or monthly as well as any other time period by putting files in a /etc/cron.xxxxxx directory as explained here.

Setting up a job to run hourly, daily, weekly or monthly is very quick. Since the question is asking how to execute code every hour so in AWS Linux you can create a file in /etc/cron.hourly.

Here is the step when you have Log in to your instance via the SSH client.

```<code>$ echo "/usr/bin/python -q /path/to/your/file" > application
$ sudo mv application /etc/cron.hourly/
$ sudo chown -R root /etc/cron.hourly
$ sudo chmod 2755 /etc/cron.hourly/application
$ sudo /etc/init.d/crond restart
</code>```

In the example above the file saved and named 'application'. The name doesn’t really matter so long as it is unique. This is the log report by running: $ sudo vim /var/log/cron

```<code>Dec 28 19:01:01 ip-xxx-xx-xx-xx CROND[20243]: (root) CMD (run-parts /etc/cron.hourly)
Dec 28 19:01:01 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20243]: starting 0anacron
Dec 28 19:01:01 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20261]: finished 0anacron
Dec 28 19:01:01 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20243]: starting application
Dec 28 19:01:02 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20323]: finished application
</code>```

As shown in the log, at hourly basis it will start to run anacron that performs periodic command scheduling which is traditionally done by cron, and then call every other files in the directory and run the commands in each files.

Title: Execute code every hour

Body:
The most likely the answer here is provided that you are running crontab with the default setting which means it is displaying the crontab SPOOL RATHER THAN THE FILES.

Meanwhile, it can be run also in AWS as it comes with cron pre-installed and configured, that allows for set up of a task that should be run hourly, daily, weekly or monthly as well as any other time period by putting files in a /etc/cron.xxxxxx directory as explained here.

Setting up a job to run hourly, daily, weekly or monthly is very quick. Since the question is asking how to execute code every hour so in AWS Linux you can create a file in /etc/cron.hourly.

Here is the step when you have Log in to your instance via the SSH client.

$ echo "/usr/bin/python -q /path/to/your/file" > application
$ sudo mv application /etc/cron.hourly/
$ sudo chown -R root /etc/cron.hourly
$ sudo chmod 2755 /etc/cron.hourly/application
$ sudo /etc/init.d/crond restart

In the example above the file saved and named 'application'. The name doesn’t really matter so long as it is unique. This is the log report by running: $ sudo vim /var/log/cron

Dec 28 19:01:01 ip-xxx-xx-xx-xx CROND[20243]: (root) CMD (run-parts /etc/cron.hourly)
Dec 28 19:01:01 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20243]: starting 0anacron
Dec 28 19:01:01 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20261]: finished 0anacron
Dec 28 19:01:01 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20243]: starting application
Dec 28 19:01:02 ip-xxx-xx-xx-xx run-parts(/etc/cron.hourly)[20323]: finished application

As shown in the log, at hourly basis it will start to run anacron that performs periodic command scheduling which is traditionally done by cron, and then call every other files in the directory and run the commands in each files.


答:
It depends on what your program is going to do with those objects. For example, if you are implementing a bar code scanner program, and in case of a scan error, the  requirement is to write the (invalid!) code the scanner has detected into a log file, or display it to the user, I can imagine a scenario where is makes sense to construct and process Ean object even if it is  invalid. If that is your case, it should be obvious you need an isValid method for something along the lines of:

```<code>  Ean eanCode;
  while(true)
  {
      eanCode = new Ean(ScanCode());
      if(eanCode.isValid())
         break;
      LogScanError(eanCode);
  }
</code>```

However, if your program always expects Ean objects to be valid, and there is absolutely no need for invalid objects, do the validation in the constructor, and throw an exception in case it fails. The example above might be implemented like

```<code>  Ean eanCode;
  bool scanOk=false;
  while(!scanOk)
  {
      String code = ScanCode();
      try
      {
          eanCode = new Ean(code);
          scanOk=true;
      }
      catch(ValidationException ex)
      {
          LogScanError(code);
      }
  }
</code>```

This second variant has IMHO a light "code smell", since it uses exceptions for control of flow, which is often seen as a bad practice.

Thus I would prefer the isValid variant if you need the "invalid" Ean codes in more than one place in your program in a sensible manner, and the "constructor variant" if invalid Ean codes are a rare exception and their usage can be can be circumvented by implementing some code like above.

Body:
It depends on what your program is going to do with those objects. For example, if you are implementing a bar code scanner program, and in case of a scan error, the  requirement is to write the (invalid!) code the scanner has detected into a log file, or display it to the user, I can imagine a scenario where is makes sense to construct and process Ean object even if it is  invalid. If that is your case, it should be obvious you need an isValid method for something along the lines of:

  Ean eanCode;
  while(true)
  {
      eanCode = new Ean(ScanCode());
      if(eanCode.isValid())
         break;
      LogScanError(eanCode);
  }

However, if your program always expects Ean objects to be valid, and there is absolutely no need for invalid objects, do the validation in the constructor, and throw an exception in case it fails. The example above might be implemented like

  Ean eanCode;
  bool scanOk=false;
  while(!scanOk)
  {
      String code = ScanCode();
      try
      {
          eanCode = new Ean(code);
          scanOk=true;
      }
      catch(ValidationException ex)
      {
          LogScanError(code);
      }
  }

This second variant has IMHO a light "code smell", since it uses exceptions for control of flow, which is often seen as a bad practice.

Thus I would prefer the isValid variant if you need the "invalid" Ean codes in more than one place in your program in a sensible manner, and the "constructor variant" if invalid Ean codes are a rare exception and their usage can be can be circumvented by implementing some code like above.


问:
Do we need to create local branches for the enhancements we are working on?
We just started implementing the Git source control for our project and the Admin says we should not be creating any new branches for the enhancements that we are working on instead everybody should pull remote master branch into their machine and make changes and push the commits to remote master branch.

I somehow feel this process is wrong and I strongly feel that we should be creating new branch for the each enhancement that we are working on and merge the respective branches into master branch. Something similar to this

I need expert advice on this and which approach do you guys suggest from your past experience.

答:
The commit to master or trunk works as long as you are ok with how it works.

It means that if you have committed a bit of code to master (and haven't pushed it because its not a complete thing) and then realize that you need to work on something else (leaving those commits in an incomplete state) - it becomes very difficult to do that.

Branches exist to separate development efforts and the roles that a given line of code may take.

Consider:

You are packaging up a release on master, and now everything other than commits for this are frozen. This stops a lot of developers in their tracks.

You need to commit a hot fix into master and push it to production.

You need to work on two separate tasks at the same time.

You need to hold off on committing some features into the master branch until marketing says "ok"

Oops, that feature was a mess. Don't commit it to master - oh wait, its already there.

These are just some of the issues that come up with everyone committing to the master branch.  If you can resolve these in other ways, then, well, you don't need branches. However, branches are exactly the tool that is used by most processes to resolve these issues avoiding code freezes and awkward reversals of specific commits.

I will also point out that none of this prevents you from having local branches. One could easily pull from master, branch local, rebase on top of master, delete the local branch, and then push that back to the remote master and none would be the wiser. Personally I feel that having branches and merges showing more information about the history of the code is useful, but thats me personally. Maybe your admin doesn't like seeing all those branches and just wants to see the master branch - there are people like that. But that doesn't mean don't branch local - it just means don't push the branches back to the remote and clean up everything before doing that push.


答:
See the above-linked question for, I think, a comprehensive Q&A on the role of the master branch.

However, to further answer your question, it's important to understand why feature branches are important. If everyone is developing on and pushing to the same branch, then what happens when someone forgets to check in a file, or checks in the wrong stuff, or messes things up in a rebase?

In our organization we use GitFlow, with the master branch left unused. Develop is the working tip of the current release's efforts, releases are in named branches, and features are all developed on (hopefully short-lived) branches.

With feature branches, we're able to run a complete CI build on each branch before it gets merged to develop. Along with an approved pull request, the branch build must be green before the merge can occur. This ensures that the to-be-merged code compiles and passes all automated tests. This process has been successful for us in catching the simplest sorts of problems as early in the development cycle as possible.

Title: Do we need to create local branches for the enhancements we are working on?

Body:
We just started implementing the Git source control for our project and the Admin says we should not be creating any new branches for the enhancements that we are working on instead everybody should pull remote master branch into their machine and make changes and push the commits to remote master branch.

I somehow feel this process is wrong and I strongly feel that we should be creating new branch for the each enhancement that we are working on and merge the respective branches into master branch. Something similar to this

I need expert advice on this and which approach do you guys suggest from your past experience.


问:
Should I log errors on exception throwing constructors?
I was building an application for a few months and I come to realize a pattern that emerged:

```<code>logger.error(ERROR_MSG);
throw new Exception(ERROR_MSG);
</code>```

Or, when catching:

```<code>try {
    // ...block that can throw something
} catch (Exception e) {
    logger.error(ERROR_MSG, e);
    throw new MyException(ERROR_MSG, e);
}
</code>```

So, whenever I was throwing or catching an exception, I would log it. In fact, that was almost all logging I did on the application (besides something for application initialization).

So, as a programmer, I shun repetition; So I decided to move the logger calls to the exception construction, so, whenever I was building an exception, things would be logged. I could also, certainly, create a ExceptionHelper that throwed the exception for me, but that would make my code harder to interpret and, even worse, the compiler wouldn't deal well with it, failing to realize that a call to that member would throw immediately.

So, is this an anti-pattern? If so, why?

答:
Not sure if it qualifies as an anti-pattern, but IMO it's a bad idea: it's unnecessary coupling to intertwine an exception with logging.

You might not always want to log all instances of a given exception (maybe it occurs during input validation, the logging of which might be both voluminous and uninteresting).

Secondly, you might decide to log different occurrences of an error with different logging levels, at which point you'd have to specify that when constructing the exception, which again represents muddying the exception creation with logging behavior.

Finally, what if exceptions occurred during the logging of another exception? Would you log that? It gets messy...

Your choices basically are:

Catch, log and (re)throw, as you gave in your example

Create an ExceptionHelper class to do both for you, but Helpers have a code smell, and I wouldn't recommend this either.

Move the catch-all exception handling to a higher level

Consider AOP for a more sophisticated solution to cross-cutting concerns such as logging and exception handling (but far more complex than just having those two lines in your catch blocks ;) )


问:
How to license application generated from boilerplate code?
I looked at a number of other licensing questions and did not find anything that I felt related to this particular issue.

I am working on a simple web app, nothing special, and intend to license it with the MIT license.  The foundation for this app was generated using Clementine.js (here is the GitHub repo).  Clementine.js contains its own MIT license with the copyright holder listed as the person who developed the boilerplate.

My confusion/concern comes from the following points:

I must maintain the MIT license for Clementine.js

Clementine.js is built in such a way that it is not a library or package, it is a foundation that you build from

I would like to license the final product under my own MIT license

I am pretty unfamiliar with licensing practices and, in this situation, I am not sure how to proceed.  I have read a number of similar licensing questions and a lot of them pertain to libraries/packages having individual licenses that can be bundled within that library/package's sub-directory.  In this case, the licensed boilerplate code will inextricably be part of the final product.

Should I:

Merge the two licenses into a single license, putting myself and the Clementine.js copyright holder on the same license?

Create a single license file containing two separate licenses, one for the final product with a mention indicating it was built off of Clementine.js and then provide the Clementine.js copyright and license agreement?

Create two separate license files (LICENSE.md and LICENSE.ClementineJS.md)?

Any other possible solutions are welcome; I am out of my depth when it comes to licensing.

答:
IANAL, but the case you describe is IMHO similar to the distinction between licenses for individual modules of a software and the software "as a whole", as you often find them in open source software. For example, though the Linux kernel is licensed under GPL, it contains parts or modules which have a different (compatible) license (like libc, which is under LGPL). You will typically find different license texts in separate files for such a case.

The MIT license reads "... The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ...", but it does not contain any requirement to put the copyright text into a file named "LICENSE.md".

Putting this together leads to

you have to add the original, unmodified copyright notice from Clementine.js somewhere to your programs docs (so this rules out any kind of "merge" where the original text is modified)

you should have a clear license distinction between the final program "as a whole" and the license of "Clementine.js"

the license you use for the final program must be "compatible" with the MIT license (it must not contain anything which contradicts the licenses of any of its parts or "foundations")

If you achieve this by creating two separate license files, or by writing both license texts into one file, does not really matter, there is nothing in the MIT license saying the text must be kept in a separate file. Mentioning in your license text that the final product was built off of Clementine.js is a good idea for both cases, independently from the decision for one or two files.


问:
OAuth2 flow - does the server validate with the Auth server?
I've been reading a lot on OAuth2 trying to get my head around it, but I'm still confused about something.

I understand that the client authorises with the OAuth provider (Google for example) and allows the Resource Server to have access to the user's profile data. Then the client can send the access token to the resource server and be given back the resource.

But what does not seem to be covered in any of the documentation is what happens when the client app asks the resource server for a resource and passes it the access token. Everything I have read so far states that the resource server just responds with the requested resource.

But that seems like a huge hole, surely the resource server must somehow validate the access token, otherwise I could just fake up any old request and pass an old, stolen, fake, or randomly generated token and it would just accept it.

Can anyone point me at a simple to follow explanation of OAuth2 because so far the ones I have read feel incomplete.

答:
Token validation is generally handled in 1 of 2 ways.

The token is cryptographically signed using pre shared keys. This has obvious short comings for use in distributed, proliferating systems.

The Authorization Server (AS) provides an endpoint for token validation or Introspection.  This method was standardized in IETF RFC 7662 in October 2015, see: https://www.rfc-editor.org/rfc/rfc7662

This Stack Overflow Question / Answer includes examples from Google and Github: https://stackoverflow.com/questions/12296017/how-to-validate-an-oauth-2-0-access-token-for-a-resource-server


问:
Are a class's methods a type of closure?
Per MDN

A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

Based on this statement is it acceptable to call methods in a class with access to global variables a type of closure?

It seems as though that description meets the requirements, as a method is of course a function for a class instance, and it has access to the class variables which are in a sense local to the method.

答:
I think what you're asking is whether static methods and static variables of the same class can be considered as a (perhaps poor person's) closure construct.

While it has some resemblance to the operation of a closure, the construct you're describing cannot be created and recreated at will (unless you count launching of the program as a creation of the closure, which is a bit far fetched.)

Creation, and multiple concurrent instances, is a capability expected of closures -- in the text you're citing, for example, the article shows makeAdder, which is used to create two different closures that coexist.

The static class mechanism cannot be created or instantiated (it just exists primordially), so you would have trouble recreating the makeAdder example using it.


答:
A function closed within a function.

Closure is a function that can be stored as a variable with in a function.

The Closure can refer to any of the outer function's local variables.

Are a class's methods a type of closure?

class methods do not not satisfy the above basic principles, so simple methods with in the class are not closure.

for example anonymous classes in java are close to being called as a closure. SO Question

Origin: late Middle English: from Old French, from late Latin clausura, from claus- ‘closed’

Body:
Per MDN

A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

Based on this statement is it acceptable to call methods in a class with access to global variables a type of closure?

It seems as though that description meets the requirements, as a method is of course a function for a class instance, and it has access to the class variables which are in a sense local to the method.


问:
Social auth from mobile app connected to API server
I have a Node.js server using PassportJS that uses social login via Google, Facebook, and Twitter.

The Node.js server hosts an API that uses the PassportJS middleware to authenticate routes and securely serve the data. The API exists to serve an iOS application which will be where the user "logs in" through Google, Facebook, Twitter and will subsequently create their account on my service.

How can I accomplish this when the mobile SDKs for the respective companies are for a direct communication between my client and their server? I essentially want a way for my client which talks to my server which talks to their server. Please let me know if the overall idea is incorrect as well.

答:
Wouldn't those processes happen one after another? Here's a workflow that makes sense to me as a user:

I log into your web service using my Facebook account. This provides you with my e-mail address and Facebook user ID.

Your web service then asks me to authorize you to use a mobile API using (say) Pocket. Usually, this involves sending me to a URL on http://getpocket.com which will ask me to confirm that I want your web service to have certain permissions to my Pocket account. Once I've confirmed, it redirects me back to your webservice, passing it an access token that your webservice can then use to access my account. You can then store this token either locally on my client or on my server, in both cases making sure that I need to log into your service before your service can use my access token to access a mobile API using my credentials.

Your webservice can now make API requests against Pocket using my access token, until I revoke your access from my Pocket account.

If the mobile API you want to use provides authentication (as Pocket does), you might be able to authenticate and obtain permission at the same time. I've never used PassportJS, but it looks like the scope option allows you to ask for permissions while logging in through a particular service; if you do this, I assume that the user profile object you obtain will contain an access token you can use to make further Facebook requests.

Whether this access token is stored in your client or your server shouldn't make any difference, as long as it is passed to their server when you make API requests on behalf of your user.


问:
Do I have to include the license for a testing framework?
A common requirement for licenses is that they must be included with the software. Should licenses for testing frameworks with this clause be included if the test code is not something that is being shipped?

In other words: when a library's license asks to be included, is it only with software that directly uses that library?

答: Does the license apply to the entire library or just the testing framework? If the former, then I'd argue that removing a part of the library before shipping it doesn't remove your obligation to report your use of that library. If it is the latter (i.e. there is a clear, separate testing component within the library with its own license), then I think you can treat it as a separate library with its own license, which you don't have to follow unless you include that separate library.</p>


问:
Doesn't "always initialize variables" lead to important bugs being hidden?
The C++ Core Guidelines have the rule ES.20: Always initialize an object.

Avoid used-before-set errors and their associated undefined behavior. Avoid problems with comprehension of complex initialization. Simplify refactoring.

But this rule doesn't help to find bugs, it only hides them.

Let's suppose that a program has an execution path where it uses an uninitialized variable. It is a bug. Undefined behavior aside, it also means that something went wrong, and the program probably doesn't meet its product requirements. When it will be deployed to production, there can be a money loss, or even worse.

How do we screen bugs? We write tests. But tests don't cover 100% of execution paths, and tests never cover 100% of program inputs. More than that, even a test covers a faulty execution path - it still can pass. It's undefined behavior after all, an uninitialized variable can have a somewhat valid value.

But in addition to our tests, we have the compilers which can write something like 0xCDCDCDCD to uninitialized variables. This slightly improves detection rate of the tests.

Even better - there are tools like Address Sanitizer, which will catch all the reads of uninitialized memory bytes.

And finally there are static analyzers, which can look at the program and tell that there is a read-before-set on that execution path.

So we have many powerful tools, but if we initialize the variable - sanitizers find nothing.

```<code>int bytes_read = 0;
my_read(buffer, &bytes_read); // err_t my_read(buffer_t, int*);
// bytes_read is not changed on read error.
// It's a bug of "my_read", but detection is suppressed by initialization.
buffer.shrink(bytes_read); // Uninitialized bytes_read could be detected here.

// Another bug: use empty buffer after read error.
use(buffer);
</code>```

There is another rule - if program execution encounters a bug, program should die as soon as possible. No need to keep it alive, just crash, write a crashdump, give it to the engineers for investigation.

Initializing variables unnecessarily does the opposite - program is being kept alive, when it would already get a segmentation fault otherwise.

答:
Let’s take a closer look at your example code:

```<code>int bytes_read = 0;
my_read(buffer, &bytes_read); // err_t my_read(buffer_t, int*);
// bytes_read is not changed on read error.
// It's a bug of "my_read", but detection is suppressed by initialization.
buffer.shrink(bytes_read); // Uninitialized bytes_read could be detected here.

// Another bug: use empty buffer after read error.
use(buffer);
</code>```

This is a good example.  If we anticipate an error such as this, we can insert the line assert(bytes_read > 0); and catch this bug at runtime, which is not possible with an uninitialized variable.

But suppose we don’t, and we find an error inside the function use(buffer).  We load the program up in the debugger, check the backtrace, and find out that it was called from this code.  So we put a breakpoint at the top of this snippet, run again, and reproduce the bug.  We single-step through trying to catch it.

If we haven’t initialized bytes_read, it contains garbage.  It doesn’t necessarily contain the same garbage each time.  We step past the line my_read(buffer, &bytes_read);.  Now, if it’s a different value than before, we might not be able to reproduce our bug at all!  It might work the next time, on the same input, by complete accident.  If it’s consistently zero, we get consistent behavior.

We check the value, perhaps even on a backtrace in the same run.  If it’s zero, we can see that something is wrong; bytes_read should not be zero on success. (Or if it can be, we might want to initialize it to -1.)  We can probably catch the bug here.  If bytes_read is a plausible value, though, that just happens to be wrong, would we spot it at a glance?

This is especially true of pointers: a NULL pointer will always be obvious in a debugger, can be tested for very easily, and should segfault on modern hardware if we try to dereference it.  A garbage pointer can cause unreproducible memory-corruption bugs later, and these are almost impossible to debug.

Body:
Let’s take a closer look at your example code:

int bytes_read = 0;
my_read(buffer, &bytes_read); // err_t my_read(buffer_t, int*);
// bytes_read is not changed on read error.
// It's a bug of "my_read", but detection is suppressed by initialization.
buffer.shrink(bytes_read); // Uninitialized bytes_read could be detected here.

// Another bug: use empty buffer after read error.
use(buffer);

This is a good example.  If we anticipate an error such as this, we can insert the line assert(bytes_read > 0); and catch this bug at runtime, which is not possible with an uninitialized variable.

But suppose we don’t, and we find an error inside the function use(buffer).  We load the program up in the debugger, check the backtrace, and find out that it was called from this code.  So we put a breakpoint at the top of this snippet, run again, and reproduce the bug.  We single-step through trying to catch it.

If we haven’t initialized bytes_read, it contains garbage.  It doesn’t necessarily contain the same garbage each time.  We step past the line my_read(buffer, &bytes_read);.  Now, if it’s a different value than before, we might not be able to reproduce our bug at all!  It might work the next time, on the same input, by complete accident.  If it’s consistently zero, we get consistent behavior.

We check the value, perhaps even on a backtrace in the same run.  If it’s zero, we can see that something is wrong; bytes_read should not be zero on success. (Or if it can be, we might want to initialize it to -1.)  We can probably catch the bug here.  If bytes_read is a plausible value, though, that just happens to be wrong, would we spot it at a glance?

This is especially true of pointers: a NULL pointer will always be obvious in a debugger, can be tested for very easily, and should segfault on modern hardware if we try to dereference it.  A garbage pointer can cause unreproducible memory-corruption bugs later, and these are almost impossible to debug.


问:
Tracking online users with a stateless architecture
I own a stateless architecture, exchanging a JWT token between client and server at authentication time.

I want to store in database (once per day) a timestamp related to the user access.

Indeed, I would like to be able to show who was accessing the app, with a margin of 1 day (kind of rather online users).

A good solution (to avoid hitting database at each client request) I guessed would be to add a property to the JWT token called recentUserAccessTimestamp and to send it to the client at every request.

Question is: Is it a good practice to make the client replace its existing token (in LocalStorage for instance in case of WebApp) right after each request on my server?

答:
You can certainly rotate the JWT across requests, but you'll quickly run into a couple problems:

What side-channel do you use to issue the JWT? A HTTP response header? An augmented response body?

How can a client issue more than one concurrent request? The JWT is rotated across request/response cycles, so reusing an existing JWT will result in funky race conditions.

You said that you don't want to update the DB on every client request. But if you rotate the JWT, would you not have to store the new JWT in Redis or another persistence mechanism anyway? Therefore I think that you should simply store the user access data upon each request.

Marketing folks go bananas for the kind of analytics data you'll be capturing. By storing it en masse, you might just save a coworker a lot of pain down the line, and it will make you look like a hero.

One final thought. If you can tolerate some loss of the data in question, just write it to an in-memory queue in your main application. A background thread can periodically flush the data to a persistence store. Now everyone wins.


答:
Are a class's methods a type of closure?

No. A closure is a very specific type of function. As Wikipedia says, they implement lexical scoping.

Closures

In Python, such a closure would look like this:

```<code>def startAt(x):
    def incrementBy(y):
        return x + y
    return incrementBy
</code>```

The variable x is bound (in Python's case, immutably) in the incrementBy that is created when startAt is called. (x could very well be a mutable data structure, or the implementation of your language may allow you to change it.)

For contrast, here is a non-closure function example that uses a global:

```<code>x = 0
def incrementBy(y):
    return x + y
</code>```

Here, there is a single function, incrementBy, and whenever x changes on the global scope, it is reflected in the function:

```<code>>>> incrementBy(5)
5
>>> x = 1
>>> incrementBy(5)
6
</code>```

Methods

Methods, on the other hand, have access to mutable variables. If they are instance methods, they know their instance, and thus class. If they are class-methods, they know their class. Even if they are static methods, not knowing class or instance, they still may use globals. The globals may be reassigned at will, and can thus change the outputs of the function for any given.

You can make a closure into a method appended to a class, depending on the implementation of your language:

```<code>class Foo(object):
    ib5 = staticmethod(startAt(5))

>>> Foo.ib5(3)
8
>>> Foo.ib5
<function incrementBy at 0x7f29e978b758>
</code>```

But I don't think that's what you actually mean to do.

What is a closure?

A closure is an inner function that binds variables to it from the outer function's scope. If a class's method doesn't do this, it's not a closure.

Comparing and Contrasting Methods and Closures

What they have in common, is combining functionality with data.

Where they contrast is closures bind data to functionality, whereas methods bind functionality to data structures. So it would not be correct to call a method a type of closure unless it really is a closure.

I would assert that most class's methods don't do this, but I'll allow that there may be environments where this is a recognized technique. I'd be very interested to know who is using this and what their justification is.
I have personally never seen this being done in the wild.

Body:
Are a class's methods a type of closure?

No. A closure is a very specific type of function. As Wikipedia says, they implement lexical scoping.

Closures

In Python, such a closure would look like this:

def startAt(x):
    def incrementBy(y):
        return x + y
    return incrementBy

The variable x is bound (in Python's case, immutably) in the incrementBy that is created when startAt is called. (x could very well be a mutable data structure, or the implementation of your language may allow you to change it.)

For contrast, here is a non-closure function example that uses a global:

x = 0
def incrementBy(y):
    return x + y

Here, there is a single function, incrementBy, and whenever x changes on the global scope, it is reflected in the function:

>>> incrementBy(5)
5
>>> x = 1
>>> incrementBy(5)
6

Methods

Methods, on the other hand, have access to mutable variables. If they are instance methods, they know their instance, and thus class. If they are class-methods, they know their class. Even if they are static methods, not knowing class or instance, they still may use globals. The globals may be reassigned at will, and can thus change the outputs of the function for any given.

You can make a closure into a method appended to a class, depending on the implementation of your language:

class Foo(object):
    ib5 = staticmethod(startAt(5))

>>> Foo.ib5(3)
8
>>> Foo.ib5
<function incrementBy at 0x7f29e978b758>

But I don't think that's what you actually mean to do.

What is a closure?

A closure is an inner function that binds variables to it from the outer function's scope. If a class's method doesn't do this, it's not a closure.

Comparing and Contrasting Methods and Closures

What they have in common, is combining functionality with data.

Where they contrast is closures bind data to functionality, whereas methods bind functionality to data structures. So it would not be correct to call a method a type of closure unless it really is a closure.

I would assert that most class's methods don't do this, but I'll allow that there may be environments where this is a recognized technique. I'd be very interested to know who is using this and what their justification is.
I have personally never seen this being done in the wild.


问:
Deterministic function shows undeterministic behaviour, how is this possible?
How can a bug could occur on static, fixed input data only "sometimes"? The following is simply an example I have observed, but I am not interested in an answer specific to the GD library.

I have some PHP code to render SVG files, utilizing the GD Graphics library. It often stops working, and no error is given. The strange thing is that after 2-3 tries it works and keeps working with no code changes. This is very strange to me because I understand that assembled code follows in sequential order and operates on certain external inputs. In this case, the known input is a static file.

My question is, how is this possible (from a general, theoretical point of view)? What could the GD library (or any other code) be doing to cause such irregular behavior? How could code run differently based on how many times you ran it, if the input stayed the same?

答:
When I understand you correctly, your question is not specificially about GD, but how in general a function with fully deterministic requirements can show non-deterministic behaviour: given exactly the same input, the output (or in this case the behaviour) is different, though there is no obvious cause like a clock-dependency or random generator.

Whenever you run a program or a function on a system, even when the code is executed in a separate process, it is never executed in perfect isolation - there is always some environment around it, lots of other processes running simultanously at the same machine. There are always shared resources like main memory, disk space, processor cores, gfx card memory, global environment variables, and so on, which are not to be expected in exactly the same state when you run the program twice at different points in time. That alone can be the cause of the non-deterministic behaviour you are observing.

Furthermore, GD is written in C, which is a language where one can create "undefined behaviour" in several ways. For example, this can happen accidentally by forgetting to initialize a variable before usage (not that this is really the case for GD, just take this as a hypothetical scenario). This makes it possible the value of a variable can depend on the state of the shared resources I mentioned above. And assumed the GD lib contains such a piece of code somewhere in the SVG rendering code, or in its PHP binding, then it I can imagine that it could lead exactly to the behaviour you described.


问:
Maximizing Value and Volume, minimizing weight - Knapsack
Trying out a Knapsack variant where the rules are

Any item you take must fit completely in the bag

Usable metrics of the bag are length(l),width(w),height(h) and you can assume that if the products fit into the bag both individually and together by total volume, there is a way to pack them in

Price value must be maximized

Weight must be minimized without compromising on dollar value

The input is basically a list of items with l,w,h, value in dollars and weight.
Seems like thats a lot of metrics apart from the regular knapsack variants. What I am doing is first eliminating all products that dont fit into the bag (volume and dimensions wise). Next I am doing regular knapsack logic (figuring out if each item belongs in the bag or not) based on volume and price using the common DP pseudo code

```<code>if (volume[i] > V) {
        return knapsack(i-1, V);
    } else {
        return Math.max(knapsack(i-1, V), knapsack(i-1, V - volume[i]) + values[i]);
    }
</code>```

This seems to go haywire considering maximum l,w,h of the bag is like 40, 40, 40. (Hence volume is 64000) and number of items is to the tune of 16k. (Java out of memory error). Trying out Branch and Bound (not sure if correctly though)

Another suboptimal way I've tried is to use heuristics based on value/weight ratio and then taking the best volume fit. Another way would be to find all possible packing ways and then pick out the best weight fit (But again this would be hyper exponential)

How to solve this?

答:
As the weight optimization should not compromise on the dollar value, presumably there will be multiple ways to fill the knapsack with items that add up to the same highest dollar value.

So, the optimization for weight then consists of selecting the knapsack with the lowest weight among the knapsacks with the highest dollar value.


问:
How to generalize the planar case of the closest pair problem to d dimensions?
I'm trying to create a solution for the Closest pair problem using d-dimensional points. I've done a thorough search on google but it seems that there is no explanation for the d-dimensional case apart from what is on wikipedia:

the divide-and-conquer algorithm can be generalized to take O(n log n) time for any constant value of d.

and this document I found stating:

Two key features of the divide and
  conquer strategy are these:

The step where subproblems are
  combined takes place in one lower
  dimension.

The subproblems in the combine step
  satisfy a sparsity condition.

Sparsity Condition: Any cube with side
  length 2δ contains O(1) points of S.

Note that the original problem does not
  necessarily have this condition.

...

Given n points with δ-sparsity condition,
  find all pairs within distance ≤ δ.

Divide the set into S1, S2 by a median
  place H. Recursively solve the problem in
  two halves.

Project all points lying within δ thick slab
  around H onto H. Call this set S'

Recursively solve the problem for S' in d − 1 space.

but I can't wrap my head around the directions given in the documents above. Can someone describe in layman's terms how do I generalize the 2d solution to d dimensions? Is it even necessary or the 2d solution will work?

Understanding the 2d case was not so hard but it seems that there is little known about the d-dimensional version and I'm no mathematician.

答:
Generalizing the divide-and-conquer algorithm from Wikipedia to the d dimensional case is straight forward:

Here is the adopted algorithm description (changes in bold):

Sort points according to their x-coordinates.

Split the set of points into two equal-sized subsets by a (d-1) dimensional, vertical hyper-plane defined by x=xmid.

Solve the problem recursively in the "left" and "right" half of the coordinate space, defined by x<=xmid and x>=xmid . This yields the left-side and right-side minimum distances dLmin and  dRmin, respectively.

Find the minimal distance dLRmin among the set of pairs of points in which one point lies on the "left" of the dividing hyper-plane and the second point lies to the "right".

The final answer is the minimum among dLmin, dRmin, and dLRmin.

Note that step 4 can be accomplished in linear time for 2 dimensions, but needs O(n * log(n)^(d-1)) steps for d dimensions. More details are described here, which includes the case d>2.

Note further that for real world data it may be a good idea to switch between different coordinate axes from one recursive step to the next (but that applies already to the planar case).


问:
What is the different between web site and web application?
I have a friend who works in financing. His company wants a website for the company. He is really confused about a web site and a web app, and I don't really understand them enough to explain. Can you all give me some clear explanation about it?</p>

答:
A website is designed to provide a user with information and allow them to make an appropriate action based on that information. The action could be a contact form, purchase a product etc.

In contrast a web application is product/service which runs within the web browser but has a clearly defined purpose. Web applications are not restricted to proving users with a single application purpose as you would expect from mobile app.

Web apps are often confused with mobile apps, and with the advent of HTML5, the lines are becoming even blurrier. Web apps look and feel very much like mobile apps. They even store data in your browser’s cache, so much of the app can be accessed offline.

A website is defined by its content, while a web application is defined by its interaction with the user.

A website is a collection of web pages under the same location while a web application is a type of application that is hosted over a network.


问:
Micro-optimizing - BAD vs Game Development
In game development there is a lot of C/C++, in business applications C#.  I have seen C/C++ devs express concern over how a single line of code translates to assembly.  In .NET some go into IL, rarely.

In C#, "micro-optimizing" is frowned upon, rare and usually a waste of time.  This does not appear to be the case in game development.

What specifically creates this inconsistency?  Do games constantly push the limits of  hardware?  If yes, as hardware improves should we expect higher level languages to take-over the gaming industry?

I'm not looking for a debate on the feasibility of C# as a game dev lang.  I know it's been done to some degree.  Focus on  Micro-optimization.  Specifically, the difference between Game Dev vs Applications dev.

UPDATE

By Game I mean modern, largescale development.  E.G. MMORPG's, Xbox, PS3, Wii...

答:
In C#, "micro-optimizing" is frowned upon, rare and usually a waste of
  time. This does not appear to be the case in game development.

If you can just assemble your application with high-level code and library code, sure it's a waste of time. Write it in an interpreted language if you want in that case; won't make much difference. If you are trying to implement cutting-edge global illumination engine which voxelizes dynamic scene content on the fly in real-time like CryEngine 3 did, you naturally can't get away from the need to micro-optimize.


问:
Can udp packets be glued
Is there any standard that says that udp packets must not be combined together by operating system?

In other words can I be sure that when I send small udp packets by sendto or analogues, I will receive udp packets of the same size by recvfrom, if I request length, which is far more than the size any of the sent packets?

Ok, I am sure that receving side cannot concatenate datagrams, because they may come reordered or be missed.
But what is about sending side? Say I make several sendto to the same address, why OS should not concatenate data?

答:
It is not explicitly stated, but it is implied in the specification of the UDP protocol (RFC 768) that multiple packets that are sent independently are received independently.

UPD stands for User Datagram Protocol, and it is the Datagram that is relevant here.

A datagram is defined as

A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer and the transporting network.

  -- RFC 1594

As datagrams are defined to be independent and self-contained, and because their delivery order (and if they arrive at all) is unspecified, there is no way by which an OS could stich multiple datagrams together in a meaningful way.

Title: Can udp packets be glued


答:
To echo @Dan1701

This is about separation of concerns - moving the logging into the exception creates tight coupling between the exception and the logging and also means that you've added an additional responsibility to the exception of logging which in turn may create dependencies for the exception class that it doesn't need.

From a maintenance point of view you can (I would) argue that you're hiding the fact that the exception is being logged from the maintainer (at least in the context of something like the example), you're also changing the context (from the location of the exception handler to the constructor of the exception) which is probably not what you intended.

Finally you're making an assumption that you always want to log an exception, in exactly the same fashion, at the point at which its created/raised - which is probably not the case. Unless you're going to have logging and non-logging exceptions which would get deeply unpleasant quite quickly.

So in this case I think "SRP" trumps "DRY".

Title: Should I log errors on exception throwing constructors?

Body:
I was building an application for a few months and I come to realize a pattern that emerged:

```<code>logger.error(ERROR_MSG);
throw new Exception(ERROR_MSG);
</code>```

Or, when catching:

```<code>try {
    // ...block that can throw something
} catch (Exception e) {
    logger.error(ERROR_MSG, e);
    throw new MyException(ERROR_MSG, e);
}
</code>```

So, whenever I was throwing or catching an exception, I would log it. In fact, that was almost all logging I did on the application (besides something for application initialization).

So, as a programmer, I shun repetition; So I decided to move the logger calls to the exception construction, so, whenever I was building an exception, things would be logged. I could also, certainly, create a ExceptionHelper that throwed the exception for me, but that would make my code harder to interpret and, even worse, the compiler wouldn't deal well with it, failing to realize that a call to that member would throw immediately.

So, is this an anti-pattern? If so, why?


答:
So, as a programmer, I shun repetition [...]

There is a danger here whenever the concept of "don't repeat yourself" is taken a little too seriously to the point where it becomes the smell.