问:
Handling null-references in C# logic
Let's say I have an API method with can be used to calculate the sum of all orders made by a specific customer:

```<code>Amount CalculateOrderSum(int customerId)
{
    // Perform authentication to make sure caller has access to customerId

    // Retrieve customer with id customerId

    // Retrieve all orders related to the customer

    // Retrieve details for different orders (not always, depending on state)
}
</code>```

At any point in this function, some system administrator may purge old items from the system. This means that one of the below can happen while the method above is running:

The authentication will fail, because the customer no longer exists

The customer can't be loaded, since it was deleted

The customer can be loaded, but a millisecond later the orders are deleted and cannot be retrieved.

Retrieving order details works for some orders, but fails for others since they have been deleted mid-processing.

I want the application to return a friendly error message when any of this happens, rather than returning a NullReferenceException or similar.

As I see it, there's some different approaches to add error-handling for this logic:

I could introduce a lot of null-checks throughout the code for example: if (customer != null) throw OrderRetrievalFailedException("customer is a goner."). Since all the data in the database can be purged at any time, this would lead to quite a lot of if's spread throughout the code (which seems to get messy)

I could change the purging functionality to mark customers or orders as deleted (rather than actually removing the database rows). This way the function could still do its work because the data will still be there. The issue here is that we actually want to purge old data for different reasons (less attack surface and performance considerations for example).

I could change all methods to throw if an object can't be loaded (so GetOrders(customerId) could throw CustomerNotFoundException if the customer cannot be loaded) which would be catched in the CalculateOrderSum function and an error given to the user. So basically the code would have to be littered with if (something == null) throw new SomeException.

I could introduce some global locking mechanism, so that a customer can't be deleted while any one is reading any of its data. The issue here is that our system is distributed so we would need to implement a central locking mechanism. Also, I have a bad experience with locking of database rows in use-cases like this in high-traffic database.

All of these approaches feels quite convoluted and tricky to get right to me, and it means that the "main success flow" of the code will be littered with handling of exception scenarios. I'm leaning towards alternative 3, but I would to hear if there's some other "standard and robust" way of handling this.

(I'm using C#, but I assume that the same issue would apply to users of for example Java or C++)

答:
They're called "Guard Clauses."  It would look something like this:

```<code>if (!userHasAccess) throw new UnauthorizedException();
if (customer == null) throw new NotFoundException("customer");
if (orders.Count == 0) return 0;
if (anOrderHasFailed) throw new NotFoundException("Order " + orderNumber.ToString());
</code>```

Not that difficult, really, and your code will be more robust for the effort.

For those who are concerned about race conditions, you're going to get a NullReferenceException when you try to dereference a property on the null object anyway, so if you want to, you can just skip the null checks.

In practice, such race conditions are quite rare; if your customer suddenly disappears, you have larger problems.

Title: Handling null-references in C# logic

Body:
They're called "Guard Clauses."  It would look something like this:

if (!userHasAccess) throw new UnauthorizedException();
if (customer == null) throw new NotFoundException("customer");
if (orders.Count == 0) return 0;
if (anOrderHasFailed) throw new NotFoundException("Order " + orderNumber.ToString());

Not that difficult, really, and your code will be more robust for the effort.

For those who are concerned about race conditions, you're going to get a NullReferenceException when you try to dereference a property on the null object anyway, so if you want to, you can just skip the null checks.

In practice, such race conditions are quite rare; if your customer suddenly disappears, you have larger problems.


问:
Moving Java static variables into XML
I've been working on a small Java project by myself for a department that does not do a lot of software development but mostly database stuff.

I showed my boss the code I've been writing and he saw that in some classes there were some static variables. He then told me to put the static variables in XML instead to make it "easier."

He left and I did not get to ask him how it makes them manageable. He's going to be gone for a couple of weeks.

I know this might be a pretty vague question but what could possibly be the reasons why he would tell me to put static variables into XML? And how do I go about doing them?

First, I had something like this:

```<code>private final static String[] ACCESS_EXTENSIONS = {"accdb", "mdb"};
</code>```

After he told me about putting static variables in an XML file, I wrote an XML code:

<input_filetypes>

    <filetype id = "access">
        <title>Access Database</title>
        <extension>accdb</extension>
        <extension>mdb</extension>
    </filetype>

    <filetype id = ....>
        ....
    </filetype>

    ......

</input_filetypes>
```

<p>But then this resulted to me creating a static String variable that contains the location of my XML file:</p>

```private final static String xmlFile = "location_of_my_xml_file";
```

<p>I also learned about how to use XPath to access data in my XML, but I ended up writing another static code which is:</p>

```private final static String GET_ACCESS_EXTNS_EXP =
    "input_filetypes/filetype[@id='access']/extension";
```

Now I think I made things worse. I know I should wait for him to get back to clarify, but that is a long time from now, and I think it's best if I start reading up while waiting. I just need ideas on where to start.

答:
You would put such variables in an XML file to make them configurable. In other words, you can change their values without recompiling the program.

Further Reading

XML configuration files

How to easily load an XML based configuration file into a Java class

ContentLicense: CC BY-SA 3.0

Title: Moving Java static variables into XML


问:
Is it better to guard the method call or the method itself?
I am writing an application and I got to this point:

private void SomeMethod()
{
    if (Settings.GiveApples)
    {
        GiveApples();
    }

    if (Settings.GiveBananas)
    {
        GiveBananas();
    }
}

private void GiveApples()
{
    ...
}

private void GiveBananas()
{
    ...
}
```

<p>This looks pretty straight-forward. There are some conditions and if they are true the methods are being called. However, I was thinking, is it rather better to do like this:</p>

<pre class="lang-cs prettyprint-override"><code>private void SomeMethod()
{
    GiveApples();
    GiveBananas();
}

private void GiveApples()
{
    if (!Settings.GiveApples)
    {
        return;
    }

    ...
}

private void GiveBananas()
{
    if (!Settings.GiveBananas)
    {
        return;
    }

    ...
}
</code>```

In the second case, each of the methods guards itself, so even if any of those methods GiveApples or GiveBananas is called from outside SomeMethod, they are going to be executed only if they have the correct flag in Settings.

Is this something that I should actually consider as a problem?

In my current context, it is very unlikely that those two methods will be called from outside this method, but no one can ever guarantee that.

答:
I think of guards as something the method must obey. In your example, the method must not give apples if Settings.GiveApples is false.

If that is the case then the guard definitely belongs inside the method. This prevents you from accidentally calling it from another point in your application without checking the guards first.

On the other hand if the settings only apply to the calling method, and another method somewhere else in your code can GiveApples regardless of the setting then it's not a guard and probably should be in the calling code.


答:
Storing the configuration of the program externally allows you to avoid needing to recompile the program when something changes.  Switch from databaseA to databaseB? Modify the property file rather than modify the hard coded values and recompile from source.

What's more, Java offers a class as part of its standard runtime environment that facilitates this - the Properties class.  This class can either take a .properties file or an .xml file that matches the dtd specified at http://java.sun.com/dtd/properties.dtd (it really is a rather simple one - its the same as the one in the javadoc).

With the Properties class, you load it in, and then you can easily call getProperty(String key) or getProperty(String key, String defaultValue) and get your values out of it.  This is much easier than loading values from a custom xml file and all the xml or xpath processing that you would have to do with it.  Furthermore, its a known thing and easier to get right.

That's the property file.

```<code>access.extensions = accdb,mdb # where you might find an access database
</code>```

And then you've got the corresponding bit of Java...

```<code>String[] extensions = prop.getproperty("access.extensions", "accdb").split(",");
</code>```

for reading it out.  This makes the code a bit more self documenting, a safeguard against not having the file with a default value.

If you really wanted to use xml instead of a properties file, it would look like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
  <comment>Access Database Extensions</comment>
  <entry key="access.extensions">accdb,mdb</entry>
</properties>
```

But again, the key point is to move the values out of the code and into external files that are easier to work with. And Java already has the tools for reading those back into the system.

Title: Moving Java static variables into XML

Body:
I've been working on a small Java project by myself for a department that does not do a lot of software development but mostly database stuff.

I showed my boss the code I've been writing and he saw that in some classes there were some static variables. He then told me to put the static variables in XML instead to make it "easier."

He left and I did not get to ask him how it makes them manageable. He's going to be gone for a couple of weeks.

I know this might be a pretty vague question but what could possibly be the reasons why he would tell me to put static variables into XML? And how do I go about doing them?

First, I had something like this:

```<code>private final static String[] ACCESS_EXTENSIONS = {"accdb", "mdb"};
</code>```

After he told me about putting static variables in an XML file, I wrote an XML code:

<input_filetypes>

    <filetype id = "access">
        <title>Access Database</title>
        <extension>accdb</extension>
        <extension>mdb</extension>
    </filetype>

    <filetype id = ....>
        ....
    </filetype>

    ......

</input_filetypes>
```

<p>But then this resulted to me creating a static String variable that contains the location of my XML file:</p>

```private final static String xmlFile = "location_of_my_xml_file";
```

<p>I also learned about how to use XPath to access data in my XML, but I ended up writing another static code which is:</p>

```private final static String GET_ACCESS_EXTNS_EXP =
    "input_filetypes/filetype[@id='access']/extension";
```

Now I think I made things worse. I know I should wait for him to get back to clarify, but that is a long time from now, and I think it's best if I start reading up while waiting. I just need ideas on where to start.

Body:
Storing the configuration of the program externally allows you to avoid needing to recompile the program when something changes.  Switch from databaseA to databaseB? Modify the property file rather than modify the hard coded values and recompile from source.

What's more, Java offers a class as part of its standard runtime environment that facilitates this - the Properties class.  This class can either take a .properties file or an .xml file that matches the dtd specified at http://java.sun.com/dtd/properties.dtd (it really is a rather simple one - its the same as the one in the javadoc).

With the Properties class, you load it in, and then you can easily call getProperty(String key) or getProperty(String key, String defaultValue) and get your values out of it.  This is much easier than loading values from a custom xml file and all the xml or xpath processing that you would have to do with it.  Furthermore, its a known thing and easier to get right.

That's the property file.

access.extensions = accdb,mdb # where you might find an access database

And then you've got the corresponding bit of Java...

String[] extensions = prop.getproperty("access.extensions", "accdb").split(",");

for reading it out.  This makes the code a bit more self documenting, a safeguard against not having the file with a default value.

If you really wanted to use xml instead of a properties file, it would look like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
  <comment>Access Database Extensions</comment>
  <entry key="access.extensions">accdb,mdb</entry>
</properties>

But again, the key point is to move the values out of the code and into external files that are easier to work with. And Java already has the tools for reading those back into the system.


答: Rather than have your C# code perform all this computation and thus have to handle all the error conditions you describe, why not move it all to a stored procedure that is transactional? That way, you can lock the DB for example, to ensure it doesn't change whilst you perform your multiple steps.</p>

Title: Handling null-references in C# logic

Body:
Let's say I have an API method with can be used to calculate the sum of all orders made by a specific customer:

```<code>Amount CalculateOrderSum(int customerId)
{
    // Perform authentication to make sure caller has access to customerId

    // Retrieve customer with id customerId

    // Retrieve all orders related to the customer

    // Retrieve details for different orders (not always, depending on state)
}
</code>```

At any point in this function, some system administrator may purge old items from the system. This means that one of the below can happen while the method above is running:

The authentication will fail, because the customer no longer exists

The customer can't be loaded, since it was deleted

The customer can be loaded, but a millisecond later the orders are deleted and cannot be retrieved.

Retrieving order details works for some orders, but fails for others since they have been deleted mid-processing.

I want the application to return a friendly error message when any of this happens, rather than returning a NullReferenceException or similar.

As I see it, there's some different approaches to add error-handling for this logic:

I could introduce a lot of null-checks throughout the code for example: if (customer != null) throw OrderRetrievalFailedException("customer is a goner."). Since all the data in the database can be purged at any time, this would lead to quite a lot of if's spread throughout the code (which seems to get messy)

I could change the purging functionality to mark customers or orders as deleted (rather than actually removing the database rows). This way the function could still do its work because the data will still be there. The issue here is that we actually want to purge old data for different reasons (less attack surface and performance considerations for example).

I could change all methods to throw if an object can't be loaded (so GetOrders(customerId) could throw CustomerNotFoundException if the customer cannot be loaded) which would be catched in the CalculateOrderSum function and an error given to the user. So basically the code would have to be littered with if (something == null) throw new SomeException.

I could introduce some global locking mechanism, so that a customer can't be deleted while any one is reading any of its data. The issue here is that our system is distributed so we would need to implement a central locking mechanism. Also, I have a bad experience with locking of database rows in use-cases like this in high-traffic database.

All of these approaches feels quite convoluted and tricky to get right to me, and it means that the "main success flow" of the code will be littered with handling of exception scenarios. I'm leaning towards alternative 3, but I would to hear if there's some other "standard and robust" way of handling this.

(I'm using C#, but I assume that the same issue would apply to users of for example Java or C++)


问:
Development process used for the code on Apollo 11 missions?
The Apollo missions had technology no more complicated than a pocket calculator.

From link here, there's an information about Apollo Guidance Computer (AGC)

The on-board Apollo Guidance Computer (AGC) was about 1 cubic foot with 2K of 16-bit RAM and 36K of hard-wired core-rope memory with copper wires threaded or not threaded through tiny magnetic cores. The 16-bit words were generally 14 bits of data (or two op-codes), 1 sign bit, and 1 parity bit. The cycle time was 11.7 micro-seconds. Programming was done in assembly language and in an interpretive language, in reverse Polish.

So, I've stumbled upon some source code when I researched what was up there, and I've noticed great comments (eg. TEMPORARY, I HOPE HOPE HOPE)

```<code>VRTSTART    TS  WCHVERT
# Page 801
        CAF TWO     # WCHPHASE = 2 ---> VERTICAL: P65,P66,P67
        TS  WCHPHOLD
        TS  WCHPHASE
        TC  BANKCALL    # TEMPORARY, I HOPE HOPE HOPE
        CADR    STOPRATE    # TEMPORARY, I HOPE HOPE HOPE
        TC  DOWNFLAG    # PERMIT X-AXIS OVERRIDE
        ADRES   XOVINFLG
        TC  DOWNFLAG
        ADRES   REDFLAG
        TCF VERTGUID
</code>```

The actual programs in the spacecraft were stored in core rope memory, an ancient memory technology made by (literally) weaving a fabric/rope, where the bits were physical rings of ferrite material. "Core" memory is resistant to cosmic rays. The state of a core bit will not change when bombarded by radiation in Outer Space.

Virtual Apollo Guidance Computer (AGC) software is also on GITHUB!

Some part of documentation is here.

Another sample of source code with great comments.

```<code>033911,000064: 32,3017    06037        FLAGORGY        TC       INTPRET      #  DIONYSIAN FLAG WAVING

    034090,000243: 32,3241    13247        BZF      P63SPOT4               #  BRANCH IF ANTENNA ALREADY IN POSITION 1
    034091,000244:
    034092,000245: 32,3242    33254        CAF      CODE500                #  ASTRONAUT:     PLEASE CRANK THE
    034093,000246: 32,3243    04616        TC       BANKCALL               #                 SILLY THING AROUND
    034094,000247: 32,3244    20623        CADR     GOPERF1
    034095,000248: 32,3245    16001        TCF      GOTOP00H               #  TERMINATE
    034096,000249: 32,3246    13235        TCF      P63SPOT3               #  PROCEED        SEE IF HE'S LYING

    034101,000254: 32,3251    04635        TC       POSTJUMP               #  OFF TO SEE THE WIZARD ...
    034102,000255: 32,3252    74126        CADR     BURNBABY
</code>```

My question here is this:

How were the teams writing this much code able to make it functional given the tools at the time?

Because if you compile so much code that was used on Apollo 11... it'd take days, even weeks. I seriously doubt that programmers back then left everything to happen by chance.

答:
The AGC is controlled with verbs and nouns

The Apollo command software is not written in any syntax users would recognize today. Astronauts input commands numerically, with each two-digit number representing a verb or a noun. The verb described the action to be performed, and the noun specified the data to be affected by the verb’s action.

Astronauts hated the verb and noun setup

Ramón Alonso, one of the original AGC hardware developers, said the interface had been invented to impress visitors to their lab, but stuck around for the flights when nobody developed a better interface. Critics said it wasn’t "scientific," and the first astronauts—all elite jet pilots—preferred dials and switches, similar to an airplane control panel.

"The AGC was very slow, but very reliable and very small for that time
  in the history of digital computers. It was the earliest to use
  integrated circuits."

The software as it was designed was built basically from scratch by MIT.

You can download and install the Apollo Guidance Computer emulator program on your personal computer, no problem. Here’s what it looks like on Mac OS X.


问:
When should feature rebranding be followed by model and code renaming?
In a product we are rebranding a feature.
For example, we have tweets and we are rebranding it to news. On the code side we have tables and structures like tweet, user_tweets, favourite_tweets and so on.

Does simple rebranding justify renames and migrations in code and Data base (structure names, file names, fields, table names)?

答:
To my experience, it is good to be prepared that names in your code need to be changed afterwards, for lots of possible reasons, feature rebranding is just one of many reasons why this may occur. Therefore it is always a good idea to take some measures beforehand to make renamings in your code as simple as possible.

Refactoring tools will help. Statically typed languages with a compiler which warns you when you make an error in renaming will help. Writing DRY code will help (so there are not more places in your code to be modified than necessary). Integration test suits will help to validate you did not make an accidental error, for all cases the compiler cannot catch. Having testers and a good QA process will help you for all cases which your automatic integration tests won't catch. Using unique, searchable names throughout your code will help. Having a strategy and/or tools for introducing changes into your database schema afterwards will help. Having a tested strategy for being "backwards compatible" with any kind of persistent data will help. Having a fully automated build and deployment process will help.

At the end, this is a tradeoff, and there is no "one-size-fits-all" rule here. You have to consider how much effort a specific name change will cause in your case (do not forget the testing and deployment efforts), and compare that to how much benefit you expect to get from the renaming in your case. If the majority of the groundwork detailed above is in place, the effort for changing the names may be small enough to justify it.


答:
Place the guard within the method itself.  The consumer of GiveApples() or GiveBananas() shouldn't be responsible for managing the guards of GiveApples().

From a design standpoint SomeMethod() should only knows that it needs fruit and shouldn't care about what your application needs to do in order to get it.  The abstraction of fruit retrieval becomes leaky if SomeMethod() is responsible for knowing that there is a global setting that permits retrieval of certain fruit.  This cascades if your guard mechanism ever changes, as now all methods that need to GetApples() or GetBananas() need to be refactored separately to implement this new guard.  It's also very easy to forgetfully try and get fruit without that  check as you're writing code.

What you should consider in this scenario is how your application should react when Settings does not allow your application to give fruit.

Title: Is it better to guard the method call or the method itself?

Body:
I am writing an application and I got to this point:

private void SomeMethod()
{
    if (Settings.GiveApples)
    {
        GiveApples();
    }

    if (Settings.GiveBananas)
    {
        GiveBananas();
    }
}

private void GiveApples()
{
    ...
}

private void GiveBananas()
{
    ...
}
```

<p>This looks pretty straight-forward. There are some conditions and if they are true the methods are being called. However, I was thinking, is it rather better to do like this:</p>

<pre class="lang-cs prettyprint-override"><code>private void SomeMethod()
{
    GiveApples();
    GiveBananas();
}

private void GiveApples()
{
    if (!Settings.GiveApples)
    {
        return;
    }

    ...
}

private void GiveBananas()
{
    if (!Settings.GiveBananas)
    {
        return;
    }

    ...
}
</code>```

In the second case, each of the methods guards itself, so even if any of those methods GiveApples or GiveBananas is called from outside SomeMethod, they are going to be executed only if they have the correct flag in Settings.

Is this something that I should actually consider as a problem?

In my current context, it is very unlikely that those two methods will be called from outside this method, but no one can ever guarantee that.


问:
What is a correct way to exchange information between "frontend" and "backend"?
I am not so experienced in client-server applications and I could not find exactly answer to my question anywhere in google.

I am developing part of application on server side and my collegue who develops frontend suggest me that I should manipulate his payload rather then act as a service.

I will explain it in example:

Frontent receives some data in tree structure (it is JSON message):

```<code>Node1
  NodeB
  NodeC
  NodeD
Node2
  NodeE
  NodeF
  NodeG
</code>```

User wants to move NodeG from Node2 to Node1 (drag and drop).

So front-end application should send me whole payload and some instruction like "move NodeG to Node1" and wait until i process data, update database and send response with new structure and render it to the user?

or

front-end should send asynchronously just instructions to backend like "move NodeG to Node1" and care about displaying by itself.

as "Instruction" i mean some HTTP POST request.

答:
If you value consistency then the service that stores the data should be the definitive 'master' source of what the data looks like. This means that the front end must defer to whatever the service says. Now that doesn't mean it cannot cache results, but it should not make assumptions about logic that may (or may not) be processed on the service.

eg. Lets assume the user moves NodeG from node2 to Node1. The front end can assume success and redisplay the tree, but what if the user does not have permission to perform this move? Or if NodeG has some other characteristic that prevents it from being moved? When happens if the user then attempts to move NodeG from node1 (as it appears) to Node3? Suddenly you're in a world of broken user interface, inconsistent data, unhappy users and a real nightmare to fix.

So, send the data to the service (whether full payload or just relevant changes is up to you), and let the service respond to the front end that then displays the changes. The front end can cache this tree structure for re-display purposes without asking for it again, but it must honour all changes that the service sends to it and must never attempt to persist the tree for itself.


答:
Welcome to the world of coding in an object-oriented language that isn't using a framework to guard against any null-reference pathways. This pain is one of the primary reasons people look into paradigms from other languages to deal with this uncertainty. For example, immutable objects, once instantiated, can safely be treated as never-null if your instantiation code guarantees a proper non-null return, and proper non-null hydration of all that objects properties.

Here's a few of my personal thoughts about your code sample above:

If a given method can take any customer ID as a param, then it can't always return the same kind of object (an "Amount" object) for a case where the ID is valid versus invalid. And throwing an exception for every possible invalid value in every method is ugly Exception-driven-programming, which I personally dislike, because it breaks normal function flow and is sorta like GOTO in that regard. I'd suggest returning something like a Message<T> object, where the Amount class is the T for the call about, and the Message class has fields for things like bool Success and string[] Errors. That way, your method can just detect or try/catch on a failed Customer load, and return that message object without even trying to process a valid Amount return.

However, you are still left with a Message<Amount> object that might have a null Amount object packed inside. To deal with this, you have a few options. Firstly, just leave it null and set up your code to always check for the Success field before operating on the <T> inside. Or, you could create your return objects as struct's, which, being value types, are never null. HOWEVER, that comes with a world of consequences, so make sure you're OK with value types being passed around if so. Thirdly, you could make use of the NullObject pattern, wherein you define a way to construct an Amount object, but of a sub-type called something like NullAmount, and your consuming code will have to know how to look out for these NullAmount objects and react accordingly.

If you are dead-set against doing any kind of null or conditional checking when you consume the results of that method call, then probably throwing exceptions is your best bet, but I would strongly encourage you to looking to the Message pattern, or the NullObject pattern above as better solutions. Regardless, C#/Java allow object references to be null by design, and so some level of legwork is involved in checking for and dealing with, this most famous of Billion Dollar Mistakes.

Title: Handling null-references in C# logic


答:
One popular current 'state of the art' is to use a RESTful API service on the backend, and the front-end is responsible for data display and sending requests/commands to the server. This is usually done through simple HTTP requests to URLs with special meaning, but many other variants work generally the same way (with some varying details - think SOAP, etc).

In your case, the front-end loads up and calls a GET to /nodes, which returns a JSON from your back-end to your front-end with the full node structure as you outlined.

The user wants to move a node, so the front-end might POST to /nodes/move/{nodeToMove}/{nodeDestination}. The back-end attempts to execute the command, and then returns...well, what does the front-end want it to return? You can just return success/failure, or you can return the whole new structure. This depends on your particular situation - and if you don't need to return the whole new structure or the structure is very large, then don't return it.

How the front-end displays this is...well, up to the front-end person and will depend on use case, and there is no universal answer - it's about maximizing human usability. The front-end can "assume success", but then will have to figure out how to gracefully deal with the issue when an error returns or if data gets out of sync. What if the user request to move Node G under Node 1, then delete Node 2 and everything underneath it. If the first command failed, the second command might delete something unintentionally!

Then the question is of when to lock the UI - and the answer varies based on your use case and other aspects of what your program is actually doing. When a command that changes data has been issued it's usually best to block further changes until that first command has been verified to be completed, or you get into some weird situations - like trying to edit a file that has been deleted or that is currently being copied (will the copy show these edit changes?), etc.

Title: What is a correct way to exchange information between "frontend" and "backend"?

Body:
I am not so experienced in client-server applications and I could not find exactly answer to my question anywhere in google.

I am developing part of application on server side and my collegue who develops frontend suggest me that I should manipulate his payload rather then act as a service.

I will explain it in example:

Frontent receives some data in tree structure (it is JSON message):

```<code>Node1
  NodeB
  NodeC
  NodeD
Node2
  NodeE
  NodeF
  NodeG
</code>```

User wants to move NodeG from Node2 to Node1 (drag and drop).

So front-end application should send me whole payload and some instruction like "move NodeG to Node1" and wait until i process data, update database and send response with new structure and render it to the user?

or

front-end should send asynchronously just instructions to backend like "move NodeG to Node1" and care about displaying by itself.

as "Instruction" i mean some HTTP POST request.


答:
Honestly, I would just set up your project so it handles errors gracefully, probably by taking the user to a custom error page (via an error handler) that says something like "Whoops, somthing went wrong.  Try again later."

I admire the idea of trying to prevent the error in the first place (and @DavidArno's idea with transactions is spot on).  But just know that at some point there will just be some errors you can't possibly code around, like, say, having your database server just die mid-request.  Sure, you could put in thousands of checks all over the place for every conceivable situation, but then your code becomes an unmaintainable nightmare.  Would you want to have a code base like this (psuedocode, also exaggerated to make a point):

```<code>function GetUserName(userId) {
    get connection
    check to make sure connection failure one didn't happen
    check to make sure connection failure two didn't happen
    ....
    check to make sure connection failure nine didn't happen
    check to make sure connection failure ten didn't happen
    try grabbing the user
    check that no errors were thrown because the db may have died
    repeat previous checks again
    check that user is not null
    make sure ....
    return user.Name;
}
</code>```

What should be a simple, couple line function has now ballooned into a huge monster.  I don't want to imagine something more complicated.  (This isn't to say that some error checking isn't appropriate.  At some point, however, you do need to assume that stuff will work.)

Sometimes you just have to be tolerant of life happening.  A generic oops message suffices when there isn't anything more specific to say that is worth having more complicated code.

Title: Handling null-references in C# logic

Body:
Honestly, I would just set up your project so it handles errors gracefully, probably by taking the user to a custom error page (via an error handler) that says something like "Whoops, somthing went wrong.  Try again later."

I admire the idea of trying to prevent the error in the first place (and @DavidArno's idea with transactions is spot on).  But just know that at some point there will just be some errors you can't possibly code around, like, say, having your database server just die mid-request.  Sure, you could put in thousands of checks all over the place for every conceivable situation, but then your code becomes an unmaintainable nightmare.  Would you want to have a code base like this (psuedocode, also exaggerated to make a point):

function GetUserName(userId) {
    get connection
    check to make sure connection failure one didn't happen
    check to make sure connection failure two didn't happen
    ....
    check to make sure connection failure nine didn't happen
    check to make sure connection failure ten didn't happen
    try grabbing the user
    check that no errors were thrown because the db may have died
    repeat previous checks again
    check that user is not null
    make sure ....
    return user.Name;
}

What should be a simple, couple line function has now ballooned into a huge monster.  I don't want to imagine something more complicated.  (This isn't to say that some error checking isn't appropriate.  At some point, however, you do need to assume that stuff will work.)

Sometimes you just have to be tolerant of life happening.  A generic oops message suffices when there isn't anything more specific to say that is worth having more complicated code.


答:
A drag/drop UI typically encourages users to play around with the interface. You may not want to have every UI operation send data back to the server every time they interact with the interface. Depending on the specific interface it may not be an issue, but it's something to think about. What happens to the UI if the server response time starts to grow? How would users interact with the application if there were concurrency issues (a record is locked, etc) or permission issues?

One possibility is to have a staging-area in the front-end. For example, let the users drag and drop and manipulate the tree as much as they want, and then submit one request when they're finished to send the result to the server. You reduce calls this way, and protect against a lot of potential issues. As far as the server sees, there's just one POST, and probably a subsequent GET so the client can rerender the tree. If every UI interaction caused a POST, you would need to follow each one with a GET and a rerender to keep front and back ends in sync - probably not ideal because it doesn't scale well and eats up more resources than needed.


问:
JavaScript & AngularJs Modules Implementation technique and structure
So Im building an app and I'm trying to implement the structure of the app so that its robust and scalable in future.

My app is mostly divided into JavaScript Modules (revealing pattern):

```<code>// filter.js file
//My javascript module structure
var filter = (function(){

var _privateMethod = function(){
}

var publicMethod = function(){
    _privateMethod();
}

return{
   publicMethod: publicMethod
}
});
</code>```

Now the main issue is that I want to use AngularJS within my app too and AngularJs has its own angular modules like so:

```<code>// app.js file
var myApp =  angular.module('myApp',[]);
myApp.controller('myController', function($scope){

});
</code>```

The way I have planned my app developed is:

All HTTP calls to the server will be done within my JavaScript module or to be more clear within my "filter.js" file (see above)

Returned data from the HTTP calls to server will then be sent back to angularjs controller or in my case the "app.js" file (see above) and that controller/app.js file will be responsible for updating my view/html file.

The reason for doing this is so that all my functions that connect with server and handle data are within a private scope (the filter.js module) and no one should have access to those functions as they are being kept out of the  global scope.

But to pass data from my filter.js file to my Angular app.js controller I had to use callbacks.

Below is the complete code of my above described scenario:

filter.js

```<code>var filter = (function(){

// public method
var testMethod = function(callback){
  loadDoc(function(dta){
    alert(dta);
    callback(dta);
 })
};

// private Method
function loadDoc(callback) {
  // Create the XHR object to do GET to /data resource
  var xhr = new XMLHttpRequest();
  var dta;
  xhr.open("GET","url",true);

  // register the event handler
  xhr.addEventListener('load',function(){
  if(xhr.status === 200){
       //alert("We got data: " + xhr.response);
        dta = xhr.response;
        callback(dta);
   }
  },false)

  // perform the work
  xhr.send();
  }

 return {
     testMethod: testMethod
  };

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

app.js:

```<code>var myApp = angular.module('myApp',[]);

myApp.controller('myController', function($scope){

$scope.myFunc = function(){

     filter.testMethod(function(dta){
        alert(dta);
        $scope.test = dta;
        console.log($scope.test);
      });
   };
});
</code>```

You can see from my above code structure that I am using callbacks to send data back to my controllers.

My Question:

My question is that the above descried scenario of how I see my code
implementation and structure, is that right approach?

Does the implementation adhere to good, clean and correct javascript
    code?

Is there something else I can do to improve my app's code structure?

答:
I would argue that, in the case of AngularJS, utilizing callbacks is a code smell. I say this for the pure simple fact that AngularJS includes the notion of promises that you can leverage for the same use-case, and in fact look extremely similar in practice to the code you have already developed.  Consider your test method:

```<code>var testMethod = function() {
  return loadDoc();
};

function loadDoc(callback) {
    // Create the XHR object to do GET to /data resource
    var xhr = new XMLHttpRequest();
    var dta,
        // This is the deferred action
        defer = $q.defer();
    xhr.open("GET","url",true);

    // register the event handler
    xhr.addEventListener('load',function() {
        if(xhr.status === 200) {
            // We have a response, tell those who are waiting
            // about it
            defer.resolve(xhr.response);
        }

    }, false) ;

    // perform the work
    xhr.send();

    return defer.promise;
}
</code>```

The calling code could look like this:

```<code>testMethod().then(function(data) {
    console.log('data', data);
});
</code>```

Not only that, but the calling code could also look like this:

```<code>function callTheTestMethod() {
    return testMethod().then(function(data) {
        console.log('data', data);

        return data;
    });
}
</code>```

And the code calling that code could look like this:

```<code>callTheTestMethod().then(function(data) {
    console.log('I have data here, too', data);
});
</code>```

Another benefit to using promises is that they already have a built-in way to handle failures:

```<code>if(xhr.status === 200) {
    defer.resolve(xhr.response);
} else if(xhr.status > 400 && xhr.status < 600) {
    defer.reject();
}
</code>```

Just glancing at your code, it looks like your callback is actually being called twice, and to me looks like a bug. Also, on a side note, I don't think you should be instantiating your own version of XMLHttpRequest here vs just using the Angular $http service, but perhaps you have your reasons.

I would suggest this approach: Build an AngularJS service that uses the built in $http service to abstract away your API Calls, something like this:

```<code>angular.module('my.module', [])
    .service('TestService', [
        '$http',
        function($http) {
            return {
                testMethod: testMethod
            };

            function testMethod() {
                // Just a simple example to illustrate private
                // method usage..
                var data = privateMethod();
                return $http.get('url/' + data);
            }

            // Since this function isn't returned in the object above, only
            // code that exists in this scope can actually reference it
            function privateMethod() {
                return '3';
            }
        }
    ])
;
</code>```

You can consume this service in a controller (or directive, or another service) in this fashion:

```<code>angular.module('app.module', ['my.module'])
    .controller('TestController', [
        'TestService',
        function(TestService) {

            activate(); // Prepare for Angular 2.0!

            function activate() {
                TestService.testMethod().then(
                    function(data) {
                        console.log('I still have data', data);
                    },
                    function() {
                        console.log('something went wrong...');
                    }
                );
            }
        }
   ])
;
</code>```

Body:
I would argue that, in the case of AngularJS, utilizing callbacks is a code smell. I say this for the pure simple fact that AngularJS includes the notion of promises that you can leverage for the same use-case, and in fact look extremely similar in practice to the code you have already developed.  Consider your test method:

var testMethod = function() {
  return loadDoc();
};

function loadDoc(callback) {
    // Create the XHR object to do GET to /data resource
    var xhr = new XMLHttpRequest();
    var dta,
        // This is the deferred action
        defer = $q.defer();
    xhr.open("GET","url",true);

    // register the event handler
    xhr.addEventListener('load',function() {
        if(xhr.status === 200) {
            // We have a response, tell those who are waiting
            // about it
            defer.resolve(xhr.response);
        }

    }, false) ;

    // perform the work
    xhr.send();

    return defer.promise;
}

The calling code could look like this:

testMethod().then(function(data) {
    console.log('data', data);
});

Not only that, but the calling code could also look like this:

function callTheTestMethod() {
    return testMethod().then(function(data) {
        console.log('data', data);

        return data;
    });
}

And the code calling that code could look like this:

callTheTestMethod().then(function(data) {
    console.log('I have data here, too', data);
});

Another benefit to using promises is that they already have a built-in way to handle failures:

if(xhr.status === 200) {
    defer.resolve(xhr.response);
} else if(xhr.status > 400 && xhr.status < 600) {
    defer.reject();
}

Just glancing at your code, it looks like your callback is actually being called twice, and to me looks like a bug. Also, on a side note, I don't think you should be instantiating your own version of XMLHttpRequest here vs just using the Angular $http service, but perhaps you have your reasons.

I would suggest this approach: Build an AngularJS service that uses the built in $http service to abstract away your API Calls, something like this:

angular.module('my.module', [])
    .service('TestService', [
        '$http',
        function($http) {
            return {
                testMethod: testMethod
            };

            function testMethod() {
                // Just a simple example to illustrate private
                // method usage..
                var data = privateMethod();
                return $http.get('url/' + data);
            }

            // Since this function isn't returned in the object above, only
            // code that exists in this scope can actually reference it
            function privateMethod() {
                return '3';
            }
        }
    ])
;

You can consume this service in a controller (or directive, or another service) in this fashion:

angular.module('app.module', ['my.module'])
    .controller('TestController', [
        'TestService',
        function(TestService) {

            activate(); // Prepare for Angular 2.0!

            function activate() {
                TestService.testMethod().then(
                    function(data) {
                        console.log('I still have data', data);
                    },
                    function() {
                        console.log('something went wrong...');
                    }
                );
            }
        }
   ])
;


问:
REST API security Stored token vs JWT vs OAuth
I am still trying to find the best security solution for protecting REST API, because the amount of mobile applications and API is increasing every day.

I have tried different ways of authentication, but still has some misunderstandings, so I need advice of someone more experienced.

Let me tell, how I understand all this stuff. If I understand something incorrectly, please let me know.

As far as REST API is stateless as well as WEB in general, we need to send some auth data in each request(cookies, token....). I know three widely used mechanisms to authenticate user

Token with HTTPS. I have used this approach a lot of times it is good enough with HTTPS. If user provides correct password and login, he will receive token in response, and will use it for the further requests. Token is generated by the server and stored, for instance in the table separate or the same where user info is stored. So for each request server checks if user has token and it is the same as in the database. Everything is pretty straightforward.

JWT Token. This token is self-descriptive, it contains all necessary information about the token itself, user cannot change for example expiration date or any other claim, because this token is generated (signed) by the server with secret keyword. This is also clear. But one big problem, personally for me, how to invalidate token.

OAuth 2. I don't understand why this approach should be used when communication is established directly between server and client. As far as I understand, OAuth server is used to issue token with restricted scope to allow other applications access user information without storing password and login. This is great solution for the social networks, when user wants to sign up on some page, server can request permissions to get user info, for instance from twitter or facebook, and fill registration fields with user data and so on.

Consider mobile client for online store.

First question should I prefer JWT over first type token ? As far as I need login/logout user on mobile client, I need to store somewhere token or in case of JWT, token should be invalidated on logout. Different approaches are used to invalidate token one of the is to create invalid token list (black list). Hmm. Table/file will have much bigger size than if token was stored in table and associated with user, and just removed on logout.

So what are benefits of JWT token ?

Second question about OAuth , should I use it in case of direct communication with my server?  What is the purpose of one more layer between client and server only to issue token, but communication will be not with oauth server but with the main server. As I understand OAuth server is responsible only for giving third-party apps permissions (tokens) to access user private information. But my mobile client application is not third-party.

答:
Consider the first case.  Each client gets a random ID that lasts for the duration of the session - which could be several days if you like.  Then you store the information relevant to that session somewhere server side.  It could be in a file or a database.  Let's suppose you pass the ID via a cookie but you could use the URL or an HTTP header.

Session IDs/ Cookies

Pros:

Easy to code both the client and server.

Easy to destroy a session when someone logs out.

Cons:

The server side periodically needs to delete expired sessions where the client didn't logout.

Every HTTP request requires a lookup to the data store.

Storage requirements grow as more users have active sessions.

If there are multiple front end HTTP servers the stored session data needs to be accessible by all of them.  This could be a bit more work than storing it on one server.  The bigger issues are the data store becomes a single point of failure and it can become a bottleneck.

JSON Web Tokens (JWT)

In the second case the data is stored in a JWT that is passed around instead of on the server.

Pros:

The server side storage issues are gone.

The client side code is easy.

Cons:

The JWT size could be larger than a session ID.  It could affect network performance since it is included with each HTTP request.

The data stored in the JWT is readable by the client.  This may be an issue.

The server side needs code to generate, validate, and read JWTs.  It's not hard but there is a bit of a learning curve and security depends on it.

Anyone who gets a copy of the signing key can create JWTs.  You might not know when this happens.

There was (is?) a bug in some libraries that accepted any JWT signed with the "none" algorithm so anyone could create JWTs that the server would trust.

In order to revoke a JWT before it expires you need to use a revocation list.  This gets you back to the server side storage issues you were trying to avoid.

OAuth

Often OAuth is used for authentication (i.e. identity) but it can be used to share other data like a list of content the user has purchased and is entitled to download.  It can also be used to grant access to write to data stored by the third party.  You might use OAuth to authenticate users and then use server side storage or JWT for the session data.

Pros:

No code for users to signup or reset their password.

No code to send an email with a validation link and then validate the address.

Users do not need to learn/write-down another username and password.

Cons:

You depend on the third party in order for your users to use your service.  If their service goes down or they discontinue it then you need to figure something else out.  Eg: how do you migrate the user's account data if their identity changes from "foo@a.com" to "bar@b.com"?

Usually you have to write code for each provider.  eg Google, Facebook, Twitter.

You or your users might have privacy concerns.  The providers know which of their users use your service.

You are trusting the provider.  It is possible for a provider to issue tokens that are valid for one user to someone else.  This could be for lawful purposes or not.

Miscellaneous

Both session IDs and JWTs can be copied and used by multiple users.  You can store the client IP address in a JWT and validate it but that prevents clients from roaming from say Wi-Fi to cellular.


答:
Generally, it is often a good idea to separate the responsibilities of testing something like externally provided settings, and the "core businesss code" like GiveApples. On the other hand, having functions which group together what belongs together is also a good idea. You can accomplish both goals by refactoring your code like this:

private void SomeMethod()
{
    GiveApplesIfActivated();
    GiveBananasIfActivated();
}

private void GiveApplesIfActivated()
{
    if (Settings.GiveApples)
    {
        GiveApples();
    }
}

private void GiveBananasIfActivated()
{
    if (Settings.GiveBananas)
    {
        GiveBananas();
    }
}

private void GiveApples()
{
    ...
}

private void GiveBananas()
{
    ...
}
```

This  gives you a better chance to refactor the code of GiveApples and/or GiveBananas into a separate place without any dependencies from the Settings class. That is obviously beneficial when you want to call those methods in a unit test which does not care for any Settings.

However, if it is always wrong in your program, under any circumstances, even in a testing context, to call something like GiveApples outside a context where Settings.GiveApples is checked first, and you are under impression just providing a function like GiveApples without the Settings check is error-prone, then stick to the variant where you test Settings.GiveApples inside of GiveApples.

Body:
Generally, it is often a good idea to separate the responsibilities of testing something like externally provided settings, and the "core businesss code" like GiveApples. On the other hand, having functions which group together what belongs together is also a good idea. You can accomplish both goals by refactoring your code like this:

private void SomeMethod()
{
    GiveApplesIfActivated();
    GiveBananasIfActivated();
}

private void GiveApplesIfActivated()
{
    if (Settings.GiveApples)
    {
        GiveApples();
    }
}

private void GiveBananasIfActivated()
{
    if (Settings.GiveBananas)
    {
        GiveBananas();
    }
}

private void GiveApples()
{
    ...
}

private void GiveBananas()
{
    ...
}

This  gives you a better chance to refactor the code of GiveApples and/or GiveBananas into a separate place without any dependencies from the Settings class. That is obviously beneficial when you want to call those methods in a unit test which does not care for any Settings.

However, if it is always wrong in your program, under any circumstances, even in a testing context, to call something like GiveApples outside a context where Settings.GiveApples is checked first, and you are under impression just providing a function like GiveApples without the Settings check is error-prone, then stick to the variant where you test Settings.GiveApples inside of GiveApples.


问:
Parallel hierarchies - partly same, partly different
There are quite a few similar questions out there 1, 2, 3, 4, but non seems exactly the case in this question, nor do the solutions seem optimal.

This is a general OOP question, assuming polymorphism, generics, and mixins are available. The actual language to be used is OOP Javascript (Typescript), but it's the same problem in Java or C++.

I have parallel class hierarchies, that sometimes share the same behaviour (interface and implementation), but sometimes each has its own 'protected' behaviour. Illustrated like so:

This is for illustration purposes only; it isn't the actual class diagram. To read it:

Anything in the common hierarchy (centre) is shared between both the Canvas (left) and SVG (right) hierarchies. By share I mean both interface and implementation.

Anything only on the left or right columns means a behaviour (methods and members) specific to that hierarchy. For example:

Both the left and right hierarchies use exactly the same validation mechanisms, shown as a single method (Viewee.validate()) on the common hierarchy.

Only the canvas hierarchy has a method paint(). This method calls the paint method on all children.

The SVG hierarchy needs to override the addChild() method of Composite, but such is not the case with the canvas hierarchy.

The constructs from the two side hierarchies cannot be mixed. A factory ensures that.

Solution I - Tease Apart Inheritance

Fowler's Tease Apart Inheritance doesn't seem to do the job here, because there is some discrepancy between the two parallels.

Solution II - Mixins

This is the only one I can currently think of. The two hierarchies are develop separately, but at each level the classes mixin the common class, which are not part of a class hierarchy. Omitting the structural fork, will look like this:

Note that each column will be in its own namespace, so class names won't conflict.

The question

Can anyone see faults with this approach? Can anyone think of a better solution?

Addendum

Here is some sample code how this is to be used. The namespace svg may be replaced with canvas:

```<code>var iView        = document.getElementById( 'view' ),
    iKandinsky   = new svg.Kandinsky(),
    iEpigone     = new svg.Epigone(),
    iTonyBlair   = new svg.TonyBlair( iView, iKandinsky ),
    iLayer       = new svg.Layer(),
    iZoomer      = new svg.Zoomer(),
    iFace        = new svg.Rectangle( new Rect( 20, 20, 100, 60) ),
    iEyeL        = new svg.Rectangle( new Rect( 20, 20, 20, 20) ),
    iEyeR        = new svg.Rectangle( new Rect( 60, 20, 20, 20) );

iKandinsky.setContext( iTonyBlair.canvas.getContext( '2d' ) );
iEpigone.setContext( iTonyBlair.canvas.getContext( '2d' ) );

iFace.addChildren( iEyeL, iEyeR );
iZoomer.setZoom( new Point( 2, 2 ) );
iZoomer.addChild( iFace );
iLayer.addChild( iZoomer );
iTonyBlair.setContent( iLayer );
</code>```

Essentially, in run-time clients compose instances hierarchy of Viewee subclasses; like so:

Say all these viewees are from the canvas hierarchy, they are rendered by traversing the hierarchy can calling paint() on each viewee. If they are from the svg hierarchy, viewees know how to add themselves to the DOM, but there isn't paint() traversal.

答:
In an article titled Design Patterns for Dealing with Dual Inheritance Hierarchies in C++, Uncle Bob presents a solution called Stairway to Heaven. It's stated intent:

This pattern describes the network of inheritance relationships that is needed when a given hierarchy must be adapted, in its entirety, to another class.

And the diagram provided:

Although in solution 2 there isn't virtual inheritance, it is very much in accord with the Stairway to Heaven pattern. Thus solution 2 seems reasonable to this problem.


问:
Why are reference-counting smart pointers so popular?
As I can see, smart pointers are used extensively in many real-world C++ projects.

Though some kind of smart pointers are obviously beneficial to support RAII and ownership transfers, there is also a trend of using shared pointers by default, as a way of "garbage collection", so that the programmer do not have to think about allocation that much.

Why are shared pointers more popular than integrating a proper garbage collector like Boehm GC? (Or do you agree at all, that they are more popular than actual GCs?)

I know about two advantages of conventional GCs over reference-counting:

Conventional GC algorithms has no problem with reference-cycles.

Reference-count is generally slower than a proper GC.

What are the reasons for using reference-counting smart pointers?

答:
As I can see, smart pointers are used extensively in many real-world C++ projects.

True but, objectively, the vast majority of code is now written in modern languages with tracing garbage collectors.

Though some kind of smart pointers are obviously beneficial to support RAII and ownership transfers, there is also a trend of using shared pointers by default, as a way of "garbage collection", so that the programmer do not have to think about allocation that much.

That's a bad idea because you still need to worry about cycles.

Why are shared pointers more popular than integrating a proper garbage collector like Boehm GC? (Or do you agree at all, that they are more popular than actual GCs?)

Oh wow, there are so many things wrong with your line of thinking:

Boehm's GC is not a "proper" GC in any sense of the word. It is truly awful. It is conservative so it leaks and is inefficient by design. See: http://flyingfrogblog.blogspot.co.uk/search/label/boehm

Shared pointers are, objectively, nowhere near as popular as GC because the vast majority of developers are using GC'd languages now and have no need of shared pointers. Just look at Java and Javascript in the job market compared to C++.

You appear to be restricting consideration to C++ because, I assume, you think that GC is a tangential issue. It isn't (the only way to get a decent GC is to design the language and VM for it from the beginning) so you are introducing selection bias. People who really want proper garbage collection don't stick with C++.

What are the reasons for using reference-counting smart pointers?

You are restricted to C++ but wish you had automatic memory management.


问:
When testing is it OK to use a method of the subject to test another method of the subject?
I have two methods in the same helper class one that creates an image (createImage) and one that compares two images (compareImages).

```<code>Image createImage(Data data);
Boolean compareImages(Image from, Image to);
</code>```

I want to check the return of createImage against an existing image. To do this I need a method exactly like compareImages.

Is it OK to use compareImages to validate createImage even if they both belong to the subject? This feels nasty to me.

答:
A unit test should be able to use any code or logic that itself is properly tested.

A unit test should have minimal logic in it. It should be straight forward as to its test and that one can look at it and reason about it.

Reimplementing an equals method violates DRY. In doing so, it introduces the possibility of having equals diverge and a bug slip in to the actual code being tested because it is still using an old copy of the code. It also adds non-trivial logic to the unit test.

So, going back to the first point - if equals is properly tested, there is no issue with using it in another unit test. In fact, one should encourage its use.  The danger of false passes in this test would only be an issue if the tests for equals were to miss those conditions and failed to fail.

You do not expose yourself to any more bugs in your code by using more than a narrowly defined 'unit' worth of code in the test. You only expose yourself to not catching a bug in a more than ideally complex unit test if the code that it leverages is less than ideally tested itself.

Don't get caught up in the dogma of "a unit test must be..." If the test makes more sense written leveraging code that you've already tested, write the test that makes sense.


答:
The biggest disadvantage of garbage collection in C++ is, that it's plain impossible to get right:

In C++, pointers do not live in their own walled community, they are mixed with other data. As such, you can't distinguish a pointer from other data that just happens to have a bit pattern that can be interpreted as a valid pointer.

Consequence: Any C++ garbage collector will leak objects that should be collected.

In C++, you can do pointer arithmetic to derive pointers. As such, if you don't find a pointer to the start of a block, that does not mean that that block can't be referenced.

Consequence: Any C++ garbage collector has to take these adjustments into account, treating any bit sequence that happens to point anywhere within a block, including right after the end of it, as a valid pointer that references the block.

Note: No C++ garbage collector can handle code with tricks like these:

```<code>int* array = new int[7];
array--;    //undefined behavior, but people may be tempted anyway...
for(int i = 1; i <= 7; i++) array[i] = i;
</code>```

True, this invokes undefined behavior. But some existing code is more clever than is good for it, and it may trigger preliminary deallocation by a garbage collector.

Title: Why are reference-counting smart pointers so popular?

Body:
As I can see, smart pointers are used extensively in many real-world C++ projects.

Though some kind of smart pointers are obviously beneficial to support RAII and ownership transfers, there is also a trend of using shared pointers by default, as a way of "garbage collection", so that the programmer do not have to think about allocation that much.

Why are shared pointers more popular than integrating a proper garbage collector like Boehm GC? (Or do you agree at all, that they are more popular than actual GCs?)

I know about two advantages of conventional GCs over reference-counting:

Conventional GC algorithms has no problem with reference-cycles.

Reference-count is generally slower than a proper GC.

What are the reasons for using reference-counting smart pointers?

Body:
The biggest disadvantage of garbage collection in C++ is, that it's plain impossible to get right:

In C++, pointers do not live in their own walled community, they are mixed with other data. As such, you can't distinguish a pointer from other data that just happens to have a bit pattern that can be interpreted as a valid pointer.

Consequence: Any C++ garbage collector will leak objects that should be collected.

In C++, you can do pointer arithmetic to derive pointers. As such, if you don't find a pointer to the start of a block, that does not mean that that block can't be referenced.

Consequence: Any C++ garbage collector has to take these adjustments into account, treating any bit sequence that happens to point anywhere within a block, including right after the end of it, as a valid pointer that references the block.

Note: No C++ garbage collector can handle code with tricks like these:

int* array = new int[7];
array--;    //undefined behavior, but people may be tempted anyway...
for(int i = 1; i <= 7; i++) array[i] = i;

True, this invokes undefined behavior. But some existing code is more clever than is good for it, and it may trigger preliminary deallocation by a garbage collector.


问:
How to structure big Node.JS modules
I am working on a rather big Node.JS project with several thousand lines of code. It's not a homepage, but acts more like a configurable general purpose application server. As such it brings some parts which are useful in most projects I do.

The problem is that I easily lose overview in the core modules. So I did a bit of research and came up with an interesting structure based on C++ Header/Code file structures. I want to know if this structure is good in the long run (maintainability, testability, extensibility), how it can be improved and if there is already a (better) "standard" way of doing the structuring I did not find.

The structure has three kinds of files, where xxx is the module name and yyy is the method name.

xxx.h.js: The "header" file, which contains the class and method declarations

xxx.yyy.c.js: The "code" files, which contain one method each (and possibly local helper functions)

index-xxx.js: The glue and main file for the module

I would like to structure all my sub-modules like this and then use a loading-mechanism to load all modules, namespace them and finally use them globally.

Here's an example:

package.json

```<code>{
    "name": "Foo",
    "version": "1.0.0",
    "description": "Does something in the core system",
    "author": "Marco Alka",
    "main": "index-foo.js"
}
</code>```

```<code>// index-foo.js
'use strict';

// return class
module.exports = require('./foo.h.js');

// overwrite definitions with declarations
// this part can and most probably will be done generically by my module loader. I write it down for easier overview.
require('./src/foo.bar.c.js');
require('./src/foo.baz.c.js');
</code>```

```<code>// foo.h.js
'use strict';

/**
 * Easy-to-read interface/class
 * No obstructive code in my way
 */
module.exports = class Foo {

  constructor() {}

  /**
   * Put comments here
   */
  bar() { throw 'Not Implemented'; }

  /**
   * More comments for methods
   * See how the method declarations+documentations nicely dominate the file?
   */
  baz() { throw 'Not Implemented'; }
}
</code>```

```<code>// src/foo.bar.c.js
'use strict';

// include header
var h = require('../foo.h.js');

// implement method Foo::bar
h.prototype.bar = function () {

  console.log('Foo.bar');
}
</code>```

```<code>// src/foo.baz.c.js
'use strict';

// include header
var h = require('../foo.h.js');

// implement method Foo::bar
h.prototype.baz = function () {

  console.log('Foo.baz');
}
</code>```

Example on how to use the whole thing from within the root folder

```<code>'use strict';

// later on a module loader will be used which loads the folder as module instead of the index file directly
var F = require('./index-foo.js');

// make object
var foo = new F();

// call method
foo.bar();
</code>```

Output in console: Foo.bar\n

答:
I'm a newbie and I'm pretty sure this is an opinion-based answer which is really outside the scope of the board.   With that, here's my practical experience:

There are no implicitly bad ways to structure code, so long as the structure can be described simply.

The only thing bad about poor code structure is lack of discipline: if you consistently follow the structure when developing, then you or anyone else editing your code should be able to discern the context quickly.

Even if you are the only person on your development team (which is sounds like you are), use Git or some other kind of repository with good robust explanations for what you changed and why.

It's been my experience that code structures are not usually the culprits for making things difficult to manage.   It's logical architecture and documentation.   If you have a good logical architecture that clearly defines modularity of functionality and you document what you've done, it will be an investment that pays off.

Title: How to structure big Node.JS modules


问:
Demonstration of garbage collection being faster than manual memory management
I've read in many places (heck, I've even written so myself) that garbage collection could (theoretically) be faster than manual memory management.

However, showing is a lot harder to come by than telling.

I have never actually seen any piece of code that demonstrates this effect in action.

Does anyone have (or know where I can find) code that demonstrates this performance advantage?

答:
I have done quite a bit of work on this and described some of it here. I benchmarked the Boehm GC in C++, allocating using malloc but not freeing, allocating and freeing using free and a custom-built mark-region GC written in C++ all vs OCaml's stock GC running a list-based n-queens solver. OCaml's GC was faster in all cases. The C++ and OCaml programs were deliberately written to perform the same allocations in the same order.

You can, of course, rewrite the programs to solve the problem using only 64-bit integers and no allocations. Although faster that would defeat the point of the exercise (which was to predict the performance of a new GC algorithm I was working on using a prototype built in C++).

I have spent many years in industry porting real C++ code to managed languages. In almost every single case I observed substantial performance improvements, many of which were probably due to GC trumping manual memory management. The practical limitation is not what can be accomplished in a microbenchmark but what can be accomplished before a deadline and GC-based languages offer such huge productivity improvements that I never looked back. I still use C and C++ on embedded devices (microcontrollers) but even that is changing now.


问:
How different is garbage collection in pure languages?
In a pure language like Haskell, all data is immutable and no existing data structures can be changed in any way. Additionally, many algorithms on immutable data and functional programming patterns generate large amounts of garbage by nature (chains of map creating intermediate lists for example).

What strategies and techniques do garbage collectors employ in the face of purity that they wouldn't otherwise? What works very well in an impure language's GC that doesn't in a pure context? What other new problems do pure languages create for GCs?

答:
In a pure language like Haskell, all data is immutable and no existing data structures can be changed in any way

Actually that is not generally true. Pure languages use non-strict (lazy) evaluation so the evaluation of potentially all subexpressions is deferred. Unevaluated expressions are generally heap allocated as a "thunk". When required the expression is evaluated and the thunk is mutated into the resulting value.

What strategies and techniques do garbage collectors employ in the face of purity that they wouldn't otherwise?

The only thing I can think of is black holes. I don't recall seeing anything else new on the GC side in the Haskell research papers.

What works very well in an impure language's GC that doesn't in a pure context?

The GC write barrier. Impure languages tend to write pointers into the heap a lot more so they tend to have their write barriers more heavily optimised.

Other GC algorithms such as mark-region are much more viable in the context of impure languages because they can have much lower allocation rates than pure languages.

What other new problems do pure languages create for GCs?

Pure languages are very rare so there is a lot less data on how pure programs use memory and, therefore, you are starting in a worse position when trying to write a GC for a pure language.


答:
In MacOS X and iOS, and with developers using Objective-C or Swift, reference counting is popular because it is handled automatically, and the use of garbage collecting has considerably decreased since Apple doesn't support it anymore (I am told that apps using garbage collection will break in the next MacOS X version, and garbage collection was never implemented in iOS). I actually seriously doubt that there was ever much software using garbage collection when it was available.

The reason for getting rid of garbage collection: It never worked reliably in a C-style environment where pointers could "escape" to areas not accessible by the garbage collector. Apple strongly believed and believes that reference counting is faster. (You can make any claims here about relative speed, but nobody has been able to convince Apple). And in the end, nobody used garbage collection.

First thing that any MacOS X or iOS developer learns is how to handle reference cycles, so that's not a problem for a real developer.


问:
Rewriting conditionals in OOP without generics
Let's say I have a set of objects,

```<code>foo f;
bar br;
baz bz;
</code>```

I also have a string of JSON data,

```<code>string JSONstring;
</code>```

Depending on the object type of the JSON string, I need to transform it into either foo, bar, or baz. Ok, cool, I'll have a method for that.

```<code>public object parseJSONToFooBarBaz(string jsonString);
</code>```

What I want to avoid is writing something like:

```<code>map<string, object> topLevelJSON = deserialized json string;

if(map[foo] != null) return new foo(jsonString);
else if(map[bar] != null) return new bar(jsonString);
...
// And the list balloons up and is difficult to maintain
</code>```

I feel like this is either a good condidate or almost a good candidate for a factory pattern, but something doesn't feel quite right. Is there a simple solution that I'm overlooking, or is a set of conditionals or a switch/case really an OK way to solve this?

答:
The simplest thing to do is to make a map<string, string -> object) where string -> object just means a function taking a string and producing an object.  If the language you are using doesn't support first-class functions you can use the Strategy pattern.  The Factory pattern is essentially just a special case of the Strategy pattern and thus just a round-about way of doing first-class functions (though the term "Factory" communicates intent.)

You could then do something like:

```<code>foreach(key in factories.keys()) {
    if(topLevelJSON[key] != null) {
        return factories[key](jsonString);
    }
}
</code>```

I assume these keys are mutually exclusive (as suggested by your if statements), though you could easily adapt the code to return all the choices or have a list of the factories in priority order.

Body:
The simplest thing to do is to make a map<string, string -> object) where string -> object just means a function taking a string and producing an object.  If the language you are using doesn't support first-class functions you can use the Strategy pattern.  The Factory pattern is essentially just a special case of the Strategy pattern and thus just a round-about way of doing first-class functions (though the term "Factory" communicates intent.)

You could then do something like:

foreach(key in factories.keys()) {
    if(topLevelJSON[key] != null) {
        return factories[key](jsonString);
    }
}

I assume these keys are mutually exclusive (as suggested by your if statements), though you could easily adapt the code to return all the choices or have a list of the factories in priority order.


问:
What are the differences between operating systems and computer systems?
Wikipedia's definition of a "computer system" is:

Computer system is define as the combination of hardware software user and data with referring to communication and procedure involved in between them.

Which doesn't make much sense to me. Whereas the definition of an operating system is:

An operating system (OS) is system software that manages computer hardware and software resources and provides common services for computer programs.

Both those definitions seem to refer to the same thing: a system that manages hardware and software for controlling programs.

A list of topics doesn't help me much, either. For example, MIT's computer systems course lists the topics as:

virtual memory

threads

networks

atomicity

coordination of parallel activities

recovery and reliability

privacy, security, and encryption

While MIT's operating systems course lists the topics as:

virtual memory

threads

context switches

kernels

interprocess communication

interrupts

system calls

coordination

interaction between software and hardware*

*According to the only answer to this question, this is a computer systems topic?

It seems like OS is slightly more related to software and to individual computers, whereas computer systems might involve multiple computers?

答:
Both those definitions seem to refer to the same thing: a system that manages hardware and software for controlling programs.

No, the first definition says "a computer system is a combination of hardware and software, not it manages the latter. That means a computer system includes both - the hardware (processor, main board, various kinds of memory, gfx card power supply, peripherals etc.) plus the software  called operating system which manages the former. The term "computer systems" does also refer to systems build up from many computers, which are interconnected by a network.

Since operating systems ("software") are always part of a computer system ("software + hardware"), and they do manage hardware resources, it is not too surprising that the MIT course on computer systems covers also some aspects on operating systems. I do not know those courses, but from the title and the topics list I would expect them having some overlapping parts, but a different focus.

ContentLicense: CC BY-SA 4.0


问:
What are important things to remember when reengineering a legacy application?
About to embark on the initial phases of a project to rewrite a legacy application from the ground up (existing business rules will change somewhat, and be extended to incorporate a large number of new requirements that the existing infrastructure cannot handle). I am looking for items that are important to remember when working to reengineer an existing application.</p>

答:
Understand what the existing code base is doing. In any old legacy application there may be a good number of special cases that users are expecting, be wary of these and only intentionally and rationally change existing behaviour.

Coupled with 1. you must also test that the new functionality is doing what is intended (based off the understanding of what it is currently doing, or will be changing).

If it is a large application or code-base, plan for the change to be incrementally introduced, this should mitigate the danger of one large release and show progress.

Be especially careful if operating in an environment that is heterogeneous in versions of the software: beware file formats, network protocols, shared memory formats. Test and ensure compatibility between versions.

If changing a data storage system, be prepared to mirror writes for a while into the new system to test load and gradually transition reads onto the new system while retaining writes into the old system. Once the new system is solid, add the new functionality.

ContentLicense: CC BY-SA 2.5


问:
How are non-folder files called?
Maybe it looks like a weird question, but what term should be attributed inside the code for files that are not folders to differentiate them from folders?

If I need write 2 functions isFolder() and isFile() 2nd one has a misleading name because folders are files too

答:
It really depends upon the file system and the operating system.

In POSIX and Unix, a file can be a directory, a plain file, a block device, a character device, a FIFO, a socket, a symbolic link, ... See POSIX stat & Linux stat(2), notice that file can have different types.

So if you want to speak of a file whose type is plain and which is a sequence of bytes, you say that is is a plain file or a regular file.

If you want any file which is not a directory you could speak of a "non-directory" file (or maybe non-directory inode); it could be a plain file, a socket, a fifo, a symlink, etc...

Notice that POSIX and Linux don't know about folders (except on the desktop). They speak of directories.

Notice also that files are quite different on Windows, on MacOSX, on Linux, on POSIX....

Some experimental OSes don't even have files. They are persisting data in some other way. Historically, the very first editions of MS-DOS (or of MVS) did not had any directories (or folders).

Title: How are non-folder files called?


答:
This depends heavily on the filesystem and the operating system. For example, on Unix, there are no folders at all:

Windows has completely different terminology. Classic MacOS had a different terminology, which, in OSX, is now mixing with Unix terminology.

Title: How are non-folder files called?

Body:
Maybe it looks like a weird question, but what term should be attributed inside the code for files that are not folders to differentiate them from folders?

If I need write 2 functions isFolder() and isFile() 2nd one has a misleading name because folders are files too


问:
REST API - Handling subresources
Suppose there is a primary resource "/accounts" which has Profile (name, national id, DOB), addresses and contacts(email, phones). I am considering them as sub-resources because they cannot exist without an account. To update them I am thinking two options

Option 1

PUT /accounts/{accountid}/address

PUT /accounts/{accountid}/contacts

PUT /accounts/{accountid}/profile

Option 2

PUT /accounts/{accountid}

(Depending on the presence/absence of address/phone/profile decide which updates to perform)

I am tempted to use option 1 because from implementation perspective each of the updates have own logic & process flow. A separate URI may keep implementation cleaner & manageable

Would it be incorrect to consider profile,address,contacts as subresources. if so, what would be an appropriate way of representing them

If they can be considered sub-resources which among the above is an appropriate option or is there a completely different option to be considered

答:
HTTP and REST don't care if a resource is a "sub-resource", they have no structural knowledge of a "can't exist without" constraint.

From a consistency perspective, if PUT is allowed for a "sub-resource" I would at least expect to be able to GET it separately from its parent resource as well. Then a strict level 3 REST approach (HATEOAS) would also probably recommend to put a hypermedia link to the Address resource in the response for GET Account instead of directly including Address data there.

Title: REST API - Handling subresources


问:
Communication between nested directives
There seem to be quite a few ways of communicating between directives. Say you have nested directives, where the inner directives must communicate something to the outer (e.g. it's been chosen by the user).

```<code><outer>
  <inner></inner>
  <inner></inner>
</outer>
</code>```

So far I have 5 ways of doing this

require: parent directive

The inner directive can require the outer directive, which can expose some method on its controller. So in the inner definition

```<code>require: '^outer',
link: function(scope, iElement, iAttrs, outerController) {
   // This can be passed to ng-click in the template
   $scope.chosen = function() {
     outerController.chosen(something);
   }
}
</code>```

And in the outer directive's controller:

```<code>controller: function($scope) {
   this.chosen = function(something) {
   }
}
</code>```

$emit event

The inner directive can $emit an event, which the outer directive can respond to, via $on. So in the inner directive's controller:

```<code>controller: function($scope) {
  $scope.chosen = function() {
    $scope.$emit('inner::chosen', something);
  }
}
</code>```

and in the outer directives controller:

```<code>controller: function($scope) {
  $scope.$on('inner::chosen, function(e, data) {
  }
}
</code>```

Execute expression in parent scope, via &

The item can bind to an expression in the parent scope, and execute it at an appropriate point. The HTML would be like:

```<code><outer>
  <inner inner-choose="functionOnOuter(item)"></inner>
  <inner inner-choose="functionOnOuter(item)"></inner>
</outer>
</code>```

So the inner controller has an 'innerChoose' function it can call

```<code>scope: {
  'innerChoose': '&'
},
controller: function() {
  $scope.click = function() {
    $scope.innerChoose({item:something});
  }
}
</code>```

which would call (in this case) the 'functionOnOuter' function on the outer directive's scope:

```<code>controller: function($scope) {
  $scope.functionOnOuter = function(item) {
  }
}
</code>```

Scope inheritance on non-isolated scope

Given that these are nested controllers, scope inheritance can be at work, and the inner directive can just call any functions in the scope chain, as long as it doesn't have an isolated scope). So in the inner directive:

```<code>// scope: anything but a hash {}
controller: function() {
  $scope.click = function() {
    $scope.functionOnOuter(something);
  }
}
</code>```

And in the outer directive:

```<code>controller: function($scope) {
  $scope.functionOnOuter = function(item) {
  }
}
</code>```

By service injected into both inner and outer

A service can be injected into both directives, so they can have direct access to the same object, or call functions to notify the service, and maybe even register themselves to be notified, in a pub/sub system. This doesn't require the directives to be nested.

Question: What are any potential drawbacks and advantages of each over the others?

答:
My opinion:

Services are the preferred way of sharing behaviour/data across modules/directives/controllers. Directives are isolated things that can be nested or not. Controllers should stick to being a viewmodel as much as they can, ideally no business logic should end up in there.

So:

When you start wiring them together by accessing parent scope functions I think you risk coupling them way too hard and making the entire application unreadable and components not reusable. When you decouple that shared data or behaviour in a service you have the benefit of reusing the entire directives with different data/behaviour even determining the service to be used at runtime. Which is what dependency injection is all about.

Title: Communication between nested directives


问:
Are there any compilers that attempt to fix syntax errors on their own?
I heard a while back that there used to be a compiler that attempted to fix syntax errors by analyzing context and inferring what was intended.

Does such a compiler really exist? Obviously it has little practical value, but would be very interesting to play with and learn from.

答: It has been tried multiple times, but often it didn't achieve the desired effect: think HAL 9000 or GlaDOS.</p>


问:
Where does apply authorization rules for my layered application?
This question is about applying rules of my application that confuse me.

My controller is using service and the service is using repository.

```<code>public class CommentController: ApiController{

    [HttpPost]
    public bool EditComment(Comment comment){
        commentService.Update(comment);
    }
}

public class CommentService{
    ICommentRepository repository;
    ....
    ....
    public void Update(Comment comment){
        repository.Update(comment);
    }
}
</code>```

If the user is authenticated, he can update a comment.

But a user should edit own comments.

But an admin can edit all comments.

But comment can not edit after a specified date.

Edit by a department

And I have something like these rules.

If I apply "user editing own comment" rule in service layer, I will change Update methot and pass parameter of controller User.Identity.Name,

```<code>public class CommentService{
    ICommentRepository repository;
    ....
    ....
    public void Update(string updatedByThisUser, Comment comment){
        // if updatedByThisUser is owner of comment
        repository.Update(comment);
    }
}
</code>```

But, is true changing service operations by rule?

I am confused a bit about where can I apply the rules. In controller or in service or in repository.

Is there any standart way to do this like design patterns.

答:
I would

create a seperate PermissionService that implements methods like isUserAllowedTo(user, PermissionService.Permissiontype.Update, PermissionService.Topic.COMMENT, additionalContextRelevantParameters)

and call the PermissionService methods in the controller, where neccessary context info (i.e. from session) is available.

You can design your architecture to call the permission service in the CommentService. But i would not recommend this because this would add additional dependencies into the service (i.e. session) that makes unit-testing the service much more difficuilt