问:
Testing front-end app that hits a REST service
A lot of questions about testing here... And I have another one. Forgive me, but I want to make sure I do this right.

Let's say I have a front-end application, be it a mobile app, or a single-page website, or anything else. This app hits a REST service, that I also develop. The service fetches data from 3rd party REST APIs, processes this data, and returns the results to the application.

My service is well tested and developed in a hexagonal manner, with comprehensive black-box unit tests (canned data) and few integration tests (hitting 3rd party services) to see that adapters are working ok with ports (see here).

My front end is also well tested with unit tests and mock data (it doesn't really hit the service in tests). I feel though that it would be nice if it was tested together with the service I develop. The few things I am unsure of:

Should I be using canned data when testing my service, or should I be hitting 3rd party APIs in the tests?

Should these be comprehensive automated tests (provided that all functionality is already tested with canned data on front end, and the service is really well tested too, so a lot of these tests would be testing what's already tested), or should it be just few manual tests, like hitting some buttons and seeing if the data comes through? Here I am mainly thinking about the cost/benefit ratio.

Are there any frameworks to write comprehensive automated tests like that?

I am sure many of you were in similar situation. So it would be great to get some advice. If you can link a white paper or a conference about the subject, it would be even better. Thanks in advance for any suggestions.

答:
If you do not own the REST API's, your responsibility ends with them

You need tests that check if your application calls the API under your control correctly. Therefore, use the actual application with the actual service (the one you control) but calling mocked services (the ones you don't control).

So...

Use canned data for the services you don't control, pipe that data into your actual service and then use that from your application.

This should be a very broad test to simply check if calls from your application go through to the service. At this point you should already have thoroughly tested your application with the responses your service might return and you should have thoroughly tested your service with the responses the services you can't control might return. All of this preferably automated. Depending on the amount of releases you do it might be easier to test this manually just prior to release.

Depends on the technology used, which might not make this the best website for that question.


问:
How do microservice system architectures avoid network bottlenecks?
I've been reading a lot about microservice architectures for server applications, and have been wondering how the internal network usage is not a bottleneck or a significant disadvantage compared to a monolith architecture.

For the sake of precision, here are my interpretations of the two terms:

Monolith architecture: One application in a single language that handles all of the functionality, data, etc. A load balancer distributes requests from the end user across multiple machines, each running one instance of our application.

Microservice architecture: Many applications (microservices) handling a small portion of the functionality and data. Each microservice exposes a common API that is accessed through the network (as opposed to inter-process communication or shared memory on the same machine). API calls are stiched mostly on the server to produce a page, although perhaps some of this work is done by the client querying individual microservices.

To my naive imagination, it seems like a microservices architecture uses slow network traffic as opposed to faster resources on the same machine (the memory and the disk). How does one ensure that API querying through the internal network will not slow down the overall response time?

答: By structuring your code and resource access such that the resulting system can be flexible enough to run as a monolithic application or a distributed one via configuration. If you abstract away the communication mechanism behind some common interface and you build your system with concurrency in mind, you can easily optimize everything after you have profiled your system and found the real bottle necks.

ContentLicense: CC BY-SA 3.0


答: I think you are reading too much into the 'micro' part. It doesn't mean replace every class with a network service, but componentize a monolithic application into sensibly sized components, each one dealing with an aspect of your program. The services won't talk to each other, so at worst you've split a large network request into several smaller ones. The data returned won't be significantly different to what you're receive anyway (though you might return more data and consolidate it in the client)</p>

Title: How do microservice system architectures avoid network bottlenecks?

Body:
I've been reading a lot about microservice architectures for server applications, and have been wondering how the internal network usage is not a bottleneck or a significant disadvantage compared to a monolith architecture.

For the sake of precision, here are my interpretations of the two terms:

Monolith architecture: One application in a single language that handles all of the functionality, data, etc. A load balancer distributes requests from the end user across multiple machines, each running one instance of our application.

Microservice architecture: Many applications (microservices) handling a small portion of the functionality and data. Each microservice exposes a common API that is accessed through the network (as opposed to inter-process communication or shared memory on the same machine). API calls are stiched mostly on the server to produce a page, although perhaps some of this work is done by the client querying individual microservices.

To my naive imagination, it seems like a microservices architecture uses slow network traffic as opposed to faster resources on the same machine (the memory and the disk). How does one ensure that API querying through the internal network will not slow down the overall response time?


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答: A language-integrated-query-engine would be great.  Sort of like what is available in .NET called LINQ.  It would help sort through massive arrays of data, and standardize database access, so that fewer SQL-injection attacks succeed.</p>

ContentLicense: CC BY-SA 2.5


答:
Your naive imagination is right. And often that doesn't matter. Modern machines are fast. The main advantages of micro service architecture are seen in development and maintenance effort and time.  </p>

<p>And of course there is no rule saying you can't use shared memory or even physically deploy multiple services in one executable. Just as long as you design it not to be dependent on that. </p>

Body:
Your naive imagination is right. And often that doesn't matter. Modern machines are fast. The main advantages of micro service architecture are seen in development and maintenance effort and time.

And of course there is no rule saying you can't use shared memory or even physically deploy multiple services in one executable. Just as long as you design it not to be dependent on that.


答:
Internal networks often use 1 Gbps connections, or faster. Optical fiber connections or bonding allow much higher bandwidths between the servers. Now imagine the average size of a JSON response from an API. How much of such responses can be transmitted over a 1 Gbps connection in one second?

Let's actually do the math. 1 Gbps is 131 072 KB per second. If an average JSON response is 5 KB (which is quite a lot!), you can send 26 214 responses per second through the wire with just with one pair of machines. Not so bad, isn't it?

This is why network connection is usually not the bottleneck.

Another aspect of microservices is that you can scale easily. Imagine two servers, one hosting the API, another one consuming it. If ever the connection becomes the bottleneck, just add two other servers and you can double the performance.

This is when our earlier 26 214 responses per second becomes too small for the scale of the app. You add other nine pairs, and you are now able to serve 262 140 responses.

But let's get back to our pair of servers and do some comparisons.

If an average non-cached query to a database takes 10 ms., you're limited to 100 queries per second. 100 queries. 26 214 responses. Achieving the speed of 26 214 responses per second requires a great amount of caching and optimization (if the response actually needs to do something useful, like querying a database; "Hello World"-style responses don't qualify).

On my computer, right now, DOMContentLoaded for Google's home page happened 394 ms. after the request was sent. That's less than 3 requests per second. For Programmers.SE home page, it happened 603 ms. after the request was sent. That's not even 2 requests per second. By the way, I have a 100 Mbps internet connection and a fast computer: many users will wait longer.

If the bottleneck is the network speed between the servers, those two sites could literally do thousands of calls to different APIs while serving the page.

Those two cases show that network probably won't be your bottleneck in theory (in practice, you should do the actual benchmarks and profiling to determine the exact location of the bottleneck of your particular system hosted on a particular hardware). The time spent doing the actual work (would it be SQL queries, compression, whatever) and sending the result to the end user is much more important.

Think about databases

Usually, databases are hosted separately from the web application using them. This can raise a concern: what about the connection speed between the server hosting the application and the server hosting the database?

It appears that there are cases where indeed, the connection speed becomes problematic, that is when you store huge amounts of data which don't need to be processed by the database itself and should be available right now (that is large binary files). But such situations are rare: in most cases, the transfer speed is not that big compared to the speed of processing the query itself.

When the transfer speed actually matters is when a company is hosting large data sets on a NAS, and the NAS is accessed by multiple clients at the same time. This is where a SAN can be a solution. This being said, this is not the only solution. Cat 6 cables can support speeds up to 10 Gbps; bonding can also be used to increase the speed without changing the cables or network adapters. Other solutions exist, involving data replication across multiple NAS.

Forget about speed; think about scalability

An important point of a web app is to be able to scale. While the actual performances matter (because nobody wants to pay for more powerful servers), scalability is much more important, because it let you to throw additional hardware when needed.

If you have a not particularly fast app, you'll lose money because you will need more powerful servers.

If you have a fast app which can't scale, you'll lose customers because you won't be able to respond to an increasing demand.

In the same way, virtual machines were a decade ago perceived as a huge performance issue. Indeed, hosting an application on a server vs. hosting it on a virtual machine had an important performance impact. While the gap is much smaller today, it still exists.

Despite this performance loss, virtual environments became very popular because of the flexibility they give.

As with the network speed, you may find that VM is the actual bottleneck and given your actual scale, you will save billions of dollars by hosting your app directly, without the VMs. But this is not what happens for 99.9% of the apps: their bottleneck is somewhere else, and the drawback of a loss of a few microseconds because of the VM is easily compensated by the benefits of hardware abstraction and scalability.


问:
Why aren't `void *`'s implicitly cast in C++?
In C, there is no need to cast a void * to any other pointer type, it is always safely promoted. However, in C++, this is not the case. E.g.,

```<code>int *a = malloc(sizeof(int));
</code>```

works in C, but not in C++. (Note: I know that you shouldn't use malloc in C++, or for that matter new, and should instead prefer smart pointers and/or the STL; this is asked purely out of curiosity) Why does the C++ standard not allow this implicit cast, while the C standard does?

答:
Here is what Stroustrup says:

In C, you can implicitly convert a void* to a T*. This is unsafe

He then goes on to show an example of how void* can be dangerous and says:

... Consequently, in C++, to get a T* from a void* you need an explicit cast. ...

Finally, he notes:

One of the most common uses of this unsafe conversion in C is to assign the result of malloc() to a suitable pointer. For example:

int* p = malloc(sizeof(int));

In C++, use the typesafe new operator:

int* p = new int;

He goes into a lot more detail on this in The Design and Evolution of C++.

So the answer boils down to: The language designer believes it is an unsafe pattern, and so made it illegal and provided alternate ways of accomplishing what the pattern was normally used for.


问:
String Searching algorithm
A title for a movie can be ambiguous. (Eg. The Lord of the Rings, Lord of the Rings, Lord of the Rings, The)
There exists a database entry that has a list of movie titles mapped to a unique identifier.

I am trying to write a method that takes a String title input and returns the unique identifier mapped to it after having resolved any ambiguity.(Is is a sequel? A remake?)

What is a good data structure to be used here?

答:
Your question is a little unclear as the title asks for an algorithm, but you also ask for a data structure.  I will describe what I did with a similar issue, dealing with music.

The way I approached it was with a series of string transformations that produced a string with as much ambiguity removed as possible.

A few of the rules:

Remove all whitespace

Change all non-ASCII letters to ASCII equivalents.  (ö -> o)

Change everything to uppercase

If a comma is encountered, swap the right side of the common with the left

Remove common words like "the", "of", etc.

Change Roman numerals to Arabic ("VII" -> 7)

So I'd end up with:

```<code>Blue Öyster Cult -> BLUEOYSTERCULT
Amos, Tori -> TORIAMOS
The Red Hot Chili Peppers -> REDHOTCHILIPEPPERS
</code>```

I then used that for all comparisons, though it was never exposed to the user.  In my case, I just used this as the identifier.

The rules were necessarily a bunch of heuristics developed by experimenting with real CDDB data.  It obviously wasn't guaranteed to be foolproof, but it wasn't that hard to find a set that worked most of the time.

Your issue isn't quite the same.  Remakes will be a problem because your titles will match.  That might be partially solvable by looking for dates in the title ("Total Recall (2013)")  but I suspect that data will often be missing.

Title: String Searching algorithm

Body:
Your question is a little unclear as the title asks for an algorithm, but you also ask for a data structure.  I will describe what I did with a similar issue, dealing with music.

The way I approached it was with a series of string transformations that produced a string with as much ambiguity removed as possible.

A few of the rules:

Remove all whitespace

Change all non-ASCII letters to ASCII equivalents.  (ö -> o)

Change everything to uppercase

If a comma is encountered, swap the right side of the common with the left

Remove common words like "the", "of", etc.

Change Roman numerals to Arabic ("VII" -> 7)

So I'd end up with:

Blue Öyster Cult -> BLUEOYSTERCULT
Amos, Tori -> TORIAMOS
The Red Hot Chili Peppers -> REDHOTCHILIPEPPERS

I then used that for all comparisons, though it was never exposed to the user.  In my case, I just used this as the identifier.

The rules were necessarily a bunch of heuristics developed by experimenting with real CDDB data.  It obviously wasn't guaranteed to be foolproof, but it wasn't that hard to find a set that worked most of the time.

Your issue isn't quite the same.  Remakes will be a problem because your titles will match.  That might be partially solvable by looking for dates in the title ("Total Recall (2013)")  but I suspect that data will often be missing.


答:
PHP suits me just fine as it is for knocking up small to medium websites; I must be a bit unimaginative, the only thing I could think of as a response to this question would be something that makes it scale better for high traffic sites.

I'm thinking in terms of spawning off processes to other cores, for example updating a database in one process while creating the output page in another process. A quick google search indicates that this can be simulated, but is not supported directly in php at present.

Title: What features would you like to have in PHP?

Body:
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.


问:
Longest x86 Instruction
I read the recent article "Longest x86 Instruction"

https://web.archive.org/web/20160405202815/http://blog.onlinedisassembler.com/blog/?p=23

I attempted to reproduce the curious disassembly issue on a Win7x86 development platform using masm and as the article suggested, redunant prefixes.

Talk is cheap, so here's a toy program (masm32):

```<code>.386 .model flat, stdcall

option casemap:none

includelib \x\x\kernel32.lib
includelib \x\x\user32.lib

include \x\x\kernel32.inc
include \x\x\user32.inc
include \x\x\windows.inc

.code

start:

db 0F3h
db 0F3h
db 0F3h
db 0F3h
db 0F3h
db 0F3h
db 0F3h
;...6 more bytes later
db 089h
db 0E5h

end start

invoke ExitProcess, NULL
</code>```

After linking and assembling, I opened the resulting executable in windbg.

To my disappointment, when I single step, unassemble the $exentry, etc. windbg simply sees the prefixes/bytes as individual instructions, says 'to hell with it' and executes only the valid instructions.

Is there something I'm missing?

答:
I was confused by the disassembler implementation...the processor executes instructions that are ( i.cache <=15B ) as the artcle states.

Verified when I single step, as IP increases by 15B.

So, it accurately treats the prefix bytes as a part of one single instruction.

However, I tested dumpbin /disasm and windbg so far, which disassemble the prefix bytes as individual instructions instead of contiguously with the "real" instruction, e.g.

```<code>F3
F3
;...
89 ; start of 'real' instruction: mov ebp, esp
E5
</code>```

...having evil thoughts already.

Apologies for forgetting the OS's/software's disassembler implementation isn't taking full advantage of processor capabilities (like Windows not implementing Ring2, etc.).

Thanks!

ContentLicense: CC BY-SA 4.0

Title: Longest x86 Instruction

Body:
I was confused by the disassembler implementation...the processor executes instructions that are ( i.cache <=15B ) as the artcle states.

Verified when I single step, as IP increases by 15B.

So, it accurately treats the prefix bytes as a part of one single instruction.

However, I tested dumpbin /disasm and windbg so far, which disassemble the prefix bytes as individual instructions instead of contiguously with the "real" instruction, e.g.

F3
F3
;...
89 ; start of 'real' instruction: mov ebp, esp
E5

...having evil thoughts already.

Apologies for forgetting the OS's/software's disassembler implementation isn't taking full advantage of processor capabilities (like Windows not implementing Ring2, etc.).

Thanks!


问:
Is there any plan to take out "features" from next versions of javascript?
I'm looking to learn javascript (now for real) and I've had a look on the latest version of ES6 which is supposed to be frozen in terms of features set.
It seems to be the pretty much same as ES5 plus new stuff(features). My main complain is that there so many ways to accomplish the same thing so I'm wondering if there is any plan to take out some of the old "features" or if it keeps building up on top of the old specs(i.e. until it becomes a big mess).  </p>

答:
ECMAScript ist the single most compatibility-constrained language that ever existed.

In general, developers can't choose the version of the implementation (or even which implementation) that is going to be used to run their code, because it is installed on the users' machine. Users can't choose the version of the app they run, because the code gets delivered by the remote website. Users often can't even choose which version of which implementation they are running, because the implementation is bound to the browser and the browser is dictated by the OS, some IT department policy, or backwards-compatibility constraints of other unrelated websites.

Websites are (should be) eternal. There may be some ECMAScript-heavy website that hasn't been maintained for 10 years, but you still need to be able to visit it 10 years from now, with a browser with an embedded ECMAScript 10 engine.

Giving those extreme backwards-compatibility constraints, it is pretty much impossible to remove a feature once it is there. var is one such feature that should probably be removed, but likely never will.

However, there is a transition feature: ECMAScript 5 and 6 have a so-called Strict Mode which is triggered by a "use strict" declaration. Strict mode is not just a subset of normal mode, it may actually have different semantics. And future versions of ECMAScript are usually built on top of the previous version's strict mode. E.g. ECMAScript 6 is built on ECMAScript 5 strict mode. New language features automatically trigger strict mode, e.g. module and class declarations in ECMAScript 6 will always be evaluated in strict mode, regardless of whether there is a "use strict" declaration.


问:
How to handle type conversion of a constant?
Consider the following (imaginary) code extract:

```<code>class X {
   private static String IS_PAYLOAD_REQUIRED = "4001";
   [....]
   checkPayloadRequired(String input) {
     if (input.startsWith(IS_PAYLOAD_REQUIRED)) {
       settings.enable(Integer.valueOf(IS_PAYLOAD_REQUIRED).intValue());
     }
   }
 }
</code>```

IS_PAYLOAD_REQUIRED is required both as a String and an int. The code above delares a String constant and converts to int at runtime when necessary. This conversion is cheap but unnecessary.

Is it worth trying to avoid the conversion? I can think of the following two ways of doing it. Appreciate any comments on usefulness of either.

1: Declare Two variables

```<code>private static String IS_PAYLOAD_REQUIRED = "4001";
private static String IS_PAYLOAD_REQUIRED_INT = Integer.valueOf(IS_PAYLOAD_REQUIRED).intValue();
</code>```

Now use one of the two constants.

2: Create a StringAndInt class
    private static StringAnInt IS_PAYLOAD_REQUIRED = new StringAnInt(4001);

Use IS_PAYLOAD_REQUIRED.intValue() or IS_PAYLOAD_REQUIRED.stringValue(). I am not showing the implementation of the class here because it is trivial.

The second is obviously safer but I am wondering if it is an overkill.

答:
Is it worth trying to avoid the conversion?

It depends. This is one of those cases where the "first, measure" sort of advice comes into play. If your profiler says it's an issue, then yes. If not, then I would say no - it's readable enough with the conversion.

The second is obviously safer but I am wondering if it is an overkill.

Yes. If you're using constants, rather than passing around something that regularly needs converted between the two values (and CPU needs optimized more than space), then having two constants is fine. It's readable, it's unlikely to get out of sync, and it's very likely to address performance problems.


问:
Open Source code in Closed Source project
If I am using open source code in my project but don't want to release any source code, what license should I use?</p>

答:
Verify that the open source you are using does not contain a "copyleft"* provision, or any other condition that prevents you from using a closed-source license, and then use a closed-source license.

That's it.

Note that the license you choose does not change the terms of the licenses of the open source code you are using in your project.  If those terms say you can't close the source, then you can't close the source.

*Copyleft is the provision in the GPL licenses that requires you to release the entire source code of your project, if you use any software, code or libraries in your project that are GPL-licensed.


问:
what should be logger's position in the parameter list
In my code I inject a logger to many of my classes through their constructor's parameter list

I noticed that I put it randomly: sometimes it's the first on the list, sometimes last, and sometimes in between

Do you have any preference? My intuition says that consistency is helpful in this case and my personal preference is to put it first so it will be easier to be noticed when it's missing and easier to skip when it's there.

答:
Loggers are a bit of a special case because they have to be available literally everywhere.

If you've decided that you want to pass a logger into every class' constructor, then you should definitely set a consistent convention for how you do that (eg, always the first parameter, always passed by reference, the constructor initialization list always starts with m_logger(theLogger), etc). Anything that's going to be used throughout your entire codebase is going to benefit from consistency someday.

Alternatively, you could have every class instantiate their own logger object, without needing anything to be passed in. The logger may need to know a few things "by magic" for that to work, but hardcoding a filepath in the class definition is potentially a lot more maintainable and less tedious than passing it correctly to hundreds of different classes, and arguably a lot less evil than using a global variable to bypass said tedium. (Admittedly, loggers are among the very few legitimate use cases for global variables)


答:
In languages with function overloading, I'd argue that the more likely an argument is to be optional, the further right it should be. This creates consistency when you create overloads where they're missing:

```<code>foo(mandatory);
foo(mandatory, optional);
foo(mandatory, optional, evenMoreOptional);
</code>```

In functional languages the reverse is more useful - the more likely you are to choose some default, the further left it should be. This makes it easier to specialize the function by simply applying arguments to it:

```<code>addThreeToList = map (+3)
</code>```

However as mentioned in the other answers, you probably don't want to explicitly pass the logger in the argument list of every class in the system.

Title: what should be logger's position in the parameter list

Body:
In my code I inject a logger to many of my classes through their constructor's parameter list

I noticed that I put it randomly: sometimes it's the first on the list, sometimes last, and sometimes in between

Do you have any preference? My intuition says that consistency is helpful in this case and my personal preference is to put it first so it will be easier to be noticed when it's missing and easier to skip when it's there.

Body:
In languages with function overloading, I'd argue that the more likely an argument is to be optional, the further right it should be. This creates consistency when you create overloads where they're missing:

foo(mandatory);
foo(mandatory, optional);
foo(mandatory, optional, evenMoreOptional);

In functional languages the reverse is more useful - the more likely you are to choose some default, the further left it should be. This makes it easier to specialize the function by simply applying arguments to it:

addThreeToList = map (+3)

However as mentioned in the other answers, you probably don't want to explicitly pass the logger in the argument list of every class in the system.


问:
What "version naming convention" do you use?
Are different version naming conventions suited to different projects? What do you use and why?

Personally, I prefer a build number in hexadecimal (e.g 11BCF), this should be incremented very regularly. And then for customers a simple 3 digit version number, i.e. 1.1.3.

```<code>1.2.3 (11BCF) <- Build number, should correspond with a revision in source control
^ ^ ^
| | |
| | +--- Minor bugs, spelling mistakes, etc.
| +----- Minor features, major bug fixes, etc.
+------- Major version, UX changes, file format changes, etc.
</code>```

答:
I prefer version numbers that assign some semantic meaning.  As long as you can use the version number to track bugs reported with a particular version to changes that occurred in the source code (and in your activity management system) then you're probably using the right method.

I use .NET so I'm stuck with the .NET version numbering system but I try to give semantic meaning to the numbers so with

major.minor.build.revision

major = (up to the project)

minor =
(up to the project)

build = build
number from Hudson (you could use
TeamCity or TeamBuild, etc. here)

revision = subversion or bazaar
revision (depending on the project
and what its using)

We always make sure thatt he version number is visible in some way (with our batch console-based programs its printed to console and a log file, with web apps its on the menu bar at the top usually)

This way if clients report problems we can use the version number to track if they are using the latest version and how many problems we have had with particular versions.

It's all about traceability!


答:
Loggers are what we call a "cross-cutting concern."  They yield to techniques such as Aspect-Oriented Programming; if you have a way to decorate your classes with an attribute  or perform some code weaving, then that is a good way to get logging capabilities while keeping your objects and parameter lists "pure."

The only reason you might want to pass in a logger is if you wanted to specify different logging implementations, but most logging frameworks have the flexibility to allow you to configure them, say, for different logging targets. (log file, Windows Event Manager, etc.)

For these reasons, I prefer to make logging a natural part of the system, rather than passing a logger into every class for logging purposes.  So what I generally do is reference the appropriate logging namespace, and simply use the logger in my classes.

If you still want to pass in a logger, my preference is that you make it the last parameter in the parameter list (make it an optional parameter, if possible).  Having it be the first parameter doesn't make much sense; the first parameter should be the most important one, the one most relevant to the class's operation.


答:
I would begin by sanitizing the input data much like @Steven Burnap and then calculate the Levenshtein distance between the input and all known movie titles. Return the top couple results. Since there's likely to be a high degree of variation between your users' input and your list of known movie titles, an exact string search algorithm isn't a good fit.

You'll have to experiment to find the most accurate and quickest fuzzy search algorithm for your use case, and you'll have to decide if it's faster to perform the calculation in the DB or on an app server. It just comes down to your app architecture.

edit: When you're dealing with sequels, I would treat all titles within a series as having an equal weight, and then choose the most appropriate answer based upon some external factor. For your software's initial release, maybe just sort by movie release date. For a second release, poll an external API to find the most buzzworthy title. For a third release, perhaps gather some user metrics to find the most relevant result (for instance, if the user regularly prefers sequels over originals, give the sequel a higher score).

Title: String Searching algorithm

Body:
A title for a movie can be ambiguous. (Eg. The Lord of the Rings, Lord of the Rings, Lord of the Rings, The)
There exists a database entry that has a list of movie titles mapped to a unique identifier.

I am trying to write a method that takes a String title input and returns the unique identifier mapped to it after having resolved any ambiguity.(Is is a sequel? A remake?)

What is a good data structure to be used here?


答:
You can definitely spend a lot of time over-engineering this problem.

For languages with canonical logging implementations, just instantiate the canonical logger directly in every class.

For languages without a canonical implementation, try to find a logging facade framework and stick to it. slf4j is a good choice in Java.

Personally I'd rather stick to a single concrete logging implementation and send everything to syslog. All the good log analysis tools are capable of combining sysout logs from multiple app servers into a comprehensive report.

When a function signature includes one or two dependency services as well as some "real" arguments, I place the dependencies last:

int calculateFooBarSum(int foo, int bar, IntegerSummationService svc)

Since my systems tend to only have five or fewer such services, I always make sure the services are included in the same order across all function signatures. Alphabetical order is as good as any. (Aside: maintaining this methodological approach for mutex handling will also reduce your chances of developing deadlocks.)

If you find yourself injecting more than a dozen or so dependencies across your app, then the system probably needs to be split up into separate subsystems (dare I say microservices?).


问:
What's the correct way to architect multiple ASP.NET MVC applications dealing with similar data?
I am currently working to replace a bunch of legacy applications. The first one is getting close to being released, which will mean I will be starting the second one.

Each application deals with a specific part of a sales process. Initial customer acquisition (with potentially very little customer data, with a lot of it being optional intentionally), through to actual quote/sale process, and then on to an application looking at how to get customers back into the beginning of the sales acquisition process.

Now I have built applications for many years, used different techniques, all with their pro's/con's, without really knowing the preferred way.

One large database, re-used by all of the applications to share customer data etc. This can make it a lot of work to maintain, having loads of developers all working on the same schema and services, having a dependency to most likely have to release all applications at the same time following changes

Database split per area (Customer, Sales, Business Hierarchy etc), gives a logical split, but they are all still used by all of the applications, yet joins for data across databases can cause problems unless you do cross-database joins/link servers etc

Each individual application has it's own set of databases. This makes development of each application a lot quicker and simpler. Yet also gives a lot of duplication in data copying it across each application. Then any changes in data needs synced somehow with other databases. For some areas you could open up a web API to get to some data between them, but a lot of the time you may end up having to read from one database to use that info to get more info from another etc rather than doing simple quick joins.

Can anyone give some info on the correct way? Yes, things can possibly be subjective, but I'm sure one of these ways would be more recommended than the other.

答:
Microservices are the current trend, and they would roughly correspond with your third choice. You can spend a lot of time getting sucked into the literature around microservices, but yes, you will definitely contend with some degree of data duplication and possibly performance issues when compositing multiple microservices into a usable product.

Ultimately there isn't a right or wrong answer. Take the microservice literature with a grain of salt. They aren't always a good choice.


答:
I agree with those suggesting that the logger should be statically accessed rather than passed into classes. However if there is a strong reason you want to pass it in (perhaps different instances want to log to different locations or something) then I would suggest you do not pass it using the constructor but rather make a separate call to do so, e.g. Class* C = new C(); C->SetLogger(logger); rather than Class* C = new C(logger);

The reason for preferring this method is that the logger is not an essentially part of the class but rather an injected feature used for some other purpose. Placing it in the constructor list makes it a requirement of the class and implies it is part of the actual logical state of the class. It is reasonable to expect, for example (with most classes although not all), that if X != Y then C(X) != C(Y) but it is unlikely that you would test logger inequality if you are comparing too instances of the same class.


问:
Creating one-line method for the single purpose of self-documenting code
Given the following two snippets:

Snippet 1:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //If node changed currentId reset it to the original.
    data.setCurrentId(originalId);
}
</code>```

Snippet 2:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    resetCurrentIdIfChangedByNode(data, originalId);
}

private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

In both cases it is not be known whether node.execute() changes the currentId or not.

Does the one-line method in Snippet 2 make the code more readable? Or is it preferable to use comments as in Snippet 1?

EDIT: I understand that node has side effects. This is why I'm resorting to creating a method that explains (or tries to explain) that the data.currentId might be changed by node. Depending on which subclass of AbstractNode is being used, it might be changed or not.

EDIT 2: The reason there is no if statement around the reset in Snippet 2 is that it would be pointless, since the result would be the same whether we check or not.

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

same result as

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    if(data.getCurrentId() != originalId)
    {
        data.setCurrentId(originalId);
    }
}
</code>```

答:
Your comment can be easily misinterpreted, as you see from some of the other answers. Most devs are trained to associate the word "if" with a conditional branch, but that is obviously not what you meant.

I guess this is what you really meant:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //in case "execute" changed the current id of "data", restore the original one
    data.setCurrentId(originalId);
}
</code>```

If you want to make the comment obsolete by picking good function names, refactoring the last two lines into a separate method is IMHO not a good approach. Instead, use a better name than foo, for example:

```<code>public void executeWhileKeepingCurrentId(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);
    data.setCurrentId(originalId);
}
</code>```

Now the intent is clear without the need for a long winded comment.

Body:
Your comment can be easily misinterpreted, as you see from some of the other answers. Most devs are trained to associate the word "if" with a conditional branch, but that is obviously not what you meant.

I guess this is what you really meant:

public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //in case "execute" changed the current id of "data", restore the original one
    data.setCurrentId(originalId);
}

If you want to make the comment obsolete by picking good function names, refactoring the last two lines into a separate method is IMHO not a good approach. Instead, use a better name than foo, for example:

public void executeWhileKeepingCurrentId(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);
    data.setCurrentId(originalId);
}

Now the intent is clear without the need for a long winded comment.


答: Build a data layer that matches your DB in a shared assembly.  You can the have each of the business layers reference it (the data layer could be all interfaces to keep implementation separate).  Then build out each of your use cases in the relevant business layers.  You'll likely have a fourth business assembly which contains objects which implement shared use cases.</p>

Title: What's the correct way to architect multiple ASP.NET MVC applications dealing with similar data?

Body:
I am currently working to replace a bunch of legacy applications. The first one is getting close to being released, which will mean I will be starting the second one.

Each application deals with a specific part of a sales process. Initial customer acquisition (with potentially very little customer data, with a lot of it being optional intentionally), through to actual quote/sale process, and then on to an application looking at how to get customers back into the beginning of the sales acquisition process.

Now I have built applications for many years, used different techniques, all with their pro's/con's, without really knowing the preferred way.

One large database, re-used by all of the applications to share customer data etc. This can make it a lot of work to maintain, having loads of developers all working on the same schema and services, having a dependency to most likely have to release all applications at the same time following changes

Database split per area (Customer, Sales, Business Hierarchy etc), gives a logical split, but they are all still used by all of the applications, yet joins for data across databases can cause problems unless you do cross-database joins/link servers etc

Each individual application has it's own set of databases. This makes development of each application a lot quicker and simpler. Yet also gives a lot of duplication in data copying it across each application. Then any changes in data needs synced somehow with other databases. For some areas you could open up a web API to get to some data between them, but a lot of the time you may end up having to read from one database to use that info to get more info from another etc rather than doing simple quick joins.

Can anyone give some info on the correct way? Yes, things can possibly be subjective, but I'm sure one of these ways would be more recommended than the other.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
Both!

I do a lot of development in CakePHP, and I use either CamelCase or $underscored_vars, in the following fashion (even outside CakePHP Projects):

filenames — /lowercased_underscored.php Typical, but worth mentioning.

classes —  class CamelCase extends ParentObject.  Note that, when using CamelCase, the initial character is not lowercase.  I find camelCase to look really weird.

variables — $are_variables_underscored === TRUE;

variables that hold instances — $CamelCase = new CamelCase();

array keys — $collection['underscored_keys'];

constants — I think everyone can agree that constants should be ALL_CAPS_AND_UNDERSCORED.

methods — $CamelCase->foo_method_underscored();

static methods — CamelCase::just_like_regular_methods();


答:
I'm answering the point of the broader question and not focusing particularly on this particular implementation:

comments are bad.  See the thousands of questions and answers here about that.  Just search.

well named methods are better than comments

extracted methods are much easier to unit test

extraction at this point will allow for any locally scoped changes you then want to make.

if the extracted method is called from more than one place this will remove the duplication.

The question though is when is enough?

For that I would focus on whether this really an atomic operation and whether it's only done in this piece of code.  You can go 'too extreme' in this operation and turn a simple 10 lines of code into 8 different methods with different nesting levels that is really hard to read.

Title: Creating one-line method for the single purpose of self-documenting code

Body:
Given the following two snippets:

Snippet 1:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //If node changed currentId reset it to the original.
    data.setCurrentId(originalId);
}
</code>```

Snippet 2:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    resetCurrentIdIfChangedByNode(data, originalId);
}

private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

In both cases it is not be known whether node.execute() changes the currentId or not.

Does the one-line method in Snippet 2 make the code more readable? Or is it preferable to use comments as in Snippet 1?

EDIT: I understand that node has side effects. This is why I'm resorting to creating a method that explains (or tries to explain) that the data.currentId might be changed by node. Depending on which subclass of AbstractNode is being used, it might be changed or not.

EDIT 2: The reason there is no if statement around the reset in Snippet 2 is that it would be pointless, since the result would be the same whether we check or not.

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

same result as

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    if(data.getCurrentId() != originalId)
    {
        data.setCurrentId(originalId);
    }
}
</code>```


问:
What is the origin of the phrase "extirpated as a potential munition"
I recently came across this statement in the Perl documentation:

```<code> extirpated as a potential munition
</code>```

derived from the sentence:

"Creates a digest string exactly like the crypt(3) function in the C library (assuming that you actually have a version there that has not been extirpated as a potential munition)."

Is this not a very odd phrase to use in regards to a function becoming defunct or does it have some special meaning involved within cryptography?

答:
Before the rise of personal computing, the most significant use of cryptography was to keep war plans secret.  Keep in mind that programmable computing as we know it essentially began with Turing's work breaking German codes in World War II, and the age of personal computing was beginning just as the Cold War was drawing to a close--not that anyone knew it at the time!

If you had an algorithm that could encrypt data such that the government couldn't read it, and it fell into the hands of the Russians, they could use this encryption to safely coordinate first-strike plans against the West, potentially setting up a nuclear attack.  This was a very real fear back in the day, and even after the Soviet Union fell, neither the nuclear weapons nor America's enemies magically went away.

Therefore, the government classified strong encryption technology as "munitions", and exporting it was regulated under the same rules as military-grade weaponry.  This lasted up until the dawning of the World Wide Web and the rise of e-commerce, which required strong encryption to foil eavesdropping and fraud, and enough of the Internet made enough of a stink about it that the rules were changed, in the name of economic progress.


问:
When do programmers use code first approach?
This is just not related to asp.net mvc but rather related all the mvc frameworks that support code first approach. One of the advantages I often see on asp.net mvc and tutorial blogs is that it supports code first approach. I'm work as a .net consultant and on the various projects( old and new) I have never seen anyone use code first approach. Just because I didn't see doesn't mean does not mean people don't use code first approach. One of the main reasons my team never favored it is because stored procedures are faster than using orm like entity framework. I understand that code first approach will make writing data acess logic a little easier. from my expirence I would never use code first when I'm working on a complex project. By complex project I mean cross database queries and security rights etc. Am I right with my assumption? If so what kind of projects would one use code first approach?</p>

答:
If a team has:

A DBA,

Or a developer who is even slightly knowledgeable about databases,

then the team will be inclined to avoid code-first approach. This is the same as using WYSIWYG editors when your team knows HTML: while the job can be done with a WYSIWYG, you still need to do it by hand if you need decently written, maintainable code.

This has nothing to do with stored procedures in particular (and I find your claim about the performance overrated), but rather with the quality of the design itself. Of course, the number of features one can use (stored procedures, computed columns, FILESTREAM, etc.) matters too.

Another aspect to consider is that the database schema is just one of the aspects to consider for a fully-featured product. Another aspects could be the backup strategy, federation (load balancing) and the overall long-term maintenance of the server.

On the other hand, code-first approach is great:

For teams with no DBAs and no people who know how databases are designed. They can either try to do it by hand (and fail), or let the tool do the job. Even if the tool won't do a great job, it will still be not much worse (or even better) compared to what an inexperienced programmer can do when designing a database schema.

For tiny projects. If I am doing my personal website which will be used by me and a few of my friends, there is really no need to use indexes or chose carefully how tables are linked together. Any design (or lack of thereof) will work.

For prototypes. The goal is not to do well, but to do fast. If code-first approach means that you can finish the feature in six hours instead of seven, this is a great benefit. This is where code generators (including ones which produce lousy code) or code-first ORMs are particularly valuable: they let you to craft a thing very quickly and focus on the details which matter (the object of a prototype) by abstracting the details which don't (the database schema).


答:
I always use code first and would never think about data first unless I have to integrate with an existing database. Why?

Instead of starting by figuring out what database looks like, I start by figuring out what my application does.

I don't have to reconcile my up-front database design with the functionality, web pages, API's etc. Instead, I do all of the design activities together.

The cost of "pre design" can be high especially if something has changed in the overall goals of the application that causes the database model to change significantly.

Title: When do programmers use code first approach?

Body: This is just not related to asp.net mvc but rather related all the mvc frameworks that support code first approach. One of the advantages I often see on asp.net mvc and tutorial blogs is that it supports code first approach. I'm work as a .net consultant and on the various projects( old and new) I have never seen anyone use code first approach. Just because I didn't see doesn't mean does not mean people don't use code first approach. One of the main reasons my team never favored it is because stored procedures are faster than using orm like entity framework. I understand that code first approach will make writing data acess logic a little easier. from my expirence I would never use code first when I'm working on a complex project. By complex project I mean cross database queries and security rights etc. Am I right with my assumption? If so what kind of projects would one use code first approach?</p>


问:
C# Real time HMI (Human Machine Interface)
I came across a discussion of real time programing on this site which seemed to have some good insights.  I would like to get your thoughts on my next project.

I plan to write a C# HMI for a machine which runs a short, about 30 second production cycle. There would be some setup functions that would need to look real time to the operator but the important part is the production cycle. In the production cycle, as much as possible, the controller would directly read all the inputs and control the servo motors and outputs according to parameters down loaded before the cycle. If the real time response lapses between cycles no problem.

My plan is to have a thread which reads the status from the controller and may send commands to the controller if needed, but avoids anything, like updating the screen, that might block it’s execution. A timer which gets status information from the thread then updates the on screen information and puts up error message boxes as needed. The original thread would respond to the on screen controls. I expect some sort of synchronization object will be needed to control passing data from the thread to the timer. As I understand C# the timer would share time with the original thread and could block its execution. I’m not sure if that could happen or if it would be good or bad?

What problems can you see in this plan, what should I look out for, any place I can look at other peoples work, and is there a better way?

BTW: I don’t buy many lottery tickets and I don’t drink much hard liquor so moving to the mountains and setting up a still is not yet a viable better way for me.

Thanks for your time

I agree that C# will never give true real time. I am just asking how people make the best of what C# can do.

答:
I can tell you for certain that you will not ever achieve hard real time (and I seriously doubt you can do soft real time) with C# and the standard .NET environment.

I develop machine vision inspection systems using C# and we have offloaded all of the real-time requirements for product tracking and sensor input, etc. to a PLC (specifically a B&R real time soft-PLC)

What you will find if you attempt to do real time with .NET is that all of a sudden there will be a chunk of time that your system is simply doing "nothing". This is due to mostly garbage collection in .NET but can also be due to any number of underlying Windows tasks going on in the background (disk management, checking for updates, etc). We fondly refer to this as "Windows is licking itself". Like a dog licking its...errr....self, it isn't doing anything useful, but what it is doing is more important than what you want it to do.


问:
How to make support for bindings for a scripting language

Main

I'm making a scripting language using C++. I plan to use it with a simple test game editor. But I have to make a support for bindings to call game engine's nodes' methods to update positions, rotations, etc.

What are the main approaches for this?

The game engine I plan to use also supports lua, so maybe I can also use this fact.

Details

The problem I have faced lies in the fact of how can I call library C++ object methods within a script. English is not my native language and the lack of knowledge in that sphere prevents me from making a good query on the topic. So I don't know what to search. Google shows me information on how to make bindings to some scripting languages not the fundamentals by search phrases like "how to make bindings support to a scripting language", "scripting bindings".

At this time I came up to the following things. I have to inherit all objects that will be used in script from a service class, ex. CLangObject. With its help I can identify the object's type within a C++ library objects' methods. Then I have to define the most general pointer to method types. I have also define a callback service class to pass it to a byte machine when C++ library method returns value. The game engine I want to use has bindning to lua, so maybe I can use its LuaObject and LuaCallback classes. At this time I don't know if this approach will lead to a normal result.

答: You could build the scripting language into the engine so that the engine can take some file formatted in your language and invent some grammars for your program to compile these script files during run-time and use a stack to push method calls, variable declarations etc. like a normal running program though I think it limits your scripting language to only the methods your engine is written with, unless you create good grammars for the language that also binds to the original language the engine is written in.</p>


问:
Robot in a grid
This was recently asked to someone I know.

A robot has to move in a grid which is in the form of a matrix. It can go to

A(i,j)--> A(i+j,j) (Down)

A(i,j)--> A(i,i+j) (Right)

Given it starts at (1,1) and it has to go to A(m,n), find the minimum number of STEPS it has to take to get to (m,n) and write

```<code>    public static int minSteps(int m,int n)
</code>```

For instance to go from (1,1) to m=3 and n=2 it has to take (1, 1) ->
  (1, 2) -> (3, 2) i.e. 2 steps

Unfortunately for my friend answered it as though it was the other well known question of finding number of unique paths.

How to solve to find min number of steps taken to reach m,n?

答:
Here's one - and I was told this is on the lines of what the interviewer was looking for

1.) If m > n, then m-=n i.e. he could only have come from (m-n,n)

2.) Else if m < n, then n-=m i.e. he could only have come from (m,n-m)

and this is followed by the edge cases and housekeeping

```<code> int minSteps(int m, int n)
        {
            if(m<=1 || n <=1) return -1;
            int count = 0;
            while(abs(m-n) && m>=1 && n>=1)
            {
                if(m>n)
                    m=m-n;
                else n = n-m;
                count++;
            }
            if(m==1 && n==1)
                return count;
            else return -1;
        }
</code>```

This is taken from here

Title: Robot in a grid

Body:
Here's one - and I was told this is on the lines of what the interviewer was looking for

1.) If m > n, then m-=n i.e. he could only have come from (m-n,n)

2.) Else if m < n, then n-=m i.e. he could only have come from (m,n-m)

and this is followed by the edge cases and housekeeping

 int minSteps(int m, int n)
        {
            if(m<=1 || n <=1) return -1;
            int count = 0;
            while(abs(m-n) && m>=1 && n>=1)
            {
                if(m>n)
                    m=m-n;
                else n = n-m;
                count++;
            }
            if(m==1 && n==1)
                return count;
            else return -1;
        }

This is taken from here


答:
The basic thing to grasp is that code relates to a single use case whereas data can relate to several use cases.

So while code first is good for a simple system with a few use cases anything complex with multiple use cases is going to need a decent data model to ensure that all use cases are covered.


问:
When are nonblocking read or receive operations useful?
Regardless of library, language, or spec, asynchronous send/write operations make sense to me, because code later in the execution path may not have any dependency upon the success or failure of the write operation.

However, asynchronous receive/read operations are not motivated for me.

Can anyone suggest specific situations or general patterns where async message receipt is useful?

Context

My question is prompted by the MPI specification, but the more general the answer the better.  Specifically, there are blocking calls to communicate between processes or machines:

MPI_Send(...)
MPI_Recv(...)

and there are analogous nonblocking calls that take an additional parameter MPI_Request * parameter to handle the send/receive operations asynchronously:

MPI_Isend(..., &request)
MPI_Irecv(..., &request)

答:
The main reason async read is handy if you still have other work to do or more often because there is another input source you also need to listen to.

For example a GUI you need to listen to the user input besides getting the image from the disk.

Without asynchronous IO you would need to start a new thread every time you start to read something with a blocking API. This won't scale well.

Servers can have several connections active at a time especially when it also communicates with a database and fileserver.


问:
How to determine whether two trees (not necessarily binary) are isomorphic
Two ordered trees T' and T'' are said to be isomorphic if one of the following holds:

◦ both T' and T'' consist of a single node

◦ both T' and T'' have the same number k of subtrees, and the ith subtree of T' is
isomorphic to the ith subtree of T'', for i = 1, 2, ..., k.

I've made an attempt to come up with the following algorithm for binary trees, however the question does not say anything about the tree being binary. What kind of algorithm could determine if two non-binary trees are isomorphic or not?

```<code>bool isomorphic(node p, node r)
     if (p = null & r = null) return true
     if (p = null || r = null) return false //they don’t have the same number of subtrees
     else return (isomorphic(p->leftchild, r->leftchild) && isomorphic(p->rightchild, r->rightchild) || (isomorphic(p->leftchild, r->rightchild) && isomorphic(p->rightchild, r->leftchild))
</code>```

答: What Giorgio said. Just change the function so that it iterates over a list of children instead of checking only a left and a right child (assuming that's how the non-binary tree you're interested in is implemented).</p>


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答:
I get the books readers on my PC. Some have had issues with formating, but I found Amazon will give you a prompt refund if this is the case. I've used Microsoft eReader and Adobe's reader. I thought Kindle was lacking in some technical book choices. I carry a laptop anyway on the commute so I don't need an extra device. Can get the same books on my work computer if needed.

What I really hate is their inability to let you copy and paste. I was taking notes into Evernote and found this to be a pain.

Title: eBook editions of programming books


问:
The dream of declarative programming
Why hasn't the dream of declarative programming been realized? What are some concrete obstacles getting in the way? For a simple example why can't I say

```<code>sort(A) is defined by sort(A) in perm(A) && asc(sort(A))
</code>```

and automatically get a sorting algorithm out of it. perm means permutations and asc means ascending.

答:
We have a difference in declarativeness of programming languages that is put to good use in the verification of digital logic.

Normally digital logic is described at the register transfer level (RTL) where the logic level of the signals between registers is defined. To check that we are increasingly adding properties defined in a more abstract and declarative manner.

One of the more declarative languages/language subsets is called PSL for Property Specification Language. When testing an RTL model of a multiplier in which, for example all the logic operations of shift and add over multiple clock cycles needs to be specified; you can write a property in the manner of assert that when enable is high, this output will equal the multiplication of these two inputs after no more than 8 clock cycles.
The PSL description can then be checked together with the RTL in a simulation, or the PSL may be formally proved to hold for the RTL description.

The more declarative PSL model forces one to describe the same behaviour as the RTL description but in a sufficiently different way that can be automatically checked against the RTL to see if they agree.

Title: The dream of declarative programming


问:
Distinguishing Classes: How to catch system behavior in classes (Library System Case)
Suppose a Library System. if I think about Data, I can just distinguish Book, Member classes or at most Author or Publisher... (Are they only classes?), but I have some use cases, scenarios (Borrow, Deliver, Reservation...). Just I don't know when and how to distribute them in the mentioned classes, or should I introduce new classes

If I think of Single Responsibility and Separation of Concerns, they suggest me many other classes for any responsibility like Borrow for Borrowing, BookRepository to save and reserve book, etc ....

I would like to know how do you find the classes of this specific example or how do you use the Single Responsibility principle to find the classes.

The answer of this quesiton has some good points but it lacks a clarifying example.

答:
There is a very simple analysis technique in which you write down the use cases in plain text and extract nouns and verbs. The nouns are likely to be essential concepts in your domain (so probably classes), the verbs are likely actions to be taken in the domain (so probably methods). This rule is not written in stone but it can help you get going. When I took courses in Object-Oriënted analysis they started us off on this method but it is something that you learn to do 'by heart' without thinking too much about it with some practice.

Let's look at an example*

A customer can make a reservation for a book in a library. To do this, he must check the availability of the book in the library. If the book is available for the period the user wishes to lend it he can make a lending with the library to lend the book for a given period.

Relevant Nouns

Customer

Reservation

Book

Library

Availability

Period

Lending

Relevant Verbs

Make (reservation)

Check (availability)

Make (lending)

This would lead me to a system where I have a Book class that belongs to a Library class. The Library class would also contain a list of Reservations and Lendings. On the Library there would be a method makeReservation that creates a Reservation for a Book during a Period. There would also be a makeLending that creates a Lending for a Book during a Period. Finally, a checkAvailability-method would be present that returns information on the availability of a Book during the Period.

The way you go about this is mostly a matter of personal preference. There are some guiding principles you could take into consideration while designing this (SOLID and the Law Of Demeter come to mind) so in that sense there are 'good' and 'less good' solutions. But if it makes more sense to you for the Book-class to have a Borrow-method that creates a Borrowing object on the book, there is nothing wrong with that.

Things like the Single Responsibility Principle (SRP, the S in SOLID) can help you look at the design you think will work and analyse it. For example, with my proposed design Library violates the SRP as it is responsible for creating reservations, creating lendings AND checking availabilities. By explaining the role of the Library class I can immediately see that I violate SRP and there might be a more optimal design.

Then again, if you were to apply all SOLID principles to the letter you wouldn't be able to write any code...

*Simplified for obvious reasons, in reality libraries would have multiple copies of some books etc...


问:
How can I avoid these nested repetitive ifs?
I'm trying to implement a web interface for a user database. Hosts can create guests for their courses, the guests can get deleted after the course has ended but have to remain in the database for a given amount of time. If a host tries to create a guest that already exists in the database, the following things can happen:

The guest is already active and was created by the same host,

The guest is already active and was created by a different host,

The guest is in deleted state and was created by the same host,

The guest is in deleted state and was created by a different host.

Currently, I'm trying to represent the user state in this enum:

```<code>public enum GuestUserStatus
{
    Unknown = 0,
    NewGuest = 1,

    ActiveSameHost = 10,
    ActiveDifferentHost = 11,

    DeletedSameHost = 20,
    DeletedDifferentHost = 21
}
</code>```

This allows me to switch() on the set user state.

However, to set the user state, I'm currently using repetetive if clauses like these:

```<code>if (queriedUser.GuestDetails.Creator == creator)
{
    if (queriedUser.GuestDetails.State == GuestState.Deleted)
    {
        currentStatus = GuestUserStatus.DeletedSameHost;
    }
    else
    {
        currentStatus = GuestUserStatus.ActiveSameHost;
    }
}
else
{
    if (queriedUser.GuestDetails.State == GuestState.Deleted)
    {
        currentStatus = GuestUserStatus.DeletedDifferentHost;
    }
    else
    {
        currentStatus = GuestUserStatus.ActiveDifferentHost;
    }
}
</code>```

The nested if clauses act on the same condition but with a different outcome.

Is there a way to avoid this? I looked into marking the enum with [Flags] and using powers of 2 as underlying values, but then I couldn't use the switch() anymore.

UPDATE: Please note that I have the same conditions twice and different outcomes to them.

UPDATE2: Trying to address the linked question How to tackle a 'branched' arrow head anti-pattern?: Let's say I implement the accepted answer of that question. That would give me something like this:

```<code> bool activeSameHost = (queriedUser.Guest.Creator == creator && queriedUser.GuestDetails.State != GuestState.Deleted);
 bool activeDifferentHost = (queriedUser.Guest.Creator == creator && queriedUser.GuestDetails.State == GuestState.Deleted);
 bool inactiveSameHost = (queriedUser.Guest.Creator != creator && queriedUser.GuestDetails.State == GuestState.Deleted);
 bool inativeDifferentHost = (queriedUser.Guest.Creator != creator && queriedUser.GuestDetails.State == GuestState.Deleted);

if(activeSameHost) currentStatus = GuestUserStatus.ActiveSameHost;
if(inactiveSameHost) currentStatus = GuestUserStatus.InactiveSameHost;
if(activeDifferentHost) currentStatus = GuestUserStatus.ActiveDifferentHost;
if(inactiveDifferentHost) currentStatus = GuestUserStatus.InactiveDifferentHost;
</code>```

I fail to see the improvement. Sure, the ifs are no longer nested, but the only thing that changed is the complexity moving from the nested ifs to the assignment of intermediate variables.

答:
You can use [Flags] and switch at the same time, simply by defining an alias for the flag combination that interest you.

```<code>[Flags]
public enum GuestUserStatus
{
    Unknown = 0,
    NewGuest = 1,

    NotNew = 2, // I need this to distinguish from the Unknown and NewGuest states.
    Deleted = 4,
    DifferentHost = 8,

    ActiveSameHost = NotNew,
    ActiveDifferentHost = NotNew | DifferentHost,

    DeletedSameHost = NotNew | Deleted,
    DeletedDifferentHost = NotNew | Deleted | DifferentHost,
}
</code>```

However, in such a design I would try to put the NotNew state at 0 instead of Unknown, but I do not know your requirements. (What is wrong with modeling it with two booleans instead?)

Body:
You can use [Flags] and switch at the same time, simply by defining an alias for the flag combination that interest you.

[Flags]
public enum GuestUserStatus
{
    Unknown = 0,
    NewGuest = 1,

    NotNew = 2, // I need this to distinguish from the Unknown and NewGuest states.
    Deleted = 4,
    DifferentHost = 8,

    ActiveSameHost = NotNew,
    ActiveDifferentHost = NotNew | DifferentHost,

    DeletedSameHost = NotNew | Deleted,
    DeletedDifferentHost = NotNew | Deleted | DifferentHost,
}

However, in such a design I would try to put the NotNew state at 0 instead of Unknown, but I do not know your requirements. (What is wrong with modeling it with two booleans instead?)


答:
The trick is to specify the behavior you want in plain language.

"A member borrows a book"

You have two nouns in that sentence. Each noun it is likely to end up as a class-- in your case Book and Member.

There is also the verb "borrows" this will likely end up as a method in one of the classes, and, most likely the subject -- its the member who is doing it so the "borrow" method should be part of the Member class.

Then we come to adjectives the member does the borrowing but a book can be "borrowed" it follows that you should somehow record the "borrowed" status in the book class maybe even who did the borrowing.

Finally in real life things are made up of other things. It may be enough for you to store the publishers name as an attribute of the Book class, but, if your library does purchasing then you will probably end up with a Publisher class, in your book class you will then need a reference to the Publisher class.

Title: Distinguishing Classes: How to catch system behavior in classes (Library System Case)

Body:
Suppose a Library System. if I think about Data, I can just distinguish Book, Member classes or at most Author or Publisher... (Are they only classes?), but I have some use cases, scenarios (Borrow, Deliver, Reservation...). Just I don't know when and how to distribute them in the mentioned classes, or should I introduce new classes

If I think of Single Responsibility and Separation of Concerns, they suggest me many other classes for any responsibility like Borrow for Borrowing, BookRepository to save and reserve book, etc ....

I would like to know how do you find the classes of this specific example or how do you use the Single Responsibility principle to find the classes.

The answer of this quesiton has some good points but it lacks a clarifying example.


问:
Limiting complexity in JPA programs Java/Hibernate
I've been working on a new application for some months now. It's my first big JPA program, and is still in the early stages. However, the complexity of my JPA object tree is becoming a growing problem.

For instance I have an object tree of Users, who have Companies, Divisions, Related Divisions, Currencies, Local Currencies, Currency Exchange Rates. At lower levels, things are not so bad. For instance if I pull out Currencies, matters are easier to cope with. But for high level, tree topping elements like a list of Users, my object tree has become horrific.

Now, a small bug has slipped into the JPA object tree meaning an important join table is being overwritten by one of my entities. I hope I can find the bug, but what I'd like advice on, is how to avoid this rapidly burgeoning complexity.

Thanks!

答:
My approach is:

prefare unidirectional relations (eg. when loading role, you don't usually need everyone with that role, and if you need it for user management, you can quary for it)

prefare lazy loading, so you don't manipulate huge graphs by accident

if you don't need entity as result of query, return non entity object (via select new).

JPA is not replacement for good analysis (don't just load object and traverse it, know what you need and load it)

try to structure your objects in way where there is no object from which it is possible to get anywhere. instead of A <- B -> C use A -> B <- C. Information for queriing is there, but object graph is broken into parts, so you have complexity closer to sum of parts than multiplication of parts.

make cleer divide between code in which entities are live and where changes does not automaticaly go into database.


问:
Why is there only code review?
In my team I have applied a culture of code review and feature review.

The code might look great, written spectacularly, however the feature might not work.

It seems to me as 2 different scopes for review. While code reviews require a very technical and in depth knowledge, feature review requires only familiarity with the spec.

When I google code review I get a bunch of results.
However can't find anything on any other kind of review.

A brief reference can be found at https://softwareengineering.stackexchange.com/a/92417/95463 where BillThor says "You were asked to review the code do so, it is not the same as testing it"..

Do you use other kind of reviews and what are their goals and process?

We use a feature review where someone is actually running the tests and the feature manually and verifies it is intuitive and applies to spec.

答:
Code review is just the first gateway to quality - not the only one. Its a very quick and easy way to ensure that what is going through to further verification is basically acceptable.

So it is to ensure there are no stupid mistakes, and that it passes whatever standards of code style or guidelines you have - code that looks wildly different to the rest of the codebase is very bad for future maintenance after all. Once this initial hurdle is passed, then you can review whether it works as intended, and performs as intended (such a non-functional feature is always implicitly present in all code changes yet only rarely mentioned as a feature). It can be checked for security processes or passed through static analysis tools.

So code review is just the "low-hanging fruit" of quality checks, that's partly why it gets done first.

Title: Why is there only code review?


问:
How to monitor code review efficiently?
I suspect major code review cover up in my team.
Too many code reviews are merged without any comment.

Seems to me like there's no such thing as a code review without a single comment.

How can I as a team lead properly monitor that my team is doing a proper code review process and how can I help them to maximize the process' benefits?

Update

Thought people might want to know about any update. I tried a lot of suggestions that were given here. most were already in use.
some helped a bit.
However, the problem remained - some people continuously got bad code in when I was not looking.

I found that code review monitoring is not as helpful as giving my team tools to make their code better to begin with.

So I added a library named "jscpd" to detect copy pastes.
The build failed on copy pastes.
That eliminated one problem immediately.

next we are going to try codeclimate.

I am also doing a manual review on old code reviews once a sprint for half a day.
I am converting todos into issues/tickets - as I found out people are writing them, but they are never handled at a later point.
I am also doing meetings with the entire teams to review code when it is appropriate.

in general it feels like we are moving in the right direction.

答: Get a tool, like ReviewBoard or Redmine's codereview plugin. Then each review is created as a task that has to be closed or commented upon by someone (just like a bug ticket). Then you have traceability of who created the review ticket, and who closed it. You can tie review tickets with source code checkins, ie create the ticket from a revision.</p>

Title: How to monitor code review efficiently?


问:
what should be logger's position in the parameter list
In my code I inject a logger to many of my classes through their constructor's parameter list

I noticed that I put it randomly: sometimes it's the first on the list, sometimes last, and sometimes in between

Do you have any preference? My intuition says that consistency is helpful in this case and my personal preference is to put it first so it will be easier to be noticed when it's missing and easier to skip when it's there.

答:
It's worth mentioning, something I have not seen the other answers touch on here, is that by making the logger injected via property or static, it makes it hard(er) to unit test the class. For example, if you make your logger injected via property, you will now have to inject that logger every time you test a method that uses the logger. This means you might as well have it sets as a constructor dependency because the class does require it.

Static lends itself to the same issue; if the logger doesn't work, then your entire class fails (if your class uses the logger) - even though the logger is not necessarily 'part' of the responsibility of the class - although it's not nearly as bad as  property injection because you at least know that the logger is always "there" in a sense.

Just some food for thought, especially if you employ TDD. In my opinion, a logger should really not be part of a testable part of a class (when you test the class, you shouldn't be testing your logging as well).


答: I'm too lazy to pass around a logger object to each class instance. So, in my code, these kinds of things either sit in a static field or a thread-local variable in a static field. The latter is kind of cool and lets you use a different logger for each thread and lets you add methods to turn logging on and off that do something meaningful and expected in a multi-threaded application.</p>


答:
There are some very good answers. I will try to contribute to the discussion.

On the topic of declarative, logic programming in Prolog, there is the great book "The Craft of Prolog" by Richard O'Keefe. It is about writing efficient programs using a programming language that lets you write very inefficient programs. In this book, while discussing the efficient implementations of several algorithms (in the chapter "Methods of Programming"), the author takes the following approach:

define the problem in English

write a working solution that is as declarative as possible; usually, that means pretty much exactly what you have in your question, just correct Prolog

from there, take steps to refine the implementation to make it faster

The most enlightening (for me) observation I was able to make while working my way through these:

Yes, the final version of the implementation is much more efficient than the "declarative" specification the author started with. It is still very declarative, succinct, and easy to understand. What has happened in between is that the final solution captures properties of the problem to which the initial solution was oblivious.

In other words, while implementing a solution, we have used as much of our knowledge about the problem as we can. Compare:

Find a permutation of a list such that all elements are in ascending order

to:

Merging two sorted lists will result in a sorted list. Since there might be sublists that are already sorted, use these as a starting point, instead of sublists of length 1.

A small aside: a definition like the one you have given is attractive because it is very general. However, I cannot escape the feeling that it purposefully ignores the fact that permutations are, well, a combinatorial problem. This is something we already know! This is not a criticism, just an observation.

As to the real question: how to move forward? Well, one way is to provide as much knowledge about the problem we are declaring to the computer.

The best attempt I know of to really solve the problem is presented in the books co-authored by Alexander Stepanov, "Elements of Programming" and "From Mathematics to Generic Programming". I am sadly not up to the task of summarizing (or even fully understanding) everything in these books. However, the approach there is to define efficient (or even optimal) library algorithms and data structures, under the provision that all relevant properties of the input are known in advance. The final result is:

Each well-defined transformation is a a refinement of the constraints that are already in place (the properties that are known);

We let the computer decide which transformation is optimal based on the existing constraints.

As to why it hasn't quite happened yet, well, computer science is a really young field, and we are still coping with truly appreciating the novelty of most of it.

PS

To give you a taste of what I mean by "refining the implementation": take for example the easy problem of getting the last element of a list, in Prolog. The canonical declarative solution is to say:

```<code>last(List, Last) :-
    append(_, [Last], List).
</code>```

Here, the declarative meaning of append/3 is:

List1AndList2 is the concatenation of List1 and List2

Since in the second argument to append/3 we have a list with only one element, and the first argument is ignored (the underscore), we get a split of the original list which discards the front of the list (List1 in the context of append/3) and demands that the back (List2 in the context of append/3) is indeed a list with only one element: so, it is the last element.

The actual implementation provided by SWI-Prolog, however, says:

```<code>last([X|Xs], Last) :-
    last_(Xs, X, Last).

last_([], Last, Last).
last_([X|Xs], _, Last) :-
    last_(Xs, X, Last).
</code>```

This is still nicely declarative. Read top to bottom, it says:

The last element of a list only makes sense for a list of at least one element.
  The last element for a pair of the tail and the head of a list, then, is:
  the head, when the tail is empty, or the last of the non-empty tail.

The reason why this implementation is provided is to work around the practical issues surrounding the execution model of Prolog. Ideally, it shouldn't make a difference which implementation is used. Similarly, we could have said:

```<code>last(List, Last) :-
    reverse(List, [Last|_]).
</code>```

The last element of a list is the first element of the reversed list.

If you want to get your fill of inconclusive discussions about what is good, declarative Prolog, just go through some of the questions and answers in the Prolog tag on Stack Overflow.

Title: The dream of declarative programming

Body:
Why hasn't the dream of declarative programming been realized? What are some concrete obstacles getting in the way? For a simple example why can't I say

```<code>sort(A) is defined by sort(A) in perm(A) && asc(sort(A))
</code>```

and automatically get a sorting algorithm out of it. perm means permutations and asc means ascending.

Body:
There are some very good answers. I will try to contribute to the discussion.

On the topic of declarative, logic programming in Prolog, there is the great book "The Craft of Prolog" by Richard O'Keefe. It is about writing efficient programs using a programming language that lets you write very inefficient programs. In this book, while discussing the efficient implementations of several algorithms (in the chapter "Methods of Programming"), the author takes the following approach:

define the problem in English

write a working solution that is as declarative as possible; usually, that means pretty much exactly what you have in your question, just correct Prolog

from there, take steps to refine the implementation to make it faster

The most enlightening (for me) observation I was able to make while working my way through these:

Yes, the final version of the implementation is much more efficient than the "declarative" specification the author started with. It is still very declarative, succinct, and easy to understand. What has happened in between is that the final solution captures properties of the problem to which the initial solution was oblivious.

In other words, while implementing a solution, we have used as much of our knowledge about the problem as we can. Compare:

Find a permutation of a list such that all elements are in ascending order

to:

Merging two sorted lists will result in a sorted list. Since there might be sublists that are already sorted, use these as a starting point, instead of sublists of length 1.

A small aside: a definition like the one you have given is attractive because it is very general. However, I cannot escape the feeling that it purposefully ignores the fact that permutations are, well, a combinatorial problem. This is something we already know! This is not a criticism, just an observation.

As to the real question: how to move forward? Well, one way is to provide as much knowledge about the problem we are declaring to the computer.

The best attempt I know of to really solve the problem is presented in the books co-authored by Alexander Stepanov, "Elements of Programming" and "From Mathematics to Generic Programming". I am sadly not up to the task of summarizing (or even fully understanding) everything in these books. However, the approach there is to define efficient (or even optimal) library algorithms and data structures, under the provision that all relevant properties of the input are known in advance. The final result is:

Each well-defined transformation is a a refinement of the constraints that are already in place (the properties that are known);

We let the computer decide which transformation is optimal based on the existing constraints.

As to why it hasn't quite happened yet, well, computer science is a really young field, and we are still coping with truly appreciating the novelty of most of it.

PS

To give you a taste of what I mean by "refining the implementation": take for example the easy problem of getting the last element of a list, in Prolog. The canonical declarative solution is to say:

last(List, Last) :-
    append(_, [Last], List).

Here, the declarative meaning of append/3 is:

List1AndList2 is the concatenation of List1 and List2

Since in the second argument to append/3 we have a list with only one element, and the first argument is ignored (the underscore), we get a split of the original list which discards the front of the list (List1 in the context of append/3) and demands that the back (List2 in the context of append/3) is indeed a list with only one element: so, it is the last element.

The actual implementation provided by SWI-Prolog, however, says:

last([X|Xs], Last) :-
    last_(Xs, X, Last).

last_([], Last, Last).
last_([X|Xs], _, Last) :-
    last_(Xs, X, Last).

This is still nicely declarative. Read top to bottom, it says:

The last element of a list only makes sense for a list of at least one element.
  The last element for a pair of the tail and the head of a list, then, is:
  the head, when the tail is empty, or the last of the non-empty tail.

The reason why this implementation is provided is to work around the practical issues surrounding the execution model of Prolog. Ideally, it shouldn't make a difference which implementation is used. Similarly, we could have said:

last(List, Last) :-
    reverse(List, [Last|_]).

The last element of a list is the first element of the reversed list.

If you want to get your fill of inconclusive discussions about what is good, declarative Prolog, just go through some of the questions and answers in the Prolog tag on Stack Overflow.


问:
Global constant values throughout MVC site
My MVC (.NET) has some constant values through out the site, such as the phone number, physical address, email address etc.

I'd like to store this value once, so future updates are easier for when they change their details.

To make my question simpler, I've only focused on phone number.

My question is where and how to store this number and a problem I'm facing with my decision. At the moment, I've chosen to store it in the Global.asax file as a static method, eg

```<code>public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
       //logic
    }

    public static string GetPhoneNumber()
    {
        return "012345 678 910";
    }
}
</code>```

This works very well, in my controller I can add references to this method and assign it to a ViewBag

```<code>  public ActionResult Contact()
  {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
  }
</code>```

As per many sites, the phone number will be visible at the top of every page and as such, placing it in the _Layout.cshtml is logical.

The problem I have is there is no controller (not that I know) for the _Layout.cshtml and the only way I can pass the value is to have a ViewBag.Phone set up for every view, EG

```<code>public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }
</code>```

This is messy and smelly but I have no idea how I can improve this.

Should I be storing my global variables in a different place or is there a better approach for this as I'm sure this is a common problem.

答:
In Global.asax.cs

```<code>public class MvcApplication : System.Web.HttpApplication
{
  ...
  public const string PhoneNumber = "01234 567890";
  ...
}
</code>```

In _Layout.cshtml

```<code><div>Phone number: @MvcApplication.PhoneNumber</div>
</code>```

Body:
In Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
  ...
  public const string PhoneNumber = "01234 567890";
  ...
}

In _Layout.cshtml

<div>Phone number: @MvcApplication.PhoneNumber</div>


答:
I dislike posting one-line answers, but this one seems appropriate:

Participate in the process.

Title: How to monitor code review efficiently?

Body:
I suspect major code review cover up in my team.
Too many code reviews are merged without any comment.

Seems to me like there's no such thing as a code review without a single comment.

How can I as a team lead properly monitor that my team is doing a proper code review process and how can I help them to maximize the process' benefits?

Update

Thought people might want to know about any update. I tried a lot of suggestions that were given here. most were already in use.
some helped a bit.
However, the problem remained - some people continuously got bad code in when I was not looking.

I found that code review monitoring is not as helpful as giving my team tools to make their code better to begin with.

So I added a library named "jscpd" to detect copy pastes.
The build failed on copy pastes.
That eliminated one problem immediately.

next we are going to try codeclimate.

I am also doing a manual review on old code reviews once a sprint for half a day.
I am converting todos into issues/tickets - as I found out people are writing them, but they are never handled at a later point.
I am also doing meetings with the entire teams to review code when it is appropriate.

in general it feels like we are moving in the right direction.