问:
OOP Design - Possible wrong approach makes it impossible to implement it in code
This last semester i've had lectures about OOP design, i understood most of what i was supposed to

but there is something that i can't get right.

I'm pretty sure that the models i create are wrong because they cannot be implemented.
I wrote quite a lot because i can't tell where the problem is.

This isn't homework , it is a sample of a problem from the past year.

An example:
Design a "Stackoverflow" like thing for a class.

Use case: Posting a question

pre-conditions: There is a authenticated student

pos-conditions: The question was recorded and everyone that can read the question has been notified.

Scenario:

```<code>1. The student tells the system he wants to submit a question and supplies the title
2. The system asks for the question body.
3. The student submits the question body.
4. The system records this.
5. The system reports all used question tags on that student's class.
6. The student submits the choosen question tag
7. The system records everything and reports the used tags
8. The student tells if he wants the question to be public
9. The system records everything and notifies the people it should
</code>```

Steps 6,7 can be repeated until the user tells us he's done.

There are extensions but not necessary to demonstrate my problem.

How would i do it:
System Sequence Diagram

```<code>newQuestion(title)
------------------>

OK
<------------------

submitBody(bodytext)
------------------->  _
                      | LOOP
Existing tags         |
<-------------------  |
                      |
choosetag(tag)        |
------------------->  |
                      _
chooseVisibility(b)
------------------->

OK
<-------------------
</code>```

The domain model would have:
Student
Class
Instructor
Question
Tag
StudentCatalog
InstructorCatalog

The relations between each other's are simple ( i believe ) thats why i'm not sketching it up.

I noticed my issue when making the interaction diagram for this use-case.

I decided that the use-case controller would be a made up "handler" class QuestionHandler so the first two interaction diagrams i would
believe to be something like:

```<code>newQuestion(title)
 - it has to create a question with the proper title title
 submitBody(bodytext)
 - it has to set bodytext has the text for the question we are creating ( and i don't know where it is!)
</code>```

The actual problem:

From all this i imagine the code to be:

```<code>class QuestionHandler
 method postQuestion(title) {
  newQuestion(title);
  submitBody(bodytext);
  ... etc
 }
</code>```

And i can't see this working like this, my problem where does "submitBody(bodytext)" gets the currentQuestion from?

How do i handle the "context" of each use-case, which in this case i would make it messy ( that's how it feels to me) and use the return values to make it work.

But what if i have a use-case "context" that requires lots of things to me change and moved around?

Im totally lost, i thought it would solve itself but it turns out o can't see how things would be implemented with this issue.

答:
Objects carry state. A sequence diagram doesn't convey this state, but your objects will keep state in between requests. You could go further and transmit the state as a method argument, as in submitBody(bodyText, session), but this is a bit dangerous in that it invites procedural style programming if you intend to simply translate this into code.

Instead, I would accept that your use case and state diagrams have some level of abstraction in them and they don't need to convey all the details. Your object details doesn't come entirely from diagrams.

Looking at the vocabulary of your domain, you should have a type along the lines of Question that constructs its state iteratively as more information is given to it by way of method calls into it. As stated already, this object would be maintained as state across requests, a typical scenario in workflow style interactions such as the one you describe here.

Fair enough?

OwnerDisplayName: Zentdayn

OwnerDisplayName: Mihai Danila


问:
Why would anyone invest time in Microsoft "Roslyn"?
I have just been reading through some of the white papers & examples from Microsoft "Roslyn" and the concept seems very interesting.  From what I can tell, it opens up the black box that is the compiler and provides an interface that we can use to get information and metrics about code written in Visual Studio.

Roslyn also appears to have the ability to "script" code and compile/execute it on the fly (similar to the CodeDom) but I have only come across limited uses for that type of functionality in my experience.

Whilst the code analysis & metrics element is an interesting space...it is something that has been around for a very long time and there are numerous providers that have already invested a lot of money into code analysis & refactoring tools (e.g. ReSharper, CodeRush, nCover, etc) and they do a pretty good job of it!

Why would any company go out of their way to implement something that can be provided at a fraction of a cost through buying a license for one of the existing tools?

Maybe I have missed some key functionality of the Roslyn project that places it outside the domain of the mentioned tools...

答:
Roslyn also appears to have the ability to "script" code and compile/execute it on the fly (similar to the CodeDom) but I have only come across limited uses for that type of functionality in my experience.

On-the-fly compilation and execution is the key benefit of Roslyn.  I think you may be undervaluing the benefit of this feature because you have never come across a use case in your experience where it really shines.  And this makes sense; the need for dynamic compilation is probably a niche feature, but having it does provide for some powerful applications that would be much more difficult without it.

Here are a couple examples off the top of my head where dynamic compilation would be quite useful.  There are other ways to accomplish all of these things, but Roslyn makes them easier.

Having plugin files that are loaded at runtime, compiled, and included in the execution of the "parent" application.

Creating a DSL which is then translated to C# at runtime and compiled using Roslyn.

Creating an programmer-oriented application which takes C#, analyzes it, translates it, etc.

Comparing two chunks of code for their differences after compilation, as opposed to just "surface" differences such as whitespace.  This is known as Semantic Diff.

So, to sum up, you may never find a use for Roslyn, depending on what software you spend your time writing.  However, there are plenty of use cases where Roslyn brings a lot to the table.  None of the tools you mention provide this feature. Nor could they based on their architecture and purpose.

ContentLicense: CC BY-SA 3.0


问:
In general, is it ethical to make a copy of work source code and take it home as reference?
Is it ethical to make a copy of my work's source code, for the sole purpose of my own reference? By reference, I mean as reference where I can refer to it about how I (and my teammates) implemented various design patterns, architecture, etc. It does not contain any trade secret, product, secret algorithm or anything like that.

Note that I wrote many parts of the source code, and also the added value from me studying the code will also indirectly benefit the company I am working on.

答: If you want to take code home but you don't tell at work and have to do it secretly it's unethical.</p>


问:
What document should describe usage of a third party library in a project?
A customer of my employer has recently requested new features for some legacy code, and since the authors of the program are no longer here, I've been assigned to implement the new features.

I've been provided with some high-level documents that are mostly from early stages of the project: the project definition, black-box testing procedures, research analysis of the initial phase of the project, and so on - nothing at a technical level.

The code makes extensive use of a third party library (Lemur Indri) for indexing and retrieval of indexed materials, but there's no documentation of how we use this library, or why it was chosen. I've spent a lot of time just learning about the library itself and how we use it; I feel like this is wasted time.

During a meeting with my supervisor I mentioned that it would have been nice if the developers of our system had written some documentation about the library and how we use it. I told him that it would have saved a lot of time for me, but I couldn't convince him that this type of thing is essential.

I think writing such documentation helps future developers to get a grip on the system and perform modification faster. If there should be such document, what would it be called, or should it be included in one of the design documents?

答:
All code should include the documentation/comments necessary to make it clear.

That includes documenting how and why a library was used. One need not repeat the documentation for the library, but if understanding the code's use of the library is not possible without hours of scouring documentation, then you absolutely should include some information on how it is being used.

The place for this is the core documentation for the code; it shouldn't be separated out simply because it is about a library.


答:
I think keeping a code example reference library from job to job is a good idea. It should be better than Google. I would encourage it if I was a boss.

tell your collegues about it and especially your boss

don't hide it, but you don't have to have it open on the net either.

ask about anything proprietary

exclude sensitive data and project names

Instead of having very broad design examples, I normally have a few lines of code or blocks to reference. A Factory Pattern example maybe but how much code is it going to take to show how to do BDD? There shouldn't be a complete application here.

Title: In general, is it ethical to make a copy of work source code and take it home as reference?

Body:
Is it ethical to make a copy of my work's source code, for the sole purpose of my own reference? By reference, I mean as reference where I can refer to it about how I (and my teammates) implemented various design patterns, architecture, etc. It does not contain any trade secret, product, secret algorithm or anything like that.

Note that I wrote many parts of the source code, and also the added value from me studying the code will also indirectly benefit the company I am working on.


答:
The proper place for this type of documentation is in the code itself. On a side note, documentation is notoriously inaccurate so your best bet, as a developer, is the create the most clear and concise code you can.

Ideally, the 3rd party library is isolated to a single Class or Module so it can be easily understood and documented. If the library seeps into the domain there may also be some coupling concerns that you need to worry about.

Title: What document should describe usage of a third party library in a project?

Body:
A customer of my employer has recently requested new features for some legacy code, and since the authors of the program are no longer here, I've been assigned to implement the new features.

I've been provided with some high-level documents that are mostly from early stages of the project: the project definition, black-box testing procedures, research analysis of the initial phase of the project, and so on - nothing at a technical level.

The code makes extensive use of a third party library (Lemur Indri) for indexing and retrieval of indexed materials, but there's no documentation of how we use this library, or why it was chosen. I've spent a lot of time just learning about the library itself and how we use it; I feel like this is wasted time.

During a meeting with my supervisor I mentioned that it would have been nice if the developers of our system had written some documentation about the library and how we use it. I told him that it would have saved a lot of time for me, but I couldn't convince him that this type of thing is essential.

I think writing such documentation helps future developers to get a grip on the system and perform modification faster. If there should be such document, what would it be called, or should it be included in one of the design documents?


答:
I'm sure companies which provide tooling (e.g., JetBrains*) are very interested in Roslyn.  Microsoft wants to make it easy to make tooling, because good tooling encourages the use of Microsoft's ecosystem.

*Per the JetBrains blog (this entry), JetBrians has announced that they will not be using Roslyn.  However, I imagine that any new competitors to JetBrains (who don't have a pre-existing codebase to work from) will use Roslyn; it gives them a head start.

Question 6 in 10 Questions, 10 Answers on Roslyn:

6: What are some of the practical uses for Roslyn? How will it help me
  as a developer?

One of the first uses of Roslyn that comes to mind is that of a
  business rules engine. Prior to Roslyn, evaluating user macros
  typically involved implementing Visual Basic for Applications (VBA),
  calling out to the DLR with Ruby expressions, or shelling out to the
  command-line compiler with dynamically generated Visual Basic or C#
  code and obtaining the result of running that code. These methods were
  less than ideal.

Roslyn will easily allow dynamic compilation and execution of C# and
  (eventually) Visual Basic code with the Evaluate() function, as
  demonstrated Eric Vogel's article "Using The Roslyn Scripting API in
  C#". User macros written in the same language as the application will
  make it easier for developers to support user macros representing
  business rules.

Code refactoring becomes much easier with Roslyn. Prior to Roslyn, the
  developers of such tools as DevExpress CodeRush and Refactor Pro and
  JetBrains ReSharper had to recreate much of the compiler operations as
  a foundation for their products. With Roslyn, refactoring developers
  can directly take advantage of the existing compiler capabilities. I
  can imagine the appearance of NuGet packages to install individual
  refactoring rules once Roslyn is widely available.

Title: Why would anyone invest time in Microsoft "Roslyn"?

Body:
I have just been reading through some of the white papers & examples from Microsoft "Roslyn" and the concept seems very interesting.  From what I can tell, it opens up the black box that is the compiler and provides an interface that we can use to get information and metrics about code written in Visual Studio.

Roslyn also appears to have the ability to "script" code and compile/execute it on the fly (similar to the CodeDom) but I have only come across limited uses for that type of functionality in my experience.

Whilst the code analysis & metrics element is an interesting space...it is something that has been around for a very long time and there are numerous providers that have already invested a lot of money into code analysis & refactoring tools (e.g. ReSharper, CodeRush, nCover, etc) and they do a pretty good job of it!

Why would any company go out of their way to implement something that can be provided at a fraction of a cost through buying a license for one of the existing tools?

Maybe I have missed some key functionality of the Roslyn project that places it outside the domain of the mentioned tools...


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
Yes.  I have no doubt.

But that's not necessarily any easier than going outside the MS shop.  Since .NET started, we've had to keep learning.  New languages are riding the framework.  New technologies (LINQ, Silverlight, WF, etc) will continue to modify the technology.  VB and C# are growing together but also just growing.

Does "knowing .NET" include SQL Server?  It depends on your job, but yeah -- you should consider that it does.  Does "knowing SQL Server" include knowing both DTS and SSIS?  Yeah, today it does.

In fifteen years will there still be a bazillion well-paying jobs for people who know these things and have kept up with however the technology morphs?  I have no doubt.

ContentLicense: CC BY-SA 2.5


问:
Checking for minimum number of command-line arguments, but allowing help switch
I just ran into an odd scenario. I’m sure that I must have run into the same situation in the past and yet somehow not noticed it until now.

I am writing a program that requires at least two command-line arguments. Dealing with this is simple enough, just check that there are sufficient arguments. For example:

```<code>A:  if (argc < 3) PrintHelpAndQuit();
</code>```

However, I also want to allow the user to specifically request the help-screen(s) using a single command-line argument. For example:

```<code>B:  if (args[1] == "/?")  PrintHelpAndQuit();
C:  if (args[1] == "/?1") PrintHelp1AndQuit();
D:  if (args[1] == "/?2") PrintHelp2AndQuit();
</code>```

The problem is that if I put line A first, it ensures that at least two arguments were specified, which prevents then lines B, C, and D from being called, and so the user cannot access those screens.

If I put line A after the others, then the program will crash if no arguments are specified (accessing the first member of the argument array is undefined).

There seems to be (only?) two ways to approach this:

Put the help-screen lines in a conditional block that checks that there is at least one argument (which duplicates the work of line A):

```<code>if (argc > 1) {
  if (args[1] == "/?...
}

if (argc < 3) PrintHelpAndQuit();
</code>```

Put an extra line at the top that checks if there are no arguments and prints help and quits if so:

```<code>if (argc < 2) PrintHelpAndQuit(); // now almost entirely duplicates line A
if (args[1] == "/?...
if (argc < 3) PrintHelpAndQuit();
</code>```

Both of these approaches are redundant to varying degrees.

How do others deal with this situation? Is there a more elegant (and less redundant) way to require a minimum number of arguments without precluding a single argument?

答:
Logically, the problem as defined requires a check that there is at least one argument for the help case, as well as a check that there are at least two arguments for the normal use case.

Think about what you have to say to describe the program's behavior:

[The program] requires at least two command-line arguments...

Then

I also want to allow the user to specifically request the help-screen(s) using a single command-line argument.

Even to describe the behavior in words, you need two different requirements about the number of arguments.  It is no surprise that the code similarly needs two requirements.  Having two checks is not redundant, because it is the minimum amount needed to logically test for the valid options.


答:
Command line utilities, in my experience, tend to be universally ugly when it comes to being flexible when parsing args, especially when you have a command that can take an arbitrary number of arguments. There will almost always be some level of duplication or cross-checking, because at its heart the tool is likely short, which means it's probably a single file, which means it's likely procedural.

The first step to any command-line tool is parsing the arguments. This is basically the equivalent of setting up the initial state of the state machine represented by the rest of your script.

Here, have some pseudocode:

```<code>if args.length is 0 or (args.length is 1 and args[0] is '--help')
    do_help_message_thing();
elseif args.length is 1
    do_invalid_usage_thing();
</code>```

I would not worry too much about the code in your tool. You're writing the tool to encapsulate a bit of unenjoyable misery so that everyone who uses the tool in the future can take a shortcut. As long as the script is not buggy, relatively fast, and doesn't have the potential to hose a system, people will love you for it (in my experience, at least).

Title: Checking for minimum number of command-line arguments, but allowing help switch

Body:
I just ran into an odd scenario. I’m sure that I must have run into the same situation in the past and yet somehow not noticed it until now.

I am writing a program that requires at least two command-line arguments. Dealing with this is simple enough, just check that there are sufficient arguments. For example:

```<code>A:  if (argc < 3) PrintHelpAndQuit();
</code>```

However, I also want to allow the user to specifically request the help-screen(s) using a single command-line argument. For example:

```<code>B:  if (args[1] == "/?")  PrintHelpAndQuit();
C:  if (args[1] == "/?1") PrintHelp1AndQuit();
D:  if (args[1] == "/?2") PrintHelp2AndQuit();
</code>```

The problem is that if I put line A first, it ensures that at least two arguments were specified, which prevents then lines B, C, and D from being called, and so the user cannot access those screens.

If I put line A after the others, then the program will crash if no arguments are specified (accessing the first member of the argument array is undefined).

There seems to be (only?) two ways to approach this:

Put the help-screen lines in a conditional block that checks that there is at least one argument (which duplicates the work of line A):

```<code>if (argc > 1) {
  if (args[1] == "/?...
}

if (argc < 3) PrintHelpAndQuit();
</code>```

Put an extra line at the top that checks if there are no arguments and prints help and quits if so:

```<code>if (argc < 2) PrintHelpAndQuit(); // now almost entirely duplicates line A
if (args[1] == "/?...
if (argc < 3) PrintHelpAndQuit();
</code>```

Both of these approaches are redundant to varying degrees.

How do others deal with this situation? Is there a more elegant (and less redundant) way to require a minimum number of arguments without precluding a single argument?

Body:
Command line utilities, in my experience, tend to be universally ugly when it comes to being flexible when parsing args, especially when you have a command that can take an arbitrary number of arguments. There will almost always be some level of duplication or cross-checking, because at its heart the tool is likely short, which means it's probably a single file, which means it's likely procedural.

The first step to any command-line tool is parsing the arguments. This is basically the equivalent of setting up the initial state of the state machine represented by the rest of your script.

Here, have some pseudocode:

if args.length is 0 or (args.length is 1 and args[0] is '--help')
    do_help_message_thing();
elseif args.length is 1
    do_invalid_usage_thing();

I would not worry too much about the code in your tool. You're writing the tool to encapsulate a bit of unenjoyable misery so that everyone who uses the tool in the future can take a shortcut. As long as the script is not buggy, relatively fast, and doesn't have the potential to hose a system, people will love you for it (in my experience, at least).


答:
In *nix tools it is common to require that all options/flags are positioned before mandatory arguments. With that requirement and the fact that you just discard the rest of the arguments if you start a help function you can do the following:

```<code>switch args[1]:
    case "/?") PrintHelpAndQuit();
    case "/?1") PrintHelp1AndQuit();
    case "/?2") PrintHelp2AndQuit();
</code>```

Once you get past the switch statement you know that any following arguments are the (at least two) necessary arguments, and you can check argc < 3.

Body:
In *nix tools it is common to require that all options/flags are positioned before mandatory arguments. With that requirement and the fact that you just discard the rest of the arguments if you start a help function you can do the following:

switch args[1]:
    case "/?") PrintHelpAndQuit();
    case "/?1") PrintHelp1AndQuit();
    case "/?2") PrintHelp2AndQuit();

Once you get past the switch statement you know that any following arguments are the (at least two) necessary arguments, and you can check argc < 3.


答:
Don't work with argument counts. Place the arguments into a queue and process the queue. This is a lot easier to work with.

```<code>Queue q = new Queue();
for(int i=0; i < argc; i++)
{
    q.push(args[i]);
}
</code>```

Once their in the queue you can then process the arguments via a simple dispatch method. What you should do is follow a consistent pattern for the platform. On Windows arguments are prefixed with a forward slash, and arguments without a slash are parameters for the previous argument. On Linux it's a double dash.

Let's assume we have a few usages like this

```<code>tool.exe /mode on /prompt off
tooo.exe /? /mode on
</code>```

The first would set some options, and the second would display help for an option. Since you have the arguments in a queue you can process it like this.

```<code>while(!q.empty())
{
    String arg = q.pop();
    // is it an option
    if(arg.startsWith("/"))
    {
        switch(arg)
        {
            case "/mode":
               setMode(q.pop());
               break;
            case "/prompt":
               setPrompt(q.pop());
               break;
            case "/help":
               showHelp(q.pop(),q.pop());
               exit();
               break;
        }
    }
    else
    {
       exit("Unexpected argument");
    }
}

// run the program, all options are set
</code>```

Now I didn't do any checks on the queue missing arguments, but you could do your own queue where pop() accepted a default value.

With a queue the order of arguments doesn't break anything.

```<code>tool.exe /mode on /prompt off
tool.exe /prompt off /mode on
tooo.exe /prompt on /? /mode on
</code>```

All the above are valid.

Body:
Don't work with argument counts. Place the arguments into a queue and process the queue. This is a lot easier to work with.

Queue q = new Queue();
for(int i=0; i < argc; i++)
{
    q.push(args[i]);
}

Once their in the queue you can then process the arguments via a simple dispatch method. What you should do is follow a consistent pattern for the platform. On Windows arguments are prefixed with a forward slash, and arguments without a slash are parameters for the previous argument. On Linux it's a double dash.

Let's assume we have a few usages like this

tool.exe /mode on /prompt off
tooo.exe /? /mode on

The first would set some options, and the second would display help for an option. Since you have the arguments in a queue you can process it like this.

while(!q.empty())
{
    String arg = q.pop();
    // is it an option
    if(arg.startsWith("/"))
    {
        switch(arg)
        {
            case "/mode":
               setMode(q.pop());
               break;
            case "/prompt":
               setPrompt(q.pop());
               break;
            case "/help":
               showHelp(q.pop(),q.pop());
               exit();
               break;
        }
    }
    else
    {
       exit("Unexpected argument");
    }
}

// run the program, all options are set

Now I didn't do any checks on the queue missing arguments, but you could do your own queue where pop() accepted a default value.

With a queue the order of arguments doesn't break anything.

tool.exe /mode on /prompt off
tool.exe /prompt off /mode on
tooo.exe /prompt on /? /mode on

All the above are valid.


问:
Should I fully parenthesize expressions or rely on precedence rules?
Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedence than OR. I could write this line of code:

```<code>If (a AND b) OR (c AND d) Then ...
</code>```

But really, that's equivalent to:

```<code>If a AND b OR c AND d Then ...
</code>```

Are there compelling arguments in favor or against including the extraneous parentheses?

Does practical experience suggest that including them significantly improves readability?

Or is wanting them a sign that a developer really needs to sit down and become conversant in the  basics of their language?

答:
Yes, if there are mixed 'and' and 'or'.

Also good idea to () what is logically one check.

Though best is to use well-named predicate functions and evict most checks and conditions there, leaving if simple and readable.

ContentLicense: CC BY-SA 4.0


问:
Loading chunks around center
I am making a voxel game like Minecraft. I am able to load chunks using multithreading with the code...

```<code>for (int x = 0; x < WorldSettings.WORLD_WIDTH_IN_CHUNKS; x++)
{
    for (int y = 0; y < WorldSettings.WORLD_LENGTH_IN_CHUNKS; y++)
    {
        chunks[x, y].BulidVertexData();
        Thread.Sleep(50);
    }
}
</code>```

this works fine, it starts by loading the far away chunk  and loads them back and forth like a windshield wiper that gets closer, but I would rather have it load in a circle around the player by loading the near chunks first. Any ideas?

答:
An obvious point of reference would be Minecraft itself.

Minecraft maps are effectively stored as a three dimensional array within the map file.

Chunks from the map are loaded based upon the player's coordinates and movement.  Chunks closest to the player are loaded first and then the more distant chunks are loaded.  Essentially, it's a spiral out algorithm centered around the player's coordinates.

At some point away from the player, the loader stops loading up chunks for display as they are beyond the resolution of the frame.

You can add additional smarts to limit loading based upon opacity of the blocks and / or based upon which direction the player is viewing.  I would check your performance times first before implementing those changes as they could be unnecessary micro-optimizations.

Title: Loading chunks around center


答:
As I see it:

YES Pros:

Order of operations is explicit.

Protects you from future developers who don't understand order of operations.

YES Cons:

May result in cluttered, difficult to read code

NO Pros:

?

NO Cons:

Order of operations is implicit

Code is less maintainable for developers without a good understanding of order of operations.

Title: Should I fully parenthesize expressions or rely on precedence rules?

Body:
Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedence than OR. I could write this line of code:

```<code>If (a AND b) OR (c AND d) Then ...
</code>```

But really, that's equivalent to:

```<code>If a AND b OR c AND d Then ...
</code>```

Are there compelling arguments in favor or against including the extraneous parentheses?

Does practical experience suggest that including them significantly improves readability?

Or is wanting them a sign that a developer really needs to sit down and become conversant in the  basics of their language?


答:
It matters less whether you are confident in your grasp of the language.  What matters more is the grasp of the language of the n00b that follows you.

Write your code in the clearest most unambiguous way possible.  Extra parenthesis often (but not always) help.  Putting only one statement on a line often helps.  Consistency in coding style often helps.

There is such a thing as too many parenthesis, but it's one of those situations where you won't need advice - you'll know it when you see it.  At that point refactor your code to reduce the complexity of the statement rather than remove parenthesis.


答:
Good developers strive to write code that is clear and correct.  Parentheses in conditionals, even if they are not strictly required, help with both.

As for clarity, think of parentheses like comments in code: they aren't strictly necessary, and in theory a competent developer should be able to figure out code without them.  And yet, these cues are exceedingly helpful, because:

They reduce the work required to understand the code.

They provide confirmation of the developer's intent.

Furthermore, extra parentheses, just like indentations, whitespace, and other style standards, help visually organize the code in a logical way.

As for correctness, conditions without parentheses are a recipe for silly mistakes.  When they happen, they can be bugs that are hard to find--because often an incorrect condition will behave correctly most of the time, and only occasionally fail.

And even if you get it right, the next person to work on your code may not, either adding errors to the expression or misunderstanding your logic and thus adding errors elsewhere (as LarsH rightly points out).

I always use parentheses for expressions that combine and and or (and also for arithmetic operations with similar precedence issues).


问:
Keeping track of all objects of a class
I'm new to object-oriented programming, and I keep running into this issue. (I'm programming in Java) I've been a bit reluctant to ask about this, since it seems like such a basic issue, but I can't find any information on it, or questions about it here, and none of the textbooks I have read (on a quite basic level of course) have touched on this issue:

Often I need to keep track of all objects of a class that have been created, to iterate through them for various purposes. They way I currently write programs, many objects are only referenced from other objects, meaning I have no array or collection with which to reference them all.

I imagine that, as this seems like such a very basic necessity in OOP, there should be a quite institutionalized, and simple, way to go about this? Is it usual practice to keep a separate list of all the objects of a class?

I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited?

I realize this question might not have one easy answer; I just hope someone can enlighten me a bit on this subject. I feel like if I'm lacking a central piece of knowledge here.

答:
It should be noted that weak references can be used in combination with the other given solutions to allow the garbage collector to dispose of tracked objects when they are no longer referenced elsewhere. This eliminates memory leaks without requiring code elsewhere to manually dispose of objects, or otherwise care that they are being tracked. You can provide a ReferenceQueue to receive notification of references to objects that have been freed.

I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited?

The constructors of base classes are invoked before constructors of derived classes. Every class has at least one constructor and constructors cannot be overridden.

Title: Keeping track of all objects of a class


问:
What's the best way to manage error logging for exceptions?
Introduction

If an error occurs on a website or system, it is of course useful to log it, and show the user a polite message with a reference code for the error.

And if you have lots of systems, you don't want this information dotted around - it is good to have a single centralised place for it.

At the simplest level, all that's needed is an incrementing id and a serialized dump of the error details. (And possibly the "centralised place" being an email inbox.)

At the other end of the spectrum is perhaps a fully normalised database that also allows you to press a button and see a graph of errors per day, or identifying what the most common type of error on system X is, whether server A has more database connection errors than server B, and so on.

What I'm referring to here is logging code-level errors/exceptions by a remote system - not "human-based" issue tracking, such as done with Jira,Trac,etc.

Questions

I'm looking for thoughts from developers who have used this type of system, specifically with regards to:

What are essential features you couldn't do without?

What are good to have features that really save you time?

What features might seem a good idea, but aren't actually that useful?

For example, I'd say a "show duplicates" function that identifies multiple occurrence of an error (without worrying about 'unimportant' details that might differ) is pretty essential.

A button to "create an issue in [Jira/etc] for this error" sounds like a good time-saver.

Just to re-iterate, what I'm after is practical experiences from people that have used such systems, preferably backed-up with why a feature is awesome/terrible.

(If you're going to theorise anyway, at the very least mark your answer as such.)

答:
In the case of database applications, some kind of ID (like
:<PrimaryKeyID>) that allows you to track the records in the database related to the scope where the exception was catched.

I've done it with Oracle and PL/SQL, recording the ID in a database table within the aplication, from the exception handler.

Body:
In the case of database applications, some kind of ID (like <TABLE>:<PrimaryKeyID>) that allows you to track the records in the database related to the scope where the exception was catched.

I've done it with Oracle and PL/SQL, recording the ID in a database table within the aplication, from the exception handler.


问:
Please explain object versioning in the nodejs module system
This question is about the persistance of variables across different modules in nodejs when they don't directly "require" each other, but do "require" a common ancestor.

It is also the generalised version of this stackoverflow question. Whilst I received an answer there that helped me solve my specific case, I'm still unclear as to the answer to the architectural problem I posed. I hoped that the general problem was a good fit for a programmers.stackexchange question.

Assume we have a nodejs program structured like so:

Module Alpha - exports variable a.

Module Beta - requires module Alpha, reads variable a -> prints it to console periodically

Module Gamma - requires module Alpha, periodically writes to variable a

Is the instance of module Alpha, and thus variable a, common across all three modules. e.g. can module Gamma make changes to variable a that are successfully printed to the console by module Beta.

If this is true, why is this true even though there is no direct "requires" relationship between modules Gamma and Beta?

If this is not true, can you explain the best way to share a variable than needs to be modified at runtime between multiple node modules?

Can you explain the underlaying data model which is causing this behaviour in nodejs modules?

答:
Data sharing between modules depends on how and what modules exports. It's important to keep in mind that require() caches and returns the exports variable. For instance:

```<code>// alpha.js
module.exports.a = 5; // returns 'exports' which is an empty object
                      // with "a" as a property. node caches this object

// gamma.js
var alpha = require("alpha");
alpha.a = 666;  // alpha is a reference to the exports object

// beta.js
var alpha = require("alpha");
console.log(alpha.a); // prints 666
</code>```

Updating it (alpha.a = 666) should work. This means that beta.js should indeed get the latest value each time.

But if you do:

```<code>// alpha.js
module.exports = 5; // returns it as an integer which is cached by node.

// gamma.js
var alpha = require("alpha");
alpha = 666; // overwrites the local copy, but nothing else happens

// beta.js
var alpha = require("alpha");
console.log(alpha); // still prints 5
</code>```

By the way, doing:

```<code>// alpha.js
exports = 5;
</code>```

fails because that code is (conceptually) like this:

```<code>// alpha.js
module.exports = {};
var exports = module.exports;
exports = 5;
return module.exports; // returns {}, not 5
</code>```

Body:
Data sharing between modules depends on how and what modules exports. It's important to keep in mind that require() caches and returns the exports variable. For instance:

// alpha.js
module.exports.a = 5; // returns 'exports' which is an empty object
                      // with "a" as a property. node caches this object

// gamma.js
var alpha = require("alpha");
alpha.a = 666;  // alpha is a reference to the exports object

// beta.js
var alpha = require("alpha");
console.log(alpha.a); // prints 666

Updating it (alpha.a = 666) should work. This means that beta.js should indeed get the latest value each time.

But if you do:

// alpha.js
module.exports = 5; // returns it as an integer which is cached by node.

// gamma.js
var alpha = require("alpha");
alpha = 666; // overwrites the local copy, but nothing else happens

// beta.js
var alpha = require("alpha");
console.log(alpha); // still prints 5

By the way, doing:

// alpha.js
exports = 5;

fails because that code is (conceptually) like this:

// alpha.js
module.exports = {};
var exports = module.exports;
exports = 5;
return module.exports; // returns {}, not 5


问:
Where should the processing to structured XML be done?
I have been given the task of redeveloping an "in house" solution to make it expandable and easier to maintain and administer.

The original solution had been hashed together over time using PHP as more requirements were added, and the need to expand is expected into the foreseeable future.

The solution, gathers many different files such as word documents and varying structures of XML document, from different "locations" and converts each into a specifically structured XML documents which get sent on via a web service.
To add to the mix, some of the original XML files are retrieved from the same "location" but have varying levels of processing that are required depending on where they are from before that (identified by a "customer" field in the XML)

My intention is to make the new solution as modular as possible so that processing can be suspended at the individual "customer" or "location" level without affecting anything else.

While I have many puzzles to overcome and questions to answer, the question that is keeping me up at night at the moment is "Where should the processing to the structured XML be done?"
At present it is done per "customer" but as you can imagine, it leads to a lot of duplicated code. Maybe it is unavoidable, due to the "customer" specific processing required sometimes but sanity tells me there must be a better way.

答: You mention that all of this XML goes to a common web service, so one option would be to have the processing happen there. Of course, this would require changes to your web service as it would have to accept the new XML structures, but since it's going to transform and process it immediately, that might not be a problem.


问:
sizeof style: sizeof(type) or sizeof variable?
I've seen two styles of using sizeof for memory-related operations (such as in memset or malloc):

sizeof(type), and

sizeof variable or sizeof(variable)

Which one would you prefer, or would you use a mix of the two styles, and when would you use each style? What are the pros and cons of each style and when you use them?

As an example, I can see the following pair of situations where one style helps and the other doesn't:

When you get the pointer indirection wrong:

```<code>type *var;
...
memset(var, 0, sizeof var);    /* oops */
</code>```

When the type changes:

```<code>new_type var;    /* changed from old_type to new_type */
...
memset(&var, 0, sizeof(old_type));    /* oops */
</code>```

答:
The preference (as always) is to reflect your intention as directly as possible.

Is the intention to operate against an existing variable's memory? If so, then use sizeof(variable), as this shows as closely as possible that it's the variable itself's memory that you care about.

Is the intention to perform some calculation on the type, for example to determine how much memory should be allocated for a new instance? If so, then use sizeof(type).

That is, I prefer

```<code>struct foo *bar;
bar = (struct foo *) malloc(sizeof(struct foo));
</code>```

over

```<code>bar = (struct foo *) malloc(sizeof(*bar));
</code>```

as the latter case looks like you're trying to access a variable that doesn't exist, yet.

On the other hand, I prefer

```<code>char Buffer[256];
memset(Buffer, 0, sizeof(Buffer));
</code>```

over

```<code>char Buffer[256];
memset(Buffer, 0, 256 * sizeof(char));
</code>```

as the intention is clearly to zero-fill the contents of the variable, so it's the variable we should operate against. Trying to use the type metadata just confuses things, here.

Body:
The preference (as always) is to reflect your intention as directly as possible.

Is the intention to operate against an existing variable's memory? If so, then use sizeof(variable), as this shows as closely as possible that it's the variable itself's memory that you care about.

Is the intention to perform some calculation on the type, for example to determine how much memory should be allocated for a new instance? If so, then use sizeof(type).

That is, I prefer

struct foo *bar;
bar = (struct foo *) malloc(sizeof(struct foo));

over

bar = (struct foo *) malloc(sizeof(*bar));

as the latter case looks like you're trying to access a variable that doesn't exist, yet.

On the other hand, I prefer

char Buffer[256];
memset(Buffer, 0, sizeof(Buffer));

over

char Buffer[256];
memset(Buffer, 0, 256 * sizeof(char));

as the intention is clearly to zero-fill the contents of the variable, so it's the variable we should operate against. Trying to use the type metadata just confuses things, here.


答:
My advice would be to invest in learning XSLT (I found a decent tutorial from the perspective of a PHP programmer here).  While it's true you could probably accomplish the same thing using only PHP, it could get quite messy.

To describe XSLT briefly, in XSLT you define a list of rules which are activated according to the specificity of the XPath used to describe which nodes are affected (very specific nodes described by the xpath have higher priority over more generic rules).  It allows you to transform XML into anything, including XML which, you guessed it, means you can perform separate operations if you wish.  You can also define rules which activate only when certain nodes are available so for example, if you wanted to apply transform using the customer or location, you simply wouldn't provide information pertaining to anything else, and the corresponding rule does not activate.

If you wanted to move the logic to the web service, XSLT is supported in virtually any language that supports XML itself.  In any case, this should offer a clean solution that allows you to use a proper technology for handling these types of situations.

Title: Where should the processing to structured XML be done?

Body:
I have been given the task of redeveloping an "in house" solution to make it expandable and easier to maintain and administer.

The original solution had been hashed together over time using PHP as more requirements were added, and the need to expand is expected into the foreseeable future.

The solution, gathers many different files such as word documents and varying structures of XML document, from different "locations" and converts each into a specifically structured XML documents which get sent on via a web service.
To add to the mix, some of the original XML files are retrieved from the same "location" but have varying levels of processing that are required depending on where they are from before that (identified by a "customer" field in the XML)

My intention is to make the new solution as modular as possible so that processing can be suspended at the individual "customer" or "location" level without affecting anything else.

While I have many puzzles to overcome and questions to answer, the question that is keeping me up at night at the moment is "Where should the processing to the structured XML be done?"
At present it is done per "customer" but as you can imagine, it leads to a lot of duplicated code. Maybe it is unavoidable, due to the "customer" specific processing required sometimes but sanity tells me there must be a better way.


问:
What are non-programming mistakes that a programmer should avoid?
People make mistakes, even in the real life... Which should we, geeky programmers, avoid?</p>

答: Learn to estimate.</p>

Body: Learn to estimate.


问:
What source control do I need for a large project in an average company?
I know Git is great for open source projects. But I was wondering: for a company with 20 programmers working on a 1 year project, which source control system is desirable? From what I heard Git uses pulling; wouldn't it be less than desirable to need to go through someone else to get your changes in the main trunk? Especially when everyone is working at the same time?

That's just of an example I was wondering about. I know how to use SVN but even at my last job we didn't use it on our projects, since everything was done in PHP and those were typically standalone 1 week projects. I just had SVN for my local code and didn't need to use it with others.

So what are good source controls, and specifically why is it good for this?

答: Mercurial is excellent, distributed, and free.</p>


问:
Is the future of the web application going the same as the desktop application?
I've noticed an increase in mobile applications being released that offer high value features, but without any corresponding web based version.

Was just reading about a new medical app for iPhone that allows doctors to share medical images, and had this idea been done 5 years ago it surely would have been a web application. Now it's released purely on iPhone without any web alternative.

It's been years since I've had a client request a desktop application, and everything has been web based, but today all future projects involve some kind mobile solution.

How much longer should I recommend clients to continue investing in web based applications?

答:
The web offers a lot of pros. It is easier to make a multi-platform web application then a MP desktop application.

The problem with the web is that you are constrained by the browser's boundaries. For example, you don't have access to the file system.

If you really need access to the file system in a web application, you can use java or flash bu they are quite undesirable in a website since they are proprietary plugins that may not work on all platforms.

The web application won't be able to entirely replace a good old desktop app for a long time since the web is growing really really slowly.


问:
Implementing Digitally signed data in a Web Application
I understand PKI well from a conceptual point of view - i.e. private keys/public keys - the math behind them, use of hash & encryption to sign a certificate, Digital Signing of Transactions or Documents etc. I have also worked on projects where openssl C libraries were used with certs for securing communication and authentication. I am also extremely familiar with openssl command line tools.

However, I have very little experience with webbased PKI projects & hence I am trying to design and code a personal project for this.

The requirements

(This is a learning project - This is never going to be used in a bank)

This is the website for a bank. All Internet Banking users are allowed use any signing certificate issued by a few known CAs (verisign, Thawte, entrust etc). The Bank is not responsible for procuring certificates for the user. The user logs into the bank site with his userid/password etc. He has access to most parts of his account. However, when the user wants to do a transaction - like transferring money to different account - the bank wants him to sign the transaction with a certificate.

The design

When user choses "Transfer" option - the website throws up a form where there are 3 entries - "Transfer To" account, the Amount of the transaction and a way for chosing a cert for doing the digital signing & do the signing.

I concatenate the "Transfer To" Account no & the amount plus a nonce and this is the string which will be signed and sent to the backend.

I have searched a lot but haven't been able to figure out how to achieve
- letting the user chose a cert
- do the signing.

I know how the user can add certs to his personal truststore on Windows. But how would I ask the browser to show him certs to chose from?

How does the signing get done - I really don't want to write crypto code in Javascript!!! So is the alternative having an ActiveX or a Java Applet? Is there a better way? Is there a way to ask the browser to use the cert and do the signing?

I have not decided on a platform/framework/language for now - so this question is rather generic.

I have searched a lot for this kind of info without luck - all I get is tutorials on digital signing, tutorials on how to enable PKI in Apache etc.

If someone feels my whole approach is wrong & there is a better way to do digital signing in a web-app - feel free to suggest those alternatives also.

答:
I could be wrong about this, but as far as I know without resorting to implementing crypto in JavaScript or using some manner of plugin you cannot do exactly what you are attempting.

There is something close that is unpopular, but fairly well supported: Client Side Certificates

The general idea is that the client has a certificate in their keychain and that certificate is examined when they request a secured resource as part of the authorization sequence.  After that point the communication proceeds over normal everyday SSL.

In your case if you were to have a web service that was behind SSL and a form that posts the transfer, transferTo and nonce  and the service was configured appropriately to request client certificates the service would respond to the initial request with a request for credentials and the distinguished names of issuers it will accept.  If the browser has more than one client certificate from that list it should prompt the user to select.

The rest of the conversation is just handled like any other SSL as I understand it, but you should then have access to the client certificate as part of the request object from the server end of things.

This is not exactly what you were asking for, but to my knowledge this is the closest you can get without doing something non-standard.  The communication is secure because of the SSL, the user has proven they have a copy of the certificate and on the server end you can use the certificate to check that the user matches who they claim to be as an additional authentication factor.  The message is not literally signed with the key, but the SSL communication channel the message traveled over was verified with the client key.

A stack overflow that discusses this further (see first answer & links):

https://stackoverflow.com/questions/1193013/ssl-client-cert-verification-optimisation

Examples of how you might set it up if you are in Microsoft land:

http://woloski.com/2012/08/04/securing-aspnet-webapi-with-clientcerts/

http://support.microsoft.com/kb/315588 (older versions)


问:
Looking for a popular, well known example of closed-source software which uses LGPL code, and says so
For advocacy purposes, I'm looking for a good example of some popular/widely-known closed-source and generally paid-for software application/package which uses dynamically linked LGPL-licensed libraries, and isn't shy of saying so in its installer dialogs or preferably in its "About" info and/or online documentation once the application is installed.

Basically I'm looking for evidence which will back up an argument "If ...big vendor... doesn't have a problem shipping ...hugely popular SW... with an LGPL dependency, neither should you."

(Links to any screenshots or online copies of documentation which demonstrate the usage without me needing to actually acquire the software would be most appreciated).

答: With very few exceptions, you can take your pick of proprietary and closed source applications for Linux or Android.  Glibc is LGPL and is linked with practically everything.  Autodesk, MathWorks, Oracle, IBM, Adobe, Google, Samsung, Amazon, Nvidia, Motorola, and many more companies incorporate and depend on LGPL and even some GPL components in their software and hardware products.</p>


答:
One thing you might do is store your chunks in a quadtree representing subdivisions of the x-y plane, or some similar structure, and then do a radius search to locate the ones near the player that are to be loaded. You could do progressively larger radius searches to draw outwards, or you could do a secondary distance sort on the search results with the full draw distance as your radius to get the draw order.

However... it looks like you're loading your entire world at once? I couldn't say for sure without more context, but it seems like that's going to really limit your world size. Minecraft uses chunks in part so that it can load only a tiny part of the world (around the player) into memory at once, but loading them all at once negates that benefit. There are others, to be sure, but you may want to consider rethinking the load-'em-all-at-once method.

If you used a quadtree (or similar) to store your chunk references (don't load them until you need them, and maybe don't even load the whole tree until you need it!), it would give you the searching benefit described above and also allow you to sparsely populate a massive world with only the chunks explored by the player.

Title: Loading chunks around center

Body:
I am making a voxel game like Minecraft. I am able to load chunks using multithreading with the code...

```<code>for (int x = 0; x < WorldSettings.WORLD_WIDTH_IN_CHUNKS; x++)
{
    for (int y = 0; y < WorldSettings.WORLD_LENGTH_IN_CHUNKS; y++)
    {
        chunks[x, y].BulidVertexData();
        Thread.Sleep(50);
    }
}
</code>```

this works fine, it starts by loading the far away chunk  and loads them back and forth like a windshield wiper that gets closer, but I would rather have it load in a circle around the player by loading the near chunks first. Any ideas?


问:
Are Ruby on Rails / Grails the fastest frameworks for getting sites up quickly?
I'm considering using Grails for a new website, but am open to other/new programming languages and frameworks.  I have done development using J2EE/JSF2, ASP.NET, and PHP.  Is Grails or Ruby on Rails pretty much the best way to get functionality up and running quickly?

Some initial thoughts:

DJango looks similar to RoR/Grails and I'd consider it

GWT is an interesting concept but it doesn't seem like turnaround time is quite as fast

Thanks,
-Jon

答: I've been working with ASP.NET MVC framework for some time now, and I've found it to be a pretty darn good framework. Extremely easy to use, especially if you're familiar with .NET. The framework has been growing quickly since its release in 2009, MVC 3 preview has been released to the public recently. I think MS is doing all the right things with the ASP.NET MVC framework.


问:
Database Facade to wrap our existing queries?
We have a very big application written in C++ using the MFC framework (millions of code lines). No need to say that it's a legacy system, but it's also heavily maintained and updated. This application lacks a lot of architecture. For example, we have a lot of classes that do queries directly to the database, which creates a lot of difficulty for unit testing.

I have read the book Working Effectively With Legacy Code, and one of the most important things to do first is to create some kind of architecture so we can separate the GUI from the logic and from the database.

My idea to go towards this is to create something like a database facade. There will be 2 goals for this:

Encapsulate all the calls to the database behind this facade.

Be able to test the facade in batch to detect errors in the SQL very fast.

The database facade itself will be implementing an IDatabaseXXXX interface so it could be easily mocked in the unit tests. The second goal will be to be able to run all the functions in the facade in batch to test if there are errors in the SQL queries. I don't count them as unit tests and would be running them only once per day.

My main concern about doing this is that I don't know if there is an existing framework or library to take care of this abstraction. As far as I know, there are some on other platforms like .NET, but it seems that for C++ or MFC, there are not a lot of options. Like I said, the application is very big and the change will be done slowly, mostly when new queries are added to the software.

I think it is a good thing to add that we also have a LOT of recordsets (one for almost each object). For the moment, I don't know how to deal with them, so I kept them on the side and decided to deal with the regular SQL queries. But if you have suggestions to deal with recordsets, I will be glad to hear them.

So my main question is: Is this whole idea of database facade worth trying? Is there any library of framework to help me in this adventure? If there are C++/MFC programmers out there, how do you deal with the abstraction of the query to the database?

Thanks!

EDIT

Some people on the chat suggest looking up at repository pattern which I knew from the world of MVC 3. Any suggestion or tutorial about the repository pattern in C++? Most of what I found is in the .NET world.

答:
As your update suggets, the repository pattern would be able to help seperate the database calls from your UI. And replacing the database calls with calls to an IDatabase interface is certainly an improvement. The repository pattern will allow you to further abstract the the data retrieval into something meaningful to the application. UserRepository, ThingRepository, etc.

http://msdn.microsoft.com/en-us/library/ff649690.aspx

As an approach to implementing this architecture. When I need to make code testable to refactor the first test is always the hardest. Find a well understood piece of code that you want to test and make that class/method testable. Once this is in place it is persistence and patience that will allow you to complete the task of introducing the new architecture into the legacy system.


答:
I think the critical piece you're missing is that the result of require("foo") is always the same object. Consider this REPL example:

```<code>> var myHttpModule = require("http")
{ ... }
> myHttpModule.someNewProperty = "someValue"
'someValue'
> require("http").someNewProperty
'someValue'
</code>```

The second call to require("http") did not re-create the http module -- it summoned up the only http module that exists in Node's current execution environment, which had been altered on the previous line.

So, in your example, there's only one Alpha module. When Beta and Gamma call require("alpha"), they're each getting the same reference to the one-and-only Alpha module singleton object.

(Or, to be perfectly precise, they're getting the same reference to the exports value of the Alpha module. require creates a Module object, but returns only the exports property of that module. If you don't fully understand the distinction right now, it's not a big deal.)

Behind the scenes: what's really going on with require caching?

The first time you use require to include a module, Node actually runs the code in that module. The resulting module is stored in require.cache. Subsequent attempts to load the module with require first check for an already-loaded module object in require.cache. (Note: environment-native built-in Node modules like http are exceptions in that they don't use require.cache -- you'll need to test out my code below with a custom module.)

require.cache is an object whose keys are module file path, with associated values that are module objects. For example, assume some module named "foo" in C:\node_modules\foo.js:

```<code>> require.cache                             // empty cache
{ }
> require("foo")                            // require foo
{ bar: 'baz' }
> require.cache                             // cache now populated
{ 'C:\\node_modules\\foo.js':
   { id: 'C: \\node_modules\\foo.js',
     exports: { bar: 'baz' },
     parent: { ... },
     filename: 'C:\\node_modules\\foo.js',
     ...
     paths:
      [ ... ] } }
</code>```

The current value of the foo module is in require.cache["C:\node_modules\foo.js"].exports. We can use require.resolve to get the file path of the module from the name, so we can express it also as require.cache[require.resolve("foo")].exports.

If we call require("foo") a second time, Node sees that require.cache[require.resolve("foo")] is defined, and so it returns the value of require.cache[require.resolve("foo")].exports instead of re-running the module creation code. This exports property of the foo module in require.cache is the single instance of the foo module export value, returned with every subsequent call to require("foo").

One interesting implication here is that you can delete require.cache[require.resolve("foo")] to force a reload of the foo module with the next call to require("foo"), because the object describing the module is removed from the require.cache object.

So what does this mean for me?

Without require, you could still share values between modules using global variables. For example, your Alpha/Beta/Gamma case would work just as well with just Beta and Gamma setting and reading the global value global.a. Instead, with Node's require system, you're actually setting and reading global.require.cache[require.resolve("alpha")].exports.a, which Node lets you read neatly as just require("alpha").a.

In fact, if you just want to share a value and don't need to import your shared data as a module, you could also use a namespacing object, i.e., have Beta and Gamma set and read properties of the object global.alpha. The major advantage to using require is that you don't need to set up require("alpha") external to the other scripts, whereas you would need to define global.alpha = {} before requireing Beta and Gamma. (Alternatively, you could conditionally define global.alpha in each module based on a typeof global.alpha == 'undefined' check instead, to see if it's the first module to use it.)

Title: Please explain object versioning in the nodejs module system

Body:
This question is about the persistance of variables across different modules in nodejs when they don't directly "require" each other, but do "require" a common ancestor.

It is also the generalised version of this stackoverflow question. Whilst I received an answer there that helped me solve my specific case, I'm still unclear as to the answer to the architectural problem I posed. I hoped that the general problem was a good fit for a programmers.stackexchange question.

Assume we have a nodejs program structured like so:

Module Alpha - exports variable a.

Module Beta - requires module Alpha, reads variable a -> prints it to console periodically

Module Gamma - requires module Alpha, periodically writes to variable a

Is the instance of module Alpha, and thus variable a, common across all three modules. e.g. can module Gamma make changes to variable a that are successfully printed to the console by module Beta.

If this is true, why is this true even though there is no direct "requires" relationship between modules Gamma and Beta?

If this is not true, can you explain the best way to share a variable than needs to be modified at runtime between multiple node modules?

Can you explain the underlaying data model which is causing this behaviour in nodejs modules?

Body:
I think the critical piece you're missing is that the result of require("foo") is always the same object. Consider this REPL example:

> var myHttpModule = require("http")
{ ... }
> myHttpModule.someNewProperty = "someValue"
'someValue'
> require("http").someNewProperty
'someValue'

The second call to require("http") did not re-create the http module -- it summoned up the only http module that exists in Node's current execution environment, which had been altered on the previous line.

So, in your example, there's only one Alpha module. When Beta and Gamma call require("alpha"), they're each getting the same reference to the one-and-only Alpha module singleton object.

(Or, to be perfectly precise, they're getting the same reference to the exports value of the Alpha module. require creates a Module object, but returns only the exports property of that module. If you don't fully understand the distinction right now, it's not a big deal.)

Behind the scenes: what's really going on with require caching?

The first time you use require to include a module, Node actually runs the code in that module. The resulting module is stored in require.cache. Subsequent attempts to load the module with require first check for an already-loaded module object in require.cache. (Note: environment-native built-in Node modules like http are exceptions in that they don't use require.cache -- you'll need to test out my code below with a custom module.)

require.cache is an object whose keys are module file path, with associated values that are module objects. For example, assume some module named "foo" in C:\node_modules\foo.js:

> require.cache                             // empty cache
{ }
> require("foo")                            // require foo
{ bar: 'baz' }
> require.cache                             // cache now populated
{ 'C:\\node_modules\\foo.js':
   { id: 'C: \\node_modules\\foo.js',
     exports: { bar: 'baz' },
     parent: { ... },
     filename: 'C:\\node_modules\\foo.js',
     ...
     paths:
      [ ... ] } }

The current value of the foo module is in require.cache["C:\node_modules\foo.js"].exports. We can use require.resolve to get the file path of the module from the name, so we can express it also as require.cache[require.resolve("foo")].exports.

If we call require("foo") a second time, Node sees that require.cache[require.resolve("foo")] is defined, and so it returns the value of require.cache[require.resolve("foo")].exports instead of re-running the module creation code. This exports property of the foo module in require.cache is the single instance of the foo module export value, returned with every subsequent call to require("foo").

One interesting implication here is that you can delete require.cache[require.resolve("foo")] to force a reload of the foo module with the next call to require("foo"), because the object describing the module is removed from the require.cache object.

So what does this mean for me?

Without require, you could still share values between modules using global variables. For example, your Alpha/Beta/Gamma case would work just as well with just Beta and Gamma setting and reading the global value global.a. Instead, with Node's require system, you're actually setting and reading global.require.cache[require.resolve("alpha")].exports.a, which Node lets you read neatly as just require("alpha").a.

In fact, if you just want to share a value and don't need to import your shared data as a module, you could also use a namespacing object, i.e., have Beta and Gamma set and read properties of the object global.alpha. The major advantage to using require is that you don't need to set up require("alpha") external to the other scripts, whereas you would need to define global.alpha = {} before requireing Beta and Gamma. (Alternatively, you could conditionally define global.alpha in each module based on a typeof global.alpha == 'undefined' check instead, to see if it's the first module to use it.)


问:
Separation of Concerns, Data Access Layer
I was thinking about this earlier today and figured I would get some input on the matter. When I develop applications I would usually have the Data Access Layer on another project, incase it could be re-used elsewhere in a similar manner in the future but also to allow updating the DAL without updating the UI layer.

When doing so I handle all of the data querying etc in the DAL. The application does not need to know if its ADO.NET, EF or a List. However, it occurred to me that in almost all cases the return types are specified in the DAL. So the UI Layer does need to know about types defined there. Is that normal or is there a way for more seperation? (other than using Anon types)

答:
Complete decoupling is unrealistic; you eventually wind up with grey goo (amorphous data with no shape at all)  Data without shape is data without meaning.

Data types are more or less implicitly specified already, due to the data's shape, and EF already abstracts away the underlying data store (although in practice it seldom matters anyway; changing the database vendor once it is chosen is extremely rare), so additional abstraction could be a matter of diminishing returns.

All that said, if you really need additional abstraction, you do it in the usual way: by creating another software layer, like a Repository (which you haven't mentioned yet).  Or, you can ditch all that, take the minimalist approach and just use a Key/Value store like BigTable.

See Also

Why is it a good idea for "lower" application layers not to be aware of "higher" ones?


答:
Yes. This is common problem with many DAL solutions. This is reason why people started using POCO/POJO. This allows you to define entities/objects in one project. And then define database mappings in different project, that references those entities.

First versions of EF didn't allow this. Only latest versions do. NHIbernated (and other 3rd party ORMs) do allow this right from the first versions. You can also create repositories and implementations by yourself. But I would discourage creating your own if you already use some kind of ORM solution, because it will become redundant.

But there are still many problems related to this separation. Even with POCO/POJO, the data access leaks into the base entities. Most common is need to make things public/protected even though they should be private.

Title: Separation of Concerns, Data Access Layer

Body:
I was thinking about this earlier today and figured I would get some input on the matter. When I develop applications I would usually have the Data Access Layer on another project, incase it could be re-used elsewhere in a similar manner in the future but also to allow updating the DAL without updating the UI layer.

When doing so I handle all of the data querying etc in the DAL. The application does not need to know if its ADO.NET, EF or a List. However, it occurred to me that in almost all cases the return types are specified in the DAL. So the UI Layer does need to know about types defined there. Is that normal or is there a way for more seperation? (other than using Anon types)


问:
Best Way to Access Hardware per COM Serial Port over USB Adapter
We are starting a total new Branch at our firm. I am usually developing database interfaces or internal server/client applications/tools for our company, but I never had to do something with hardware.

Szenario

My Boss want to sell a device, which has a touch-screen to set up the many, many features. However, the configuration of the device can be very time consuming. He wants to give a software free for a good customer and for a litte charge to "small" customers. The customer should only be able to use the software, if he registers at our system, so that he can't copy the software without a notice by us.

Requirements

The device has a build in USB cable. If you plug it in your computer it opens a new COM serial port. The software has the following requirements:

Configurating different presents for the device

Reading and writing the presets to the device

Software will refuse to start, if the user has no registration at our server

The user can store his presets at our server and share it with other customers

One preset, copied over and over to multiple devices

My boss has seen similar system (he said something about logitech harmony remote controls) and it is now on me, to create the architecture.

Server Side:
The server is not that kind of problem. We have enough different machines to suite any kind of favour (IIS, LAMPP, Apache/Tomcat etc.) I could take MSSQL or MySQL DBase to store the data, thats not the problem.

Client Side:
This is the tricky part for me. I never did something with hardware. My boss suggested I should use Silverlight. I claimed that I want to do it with a native application. But what is the best combination?

Total Client-Side (C++, C# or Java are the languages I could write)

Mixed Structure #1 Silverlight + Native "Driver" Application

Mixed Structure #2 Java-Applet + Native "Driver" Application

Browser Only - Silverlight or Java-Applet?

Any other suggest

The device is for a special customer group who's getting personal trained with any purchase so security risks like unsafe code or dangerous browser plugins are no negative selling argument.

I did some research about COM Serial Port connection with Silverlight and P/Invoke but I don't want to start without a discussion what would be the best way.

答:
If the device doesn't have a network interface of its own, then there are three machines to consider for the use-cases where the device needs to access your server. The three machines are your server, the device and the computer from the customer that the device is connected to.
The customer's computer must be considered, because it must act as a go-between in the data transfer between the sever and the device.

For the server side, it does not really matter what kind of technology you use, as long as there is a defined protocol for communicating with the device and your technology stack can handle that protocol.

For the device, you should use a technology that can run entirely on the device itself, as that allows some use-cases to be executed stand-alone.

For the customer's computer, you can use either a native or a browser-based solution, but for both you should consider which OS-es, respectively browsers are likely to be used by the customers and if you can support them all. For a native solution it might mean you would have to support several versions at the same time. Also, a browser-based solution might be considered more user-friendly.


答:
The parentheses are semantically redundant, so the compiler doesn't care, but that's a red herring--the real concern is programmer readability and comprehension.

I'm going to take the radical position here and give a hearty "no" to the parentheses in a AND b OR c AND d.  Every programmer should know by heart that precedence in Boolean expressions goes NOT > AND > OR, just like remembering Please Excuse My Dear Aunt Sally for algebraic expressions.   Redundant punctuation just adds visual clutter most of the time in code with no benefit in programmer readability.

Also, if you always use parentheses in logical and algebraic expressions, then you give up the ability to use them as a marker for "something tricky is happening here--look out!"  That is, in the cases where you want to override default precedence and have addition evaluated before multiplication, or OR before AND, parentheses are a nice red flag to the next programmer.  Too much use of them when they're not needed, and you become the Boy Who Cried Wolf.

I would make an exception for anything outside the realm of algebra (Boolean or not), such as pointer expressions in C, where anything more complicated than standard idioms like *p++ or p = p->next probably ought to be parenthesized to keep the dereferencing and the arithmetic straight.  And, of course none of this applies to languages like Lisp, Forth, or Smalltalk that use some form of Polish notation for expressions; but for the majority of mainstream languages, logical and arithmetic precedence are totally standardized.


问:
How to handle flag in multiple if-else's
I seem to see this often enough in my code and others. There's nothing about it that seems horribly wrong, but it annoys me as it looks like it can be done better. I suppose a case statement, might make a little more sense, but often variable is a type that does not work well or at all with case statements (depending on language)

```<code>If variable == A
    if (Flag == true)
        doFooA()
    else
        doFooA2

else if variable == B
    if (Flag == true)
        doFooB()
    else
        doFooB2
else if variable == C
    if (Flag == true)
        doFooC()
    else
        doFooC2
</code>```

It seems there's multiple ways to "factor" this, such as 2 sets of if-elses, where one set handles when Flag == true.

Is there a "good way" to factor this, or perhaps when this if-else algorithm happens it usually means you  are doing something wrong?

答:
another option is to combine if and switch.  This is not superior to your nested if technique, but can reduce the number of duplicate tests (if the switch optimizes to a jump table).</p>

```<code>
if (flag)
{
    switch (variable)
    {
        case A:
           ... blah
           break;

        case B:
           ... blah
           break;

        case C:
           ... blah
           break;

        default:
           ... log an error.
           ... maybe do a default action.
           break;
    }
}
else // flag == false
{
    switch (variable)
    {
        case A:
           ... blah
           break;

        case B:
           ... blah
           break;

        case C:
           ... blah
           break;

        default:
           ... log an error.
           ... maybe do a default action.
           break;
}</code>```

Body:
another option is to combine if and switch.  This is not superior to your nested if technique, but can reduce the number of duplicate tests (if the switch optimizes to a jump table).

if (flag)
{
    switch (variable)
    {
        case A:
           ... blah
           break;

        case B:
           ... blah
           break;

        case C:
           ... blah
           break;

        default:
           ... log an error.
           ... maybe do a default action.
           break;
    }
}
else // flag == false
{
    switch (variable)
    {
        case A:
           ... blah
           break;

        case B:
           ... blah
           break;

        case C:
           ... blah
           break;

        default:
           ... log an error.
           ... maybe do a default action.
           break;
}


问:
Should I fully parenthesize expressions or rely on precedence rules?
Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedence than OR. I could write this line of code:

```<code>If (a AND b) OR (c AND d) Then ...
</code>```

But really, that's equivalent to:

```<code>If a AND b OR c AND d Then ...
</code>```

Are there compelling arguments in favor or against including the extraneous parentheses?

Does practical experience suggest that including them significantly improves readability?

Or is wanting them a sign that a developer really needs to sit down and become conversant in the  basics of their language?

答:
General case

In C#, multiplication and division has a precedence over addition and subtraction.

Still, StyleCop, a tool which enforces common style across the codebase with an additional goal to mitigate the risk of bugs introducing by code which may not be clear enough, has the rule SA1407. This rule will produce a warning with a piece of code like this:

```<code>var a = 1 + 2 * 3;
</code>```

It's clear that the result is 7 and not 9, but still, StyleCop suggests to put parenthesis:

```<code>var a = 1 + (2 * 3);
</code>```

Your particular case

In your particular case, there is a precedence of AND compared to OR in the particular language you use.

This is not how every language behave. Many others treat AND and OR equally.

As a developer who works mostly with C#, when I saw your question the first time and read the piece of code without reading what you've wrote before, my first temptation was to comment that the two expressions are not the same. Hopefully, I've read the whole question entirely before commenting.

This particularity and the risk that some developers may believe that AND and OR have the same priority makes it even more important to add parenthesis.

Don't write code with a goal to show that you're smart. Write code with a goal of readability, including by people who may not be familiar with every aspect of the language.

Body:
General case

In C#, multiplication and division has a precedence over addition and subtraction.

Still, StyleCop, a tool which enforces common style across the codebase with an additional goal to mitigate the risk of bugs introducing by code which may not be clear enough, has the rule SA1407. This rule will produce a warning with a piece of code like this:

var a = 1 + 2 * 3;

It's clear that the result is 7 and not 9, but still, StyleCop suggests to put parenthesis:

var a = 1 + (2 * 3);

Your particular case

In your particular case, there is a precedence of AND compared to OR in the particular language you use.

This is not how every language behave. Many others treat AND and OR equally.

As a developer who works mostly with C#, when I saw your question the first time and read the piece of code without reading what you've wrote before, my first temptation was to comment that the two expressions are not the same. Hopefully, I've read the whole question entirely before commenting.

This particularity and the risk that some developers may believe that AND and OR have the same priority makes it even more important to add parenthesis.

Don't write code with a goal to show that you're smart. Write code with a goal of readability, including by people who may not be familiar with every aspect of the language.


答:
Definitely stay away from Java applets and Silverlight. Both are tricky for users, error-prone, and their future is uncertain at best.

The only tricky part is the client.

For client, I'd take a well-supported cross-platform language. Unfortunately, you can't be sure that a runtime for such a language is readily available on a client machine. So bring it with you.

I'd take Ruby, Javascript (node.js), or Python. Either has a relatively compact runtime, and either allows to create an self-contained standalone app from your program. Accessing COM port should not be hard from any of them. Accessing your server, even easier.

Your client app will likely require a GUI. I'd go for a web UI: start a local web server, stop caring about cross-platform GUI toolkits and the like.

I'd build a version of a client for each major OS type (Windows, OSX, Linux) without much (if any) code modifications, and would distribute it with the device.

The server part is not tricky; use whatever technology you like. For the client-server protocol I'd use REST over HTTP(S); it has the fewest problems with any kinds of network setup, firewalls, etc. It also has excellent tools for troubleshooting.

Another tricky part is server-side authorization. It'd be best if your device had an unique ID, because your program would be much easier to crack than a hardware device.

I don't see why this is needed, though. It's the device that brings you profit. You can't sell more of your support software unless you sell more devices, and the support software is useless without a device. I'd just give the software away. Your software is not unlike a driver. See, graphics cards manufacturers allow to download their huge and sophisticated drivers for free, and feel fine. So will you.

Title: Best Way to Access Hardware per COM Serial Port over USB Adapter

Body:
We are starting a total new Branch at our firm. I am usually developing database interfaces or internal server/client applications/tools for our company, but I never had to do something with hardware.

Szenario

My Boss want to sell a device, which has a touch-screen to set up the many, many features. However, the configuration of the device can be very time consuming. He wants to give a software free for a good customer and for a litte charge to "small" customers. The customer should only be able to use the software, if he registers at our system, so that he can't copy the software without a notice by us.

Requirements

The device has a build in USB cable. If you plug it in your computer it opens a new COM serial port. The software has the following requirements:

Configurating different presents for the device

Reading and writing the presets to the device

Software will refuse to start, if the user has no registration at our server

The user can store his presets at our server and share it with other customers

One preset, copied over and over to multiple devices

My boss has seen similar system (he said something about logitech harmony remote controls) and it is now on me, to create the architecture.

Server Side:
The server is not that kind of problem. We have enough different machines to suite any kind of favour (IIS, LAMPP, Apache/Tomcat etc.) I could take MSSQL or MySQL DBase to store the data, thats not the problem.

Client Side:
This is the tricky part for me. I never did something with hardware. My boss suggested I should use Silverlight. I claimed that I want to do it with a native application. But what is the best combination?

Total Client-Side (C++, C# or Java are the languages I could write)

Mixed Structure #1 Silverlight + Native "Driver" Application

Mixed Structure #2 Java-Applet + Native "Driver" Application

Browser Only - Silverlight or Java-Applet?

Any other suggest

The device is for a special customer group who's getting personal trained with any purchase so security risks like unsafe code or dangerous browser plugins are no negative selling argument.

I did some research about COM Serial Port connection with Silverlight and P/Invoke but I don't want to start without a discussion what would be the best way.


答:
Complex conditionals are "boolean algebra", which you write in some ways that, well, make it look pretty much exactly like algebra, and you'd definitely use parens for algebra, wouldn't you?

The really useful rules are the negation ones:

```<code>!(A || B) <=> !A && !B
!(A && B) <=> !A || !B
</code>```

Or, in a little clearer format:

```<code>!(A + B) <=> !A * !B
!(A * B) <=> !A + !B
</code>```

which is really clearly just algebra when written as:

```<code>-1*(A + B) = -A + -B
-1*(A * B) = -A * -B
</code>```

But we can also apply the thinking for algebraic simplification and expansion:

```<code>(A && B) || (C && D) =>
((A && B) || C) && ((A && B) || D) =>
(AC && BC) && (AD && BD) =>
AC && BC && AD && BD
</code>```

although in code you have to write:

```<code>(A||C) && (B||C) && (A||D) && (B||D)
</code>```

or, in a little clearer format:

```<code>(A + B) * (C + D) =>
((A + B) * C) + ((A + B) * D) =>
(AC + BC) + (AD + BD) =>
AC + BC + AD + BD
</code>```

Basically, a conditional is still just an algebraic expression, and by clearly using parenthesis, you can more easily apply the various algebraic rules you already know to the expression, including ye olde concept of "simplify or expand this formula".

Body:
Complex conditionals are "boolean algebra", which you write in some ways that, well, make it look pretty much exactly like algebra, and you'd definitely use parens for algebra, wouldn't you?

The really useful rules are the negation ones:

!(A || B) <=> !A && !B
!(A && B) <=> !A || !B

Or, in a little clearer format:

!(A + B) <=> !A * !B
!(A * B) <=> !A + !B

which is really clearly just algebra when written as:

-1*(A + B) = -A + -B
-1*(A * B) = -A * -B

But we can also apply the thinking for algebraic simplification and expansion:

(A && B) || (C && D) =>
((A && B) || C) && ((A && B) || D) =>
(AC && BC) && (AD && BD) =>
AC && BC && AD && BD

although in code you have to write:

(A||C) && (B||C) && (A||D) && (B||D)

or, in a little clearer format:

(A + B) * (C + D) =>
((A + B) * C) + ((A + B) * D) =>
(AC + BC) + (AD + BD) =>
AC + BC + AD + BD

Basically, a conditional is still just an algebraic expression, and by clearly using parenthesis, you can more easily apply the various algebraic rules you already know to the expression, including ye olde concept of "simplify or expand this formula".


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
While knowing .Net can be a plus, I really doubt that one could stay just within just .Net and not end up getting into either a UI specific language like JavaScript or some database work, possibly T-SQL or PL/SQL to give a couple of examples.  While these may be considered within a .Net development environment in a broad sense, they are other technical skills that can be useful in securing employment.

I'd also be careful of trying to get too specialized as the .Net platform could grow rather broadly to some extent.  There may be times where a new version of the framework brings in some other big changes like how the 3.0 version added WPF and WCF to give a couple of examples.  In other words, even within .Net there can be new things coming along that may change things in the next 10 years.


答:
Yes

You should always use parentheses... you do not control the order of precedence... the developer of the compiler does. Here is a story that happened to me about non use of parentheses. This affected hundreds of people over a two week period.

Real World Reason

I inherited a main-frame application. One day, out of the blue, it stopped working. That's it... poof it just stopped.

My job was to get it working as fast as possible. The source code had not been modified for two years, but all of the sudden it just stopped. I tried to compile the code and it broke on line XX. I looked at line XX and I could not tell what would make line XX break. I asked for the detailed specs for this application and there were none. Line XX was not the culprit.

I printed out the code and started reviewing it from the top down. I started to create a flowchart of what was going on. The code was so convoluted I could hardly even make sense of it. I gave up trying to flowchart it. I was afraid to make changes without knowing how that change would effect the rest of the process, especially since I had no details of what the application did or where it was in the dependency chain.

So, I decided to start at the top of the source code and add whitespace and line breaks to make the code more readable. I noticed, in some cases, there were if conditions that combined AND and OR statements and it wasn't clearly distinguishable what data was being ANDed and what data was being ORed. So I started putting parentheses around the AND and OR conditions to make them more readable.

As I slowly moved down cleaning it up, I would periodically save my work. At one point I tried compiling the code and a strange thing happened. The error had jumped passed the original line of code and was now further down. So I continued, separating the AND and OR conditions with parens. When I got done cleaning it up it worked. Go figure.

I then decided to visit the operations shop and ask them if they had recently installed any new components on the main-frame. They said yes, we recently upgraded the compiler. Hmmmm.

It turns out that the old compiler evaluated expressions from left to right regardless. The new version of the compiler also evaluated expressions from left to right but ambiguous code, meaning unclear combinations of AND and OR could not be resolved.

Lesson I learned from this... ALWAYS, ALWAYS, ALWAYS use parens to separated AND conditions and OR conditions when they are used in conjunction with each other.

Simplified Example

`IF Product = 191 OR Product = 193 AND Model = "ABC" OR Product = 201 OR Product = 202 AND Model = "DEF" ...` (code littered with several of these)

This is a simplified version of what I encountered. There were else conditions with compound boolean logic statements as well.

I remember changing it to:

`IF ((Product = 191 OR Product = 193) AND Model = "ABC") OR ((Product = 201 OR Product = 202) AND Model = "DEF") ...`

I couldn't rewrite it because there were no specs. The original author was long gone. I remember intense pressure. An entire cargo ship was stranded in port and could not be offloaded because this little program did not work. No warning. No changes to the source code. It only dawned on me to ask the Network Operations if they modified anything after I noticed that adding parens shifted the errors.


答:
Or is it a sign that a developer needs to really sit down and become
  confident in the basics of their language?

If you strictly use language in singular, maybe. Now take all the languages you know, from ages old to most modern, from compiled to scripting to SQL to your own DSL you've invented last month.

Do you remember the exact precedence rules for each of these languages, without looking?