问:
Why after each restart, my local .NET sites take time to load for the first time?
I'm developing sites based on .NET platform. I usually deploy these sites on my local IIS, so that I can test them and see their functionality before going live. However, each time I restart windows, it seems that sites take a long time to run for the first time.

I know about JIT and I'm also aware of this question, but it doesn't answer my question.

Does JIT happens every time you restart windows? Is it related to creation of w3wp.exe process? Why sites are so slow for the first request after each restart?

答: IIS has an annoying (sometimes) feature for low traffic websites. It recycles unused worker processes – which cause the first user to the site; sometimes extremely long delay (30+ seconds). http://dotnettimes.wordpress.com/2014/03/24/fixing-slow-initial-load-for-iis-web-site/</p>


问:
Reason for (post/pre) increment operator in Java or C#
Recently, I've stumbled across question about predicting the output of code which heavily uses post/pre increment operators on integers. I am experienced C programmer, so I felt like at home, but people made statements that Java just blindly copied that from C (or C++), and that this is an useless feature in Java.

That being said, I am not able to find good reason for that (especially with keeping in mind the difference betwen post/pre forms) in Java (or C#), because it's not like you will manipulate arrays and use them as strings in Java. Also, it was long ago when I last looked into bytecode, so I don't know if there's a INC operation, but I don't see any reason why this

```<code>for(int i = 0; i < n; i += 1)
</code>```

could be less effective than

```<code>for(int i = 0; i < n; i++)
</code>```

Is there any particular part of the language where this is really useful, or is this just a feature to bring C programmers in town?

答:
I use sometimes the postfix increment in return statements. E.g. consider this:

```<code>//Java
public class ArrayIterator implements Iterator<T> {
   private final T[] array;
   private int index = 0;
   public ArrayIterator(T ... array) {
      this.array = array;
   }

   public T next {
      if (! hasNext()) throw new NoSuchElementException();
      return array[index++];
   }
   ...
}
</code>```

You can't do this with index += 1. So at least the postfix version can save you now and then some lines.

That said, these operators are indeed not necessary, and may confuse people. I know Scala decided against these operators (you have only +=  and -=, as you suggested), and due to the more "high-level" approach I don't really miss them there. I hope Java develops (more slowly) in the same direction.

However Java has a bunch of other operators you don't see very often "in the wild" (did you ever use ^= or >>>= ?), and nobody cares.

ContentLicense: CC BY-SA 3.0

Body:
I use sometimes the postfix increment in return statements. E.g. consider this:

//Java
public class ArrayIterator implements Iterator<T> {
   private final T[] array;
   private int index = 0;
   public ArrayIterator(T ... array) {
      this.array = array;
   }

   public T next {
      if (! hasNext()) throw new NoSuchElementException();
      return array[index++];
   }
   ...
}

You can't do this with index += 1. So at least the postfix version can save you now and then some lines.

That said, these operators are indeed not necessary, and may confuse people. I know Scala decided against these operators (you have only +=  and -=, as you suggested), and due to the more "high-level" approach I don't really miss them there. I hope Java develops (more slowly) in the same direction.

However Java has a bunch of other operators you don't see very often "in the wild" (did you ever use ^= or >>>= ?), and nobody cares.


问:
Strategies to troubleshoot an error that only happens on a specific device
As an Android developer, the target market I create apps for is very fragmented. While I can specify certain requirements - e.g. my app only supports Android version x.x or above, sometimes errors may occur that are only evident on one specific phone model.

Are there any strategies to handle device-specific errors, without buying the phone in question? We maintain a suite of phones for testing, but can't afford to go out and buy a new phone when 2 or 3 users report that there's a bug that only occurs for their model of phone.

I'm sure other Android developers have encountered similar issues in the past, and I'm curious what cost-effective strategies are available to help squish device-specific bugs.

Update to add a few details:

I use Bugsense to capture bug reports, so whenever exceptions are thrown I will know the model of the phone, the stack trace, the number of times it has happened to my users, and a few other details.

The users may be located in different countries, so I can't assume I'll ever be able to borrow their phone.

Imagine a scenario like this: 100 users have installed the app, but three people complained that a button doesn't work properly when pressed. None of the models of phone I have for testing experience the problem. There doesn't appear to be an emulator for the problem phone model.

答:
Years ago, I used to run into the same problem developing software for Palm devices.  There are a couple of obvious strategies:

Having users help with the testing - have a beta testing program, have your app give good information on errors, and have a good way to report bugs.

Using device-specific emulators

Both are quite limiting, though.  There is no surefire substitute for having the actual device.

One interesting thing I came across is AppThwack, a company that lets you remotely test hundreds of real Android devices.  I have no experience with this personally, but it looks promising (it's also a strong indication that there's no easy, cheap answer to your problem).


问:
is there a way to leave notificationManager and alarmManger alive even when the app is closed?
how would you recommend for me to design an android app where i want it to

1) send location update every 10 minutes

2) to show push notification

I want both actions be available even when the app is closed.

Here i might ask for your explanation what "closed" states an app can be in?

a) removed from recent tasks stack - close the whole process including its services ?

b) forces closed - close the whole process including its services ?

c) other?

I was using

1) alarm manager that sends a pending intent to a broadcast receiver.

2) notification manager

I have tried to register all manager using ApplicationContext instead of Current-Activity context. Now both actions work even after user remove the app from the "recent tasks" stack.

but I'm not sure about the "closed" states so I might be missing something.

答:
Actually, I'm not 100% sure what you're asking but:

If you register a PendingIntentto the AlarmManager you can rely on the system to deliver your intent.

If you registered the BroadcastReciever in your app's Manifest, the code in the Receiver will be executed (Note: always consider doing the actual logic in an IntentService, since BraodcastReceivers only have about 5 seconds to perform their work!).
Simply put your call to the NotificationManager here.

If you registered the LocationListener using the ApplicationContext it will receive the location updates until the user "force closes" your app. But you could schedule another Alarm that registers the LocationListener again.

But keep in mind that you should keep the location updates on a moderate level - it drains battery.

As for your question about the "closed" states:

An app is not running. It was never started, force closed by the user or crashed.

The app is not visible. The UI is "closed" but the process is still running. This happens if someone hits the back button and the app closes. The system might close it completely if it needs the memory (point 1).

There are probably more cases, but these are the usual ones.

If the AlarmManager calls to your BroadcastReceiver and the Type is RTC_WAKEUP your App will be started if it was closed before.


答:
is this just a feature to bring C programmers in town

It is surely a feature "to bring C (or C++) programmers in town", but using the word "just" here underestimates the value of such a similarity.

it makes code (or at least code snippets) easier to port from C (or C++) to Java or C#

i++ is less to type than i += 1, and x[i++]=0; is much more idiomatic than x[i]=0;i+=1;

And yes, code which heavily uses post/pre increment operators maybe hard to read and maintain, but for any code where these operators are misused, I would not expect a drastic increase in code quality even when the language would not provide these operators. That's because if you have devs which don't care for maintainability, they will always find ways to write hard-to-understand code.

Related: Is there any difference between the Java and C++ operators? From this answer one can deduce that any well-defined operator behaviour in C is similar in Java, and Java does only add some definitions for operator precedence where C has undefined behaviour. This does not look like coincidence, it seems to be pretty intentional.

Title: Reason for (post/pre) increment operator in Java or C#

Body:
Recently, I've stumbled across question about predicting the output of code which heavily uses post/pre increment operators on integers. I am experienced C programmer, so I felt like at home, but people made statements that Java just blindly copied that from C (or C++), and that this is an useless feature in Java.

That being said, I am not able to find good reason for that (especially with keeping in mind the difference betwen post/pre forms) in Java (or C#), because it's not like you will manipulate arrays and use them as strings in Java. Also, it was long ago when I last looked into bytecode, so I don't know if there's a INC operation, but I don't see any reason why this

```<code>for(int i = 0; i < n; i += 1)
</code>```

could be less effective than

```<code>for(int i = 0; i < n; i++)
</code>```

Is there any particular part of the language where this is really useful, or is this just a feature to bring C programmers in town?


答:
I've built many languages over the years, mostly special-purpose.
What happens is you have a large audience, and they all have expectations.
In considering each feature, you have to weigh the benefit of the feature against the cost of possibly violating expectations.

One that I personally had to backpedal on was integer division, which normally truncates downward, right?
Like 3 / 2 = 1.5 = 1, right?
Well, way back in the early days of Fortran, somebody decided -3 / 2 = -1.5 = -1 (not -2).
In other words, if the dividend is negative and the divisor is positive, it should truncate up.
Note what this implies - in that case the remainder is negative.
That violates the usual assumption that remainder = modulus.
If you're doing graphics, with integer coordinates, this can lead to all kinds of trouble.
SO, in the language I simply had integer division truncate downward all the time, and say so in the doc.

And SO, guess what happened? All h*** broke loose. The language had a bug in integer division!

It did no good to say the old way was broken.
It was easier to change it than to argue it.

So to answer your question, in languages like C# and Java, it's simply easier to include the ++ operators (which I personally like) than to explain why not.


问:
Collection vs data structure vs aggregate
I know three terms that have to do with storing objects or data. I'm not sure I understand the exact differences between the terms. Please confirm if what I'm about to write is accurate.

A data structure is a group of data types or objects of the same type, grouped together in some formation.

A collection is the same as a data structure (I don't mean a Java Collection, I mean a collection in the more general meaning).

An aggregate is an object containing a collection or data structure, providing an interface to communicate with the inner data structure. For example, the object someContainer, which contains an inner ArrayList, is an aggregate because it contains a data structure, encapsulates it, and provides an interface to manipulate it.

Is all of this accurate?

答:
A Data Structure is a computer science term for some way of ordering data, and how you can store/retrieve data from it.

A Collection is a Data Structure which can hold an arbitrary number of objects. There are many types of collections, differentiated by their data organization and by their store/retrieve algorithms, giving different complexity in different use-cases. For example:

an Array has a random access read (which means that if you know at what index you item is, you can retrieve it with complexity O(1)), but for adding a new item beyond the capacity of the array, you need to copy it to an array with double capacity, giving a worst case of write of O(n).

a Linked list, on the other hand, doesn't have random access, meaning that you need O(n) for retrieving an object, but adding an element to it is in O(1).

An Aggregate function is a database term for taking a vector data (which is an arbitrary number of items) and by using some operation (addition, average, etc.) creating a scalar (which is a single item, or a fixed number of items) result. Examples may be count, sum, average, max. One feature of aggregate functions is that it does not retain whole the information it receives, but keeps only some aspect of it.


问:
Is open-sourcing previously-commercial engines a smart move?
I saw that the Unreal Engine is going open-source on github (see link1 and link2) and that made me wonder: "is open-sourcing a previously commercial engine a smart move?"

What's the benefit to Epic Games in open-sourcing their core code in this manner?
How can they not be concerned about people stealing parts of it just because they put a copyright and license statement on the code?

It seems like there has to be a catch.  How does releasing their source code benefit Epic Games?

答:
You seem to misunderstand a key part: the unreal engine remains a commercial engine. This means that they will still get the licensing fees from every developer and each game sold. The EULA even specifically states that you can't share the source with anyone that isn't also a licensee.

The major benefit is that there are now programmers that are paying you to get the chance to upgrade the engine.

As for discovering if part of the engine was used in another project, I'll refer to this question. Mainly embedded string and residual debug information is key part in discovering illicit use of open source parts.


问:
What are good unit tests to cover the use case of rolling a die?
I'm trying to get to grips with unit testing.

Say we have a die which can has a default number of sides equal to 6 (but can be 4, 5 sided etc.):

```<code>import random
class Die():
    def __init__(self, sides=6):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)
</code>```

Would the following be valid/useful unit tests?

test a roll in the range 1-6 for a 6 sided die

test a roll of 0 for a 6 sided die

test a roll of 7 for a 6 sided die

test a roll in the range 1-3 for a 3 sided die

test a roll of 0 for a 3 sided die

test a roll of 4 for a 3 sided die

I'm just thinking that these are a waste of time as the random module has been around for long enough but then i think if the random module gets updated (say i update my Python version) then at least i'm covered.

Also, do I even need to test other variations of die rolls e.g. the 3 in this case, or is it good to cover another initialized die state?

答:
At the risk of swimming against the tide, I solved this exact problem a number of years ago using a method not so far mentioned.

My strategy was simply to mock the RNG with one that produces a predictable stream of values spanning the entire space. If (say) side=6 and the RNG produces values from 0 to 5 in sequence I can predict how my class should behave and unit test accordingly.

The rationale is that this tests the logic in this class alone, on the assumption that the RNG will eventually produce each of those values and without testing the RNG itself.

It's simple, deterministic, reproducible and it does catch bugs. I would use the same strategy again.

The question does not spell out what the tests should be, just what data might be used for testing, given the presence of an RNG. My suggestion is merely to test exhaustively by mocking the RNG. The question of what is worth testing depends on information not provided in the question.


答:
What is a Die if you think about it ? - no more than a wrapper around random. It encapsulates random.randint and relabels it in terms of your application's own vocabulary : Die.Roll.

I don't find it relevant to insert another layer of abstraction between Die and random because Die itself is already this layer of indirection between your application and the platform.

If you want canned dice results, just mock Die, don't mock random.

In general, I don't unit test my wrapper objects that communicate with external systems, I write integration tests for them. You could write a couple of those for Die but as you pointed out, due to the random nature of the underlying object, they will not be meaningful. In addition, there's no configuration or network communication involved here so not much to test except a platform call.

=> Considering that Die is only a few trivial lines of code and adds little to no logic compared to random itself, I'd skip testing it in that specific example.

Title: What are good unit tests to cover the use case of rolling a die?

Body:
I'm trying to get to grips with unit testing.

Say we have a die which can has a default number of sides equal to 6 (but can be 4, 5 sided etc.):

```<code>import random
class Die():
    def __init__(self, sides=6):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)
</code>```

Would the following be valid/useful unit tests?

test a roll in the range 1-6 for a 6 sided die

test a roll of 0 for a 6 sided die

test a roll of 7 for a 6 sided die

test a roll in the range 1-3 for a 3 sided die

test a roll of 0 for a 3 sided die

test a roll of 4 for a 3 sided die

I'm just thinking that these are a waste of time as the random module has been around for long enough but then i think if the random module gets updated (say i update my Python version) then at least i'm covered.

Also, do I even need to test other variations of die rolls e.g. the 3 in this case, or is it good to cover another initialized die state?


问:
Does the GPL allow anyone to obtain GPL software without paying for it?
I've spotted a nice WordPress (GPL) theme for sale.

I know somebody who bought it.

I have 2 questions:

Has the company selling it the obligation to send the source code to whoever (customers or not) ask it?

Can the person who bought it give me a copy for free which I could use in production?

答:
The company selling it has no obligation to distribute source to anyone except people to whom they have given binaries. So no, they don't have to give you anything.

Someone who has purchased GPL software does have the right to request source and subsequently redistribute that source to anyone under the terms of the GPL. If you can find a customer willing to give you a copy, that will work.


问:
Why are header files bad design?
this says header files are bad design, but I don't know why.  The answers specified there are about the inefficiency of header file when building.  Why it is bad design is not really touched upon.

As far as I know:

- headers lets you break the source file up so you can compile smaller things faster

- headers lets you separate the interface from the implementation

- headers lets you specify functionality in only one place. ie. no repeating

Yet using includes, include guards, headers, etc. are considered bad design.  How so?  What are the alternatives?

-- EDIT: re. DRY issues

A common argument is that it violates DRY in that you repeat changes in signatures in both the .cpp and .h files.  However, if the code is designed to reuse functionality specified in outside files, is it not unavoidable that header files must be used?

The question asks why header files are bad design, yet without the headers, is modularity not lost?  If modularity is lost, is that not itself a design issue?  Thus using header files averts a separate design issue.

Repeating in general is a bad idea, I get that, but it seems unavoidable if you require common functionality. In which case headers are bad, in terms of signature repetition. In terms of how you design your software, I'm inclined to say that splitting code up/modularizing, and reusing code means your code is designed well.

答:
Header files are a legacy of C's heritage - it was written to be close to the hardware, but abstracted enough to run on similar platforms, if a compiler is made for the platform.

What header files do is they define symbols other files can use without the compiler having an issue. The compiler then replaces the symbolic reference with a link or copy of the actual code.

The design issue with this is that you have to repeat yourself. You define the same symbols in two separate files, and when one changes(say a method signature or a class name), the other must be changed as well.

This violates DRY - "Don't Repeat Yourself". This creates an automatic dependency on another file due to the header files. So then when trying to figure out what the objects and classes are doing, you need both, as there's a tonne of syntactical knobs that can turned in either file.

Title: Why are header files bad design?


答:
This answer looks at header files from a language design perspective. My point is not that you shouldn't use headers in your C or C++ programs – headers are required by these languages. Instead, this answer is an argument that you shouldn't design new languages that use header files.

Header files are bad language design, at least from a modern perspective:

Header files in C are a bad design not least because C's macro system is bad: it works via token substitution, not on an AST level. This means:

It barfs on circular includes

It means that the same stuff is compiled multiple times

A seemingly short and simple program might grow to a gigantic behemoth due to a few includes.

It is incredibly limited (compared to what the gold standard of macros – Lisp – can do).

Header files are bad because they are files. And these files are separate from the actual code. Or not: nobody is preventing you from putting code in the header as well. Why shouldn't the header be in the same file as the source code? There is no solid technical reason for not doing this unless single-pass compilation of each compilation unit is required.

Headers are bad because a non-naive compiler can jolly well figure out forward references of symbols without having these be pre-declared. Predeclarations are only useful if a multi-pass compiler is not an option for some reason. Pre-declarations have no value for a human reader (it's a massive DRY violation), and add too little value for a compiler.

And now to refute some possible rebuttals of the “headers are bad” idea:

“Without headers we can't link against libraries” – I'm sure that's true for C and descendants (which unfortunately are ubiquitous), but this doesn't hold for other languages.

A simple alternative is to directly use the source code of a library to extract the interface (this is how many scripting languages like Perl or Python kind of work).

This may not be desirable in closed-source environments, where the compiler output could be used to link against (which is roughly how Java works, where .class files contain the interface alongside the executable bytecode).

The key point is not that no link specification exists, the key is that this specification isn't written by humans.

“Without headers we can't share things (functions, macros, classes) between files” – yes we can, with things like namespaces and modules containing these things. Let's say I have a #define PI 3.1415 in some C code. To share that definition between my source files, I'd have to #include "my_math_constans.h" or something. Python's solution from math import pi which loads the math module and imports the pi symbol from that module into the current scope works at least just as well.

Title: Why are header files bad design?

Body:
this says header files are bad design, but I don't know why.  The answers specified there are about the inefficiency of header file when building.  Why it is bad design is not really touched upon.

As far as I know:

- headers lets you break the source file up so you can compile smaller things faster

- headers lets you separate the interface from the implementation

- headers lets you specify functionality in only one place. ie. no repeating

Yet using includes, include guards, headers, etc. are considered bad design.  How so?  What are the alternatives?

-- EDIT: re. DRY issues

A common argument is that it violates DRY in that you repeat changes in signatures in both the .cpp and .h files.  However, if the code is designed to reuse functionality specified in outside files, is it not unavoidable that header files must be used?

The question asks why header files are bad design, yet without the headers, is modularity not lost?  If modularity is lost, is that not itself a design issue?  Thus using header files averts a separate design issue.

Repeating in general is a bad idea, I get that, but it seems unavoidable if you require common functionality. In which case headers are bad, in terms of signature repetition. In terms of how you design your software, I'm inclined to say that splitting code up/modularizing, and reusing code means your code is designed well.


问:
What are the origins of the Public/Private function declarations?

The Question

What are the origins of the Public/Private function paradigm?

Background

A question came up in chat about Header files in C, and their usage being mainly to help the compiler, not the programmer. It's my understanding though, that this is the first usage of the concept of "Private" functions, or functions which aren't prototyped in the header file. Had C not used header files to declare functions, would we still have the current concept of Public and Private functions as seen in C# or Java? Or was this concept initially developed elsewhere and simply implemented in the C Header/Source scheme

答:
Private/public comes from the original OO language, Simula, which predated C by a few years.  According to the Wikipedia article, the original concept was first implemented in the TOPS/10 variant of Simula, and was integrated into the core language standard in 1987.  It doesn't say when TOPS/10 Simula was first created, though, so it may or may not have been earlier than C.

Regardless, even if C and its header file system had not been around, modern programming languages would still have inherited the concept of encapsulation through the private/public system from Simula.


答:
Yup, its nothing important in itself, its only benefit is the syntactic sugar that makes it easier to type.

The reason it is in C in the first place is solely because the PDP-11 that was the basis for C, way back in the old days, had a special instruction for incrementing by 1. In those days, using this instruction was important to get more speed out of the system, hence the language feature.

However, I think people like the command so much they would complain if it wasn't there.


问:
Are header files actually good?
I find header files to be useful when browsing C++ source files, because they give a "summary" of all the functions and data members in a class.  Why do so many other languages (like Ruby, Python, Java, etc.) not have a feature like this?  Is this an area where C++'s verbosity comes in handy?</p>

答:
An additional disadvantage of header files is that the program depends on the order of their inclusion, and the programmer has to take extra steps to ensure correctness.

That, coupled with C's macro system (inherited by C++), leads to many pitfalls and confusing situations.

To illustrate, if one header defined some symbol using macros for its use, and another header used the symbol in another fashion such as a name for a function, then the order of inclusion would greatly influence the final result. There are many such examples.

Title: Are header files actually good?


答:
Unfortunately there is no easy answer to this problem.

to refine @dan1111 answer Having users help with the testing for android

add many log statements in you android-app that log important context information à la

now opening database "/data/data/my.namespace.com/databases/myDatabase.db" or

now calling webservice "my.server.com/loadingOrder(id=22)"

ask the user to install  alogcat on the device that can read the local debug-log and instruct him how to set filter to track the source of the problem and send you the log.

Title: Strategies to troubleshoot an error that only happens on a specific device

Body:
As an Android developer, the target market I create apps for is very fragmented. While I can specify certain requirements - e.g. my app only supports Android version x.x or above, sometimes errors may occur that are only evident on one specific phone model.

Are there any strategies to handle device-specific errors, without buying the phone in question? We maintain a suite of phones for testing, but can't afford to go out and buy a new phone when 2 or 3 users report that there's a bug that only occurs for their model of phone.

I'm sure other Android developers have encountered similar issues in the past, and I'm curious what cost-effective strategies are available to help squish device-specific bugs.

Update to add a few details:

I use Bugsense to capture bug reports, so whenever exceptions are thrown I will know the model of the phone, the stack trace, the number of times it has happened to my users, and a few other details.

The users may be located in different countries, so I can't assume I'll ever be able to borrow their phone.

Imagine a scenario like this: 100 users have installed the app, but three people complained that a button doesn't work properly when pressed. None of the models of phone I have for testing experience the problem. There doesn't appear to be an emulator for the problem phone model.


问:
Rules and advice for logging?
In my organization we've put together some rules / guildelines about logging that I would like to know if you can add to or comment.

We use Java but you may comment in general about loggin - rules and advice

Use the correct logging level

ERROR: Something has gone very wrong and need fixing immediately

WARNING: The process can continue without fixing. The application should tolerate this level but the warning should always get investigated.

INFO: Information that an important process is finished

DEBUG. Is only used during development

Make sure that you know what you're logging.

Avoid that the logging influences the behavior of the application

The function of the logging should be to write messages in the log.

Log messages should be descriptive, clear, short and concise.

There is not much use of a nonsense message when troubleshooting.

Put the right properties in log4j

Put in that the right method and class is written automatically.

Example:

Datedfile -web

```<code>log4j.rootLogger=ERROR, DATEDFILE
log4j.logger.org.springframework=INFO
log4j.logger.waffle=ERROR
log4j.logger.se.prv=INFO
log4j.logger.se.prv.common.mvc=INFO
log4j.logger.se.prv.omklassning=DEBUG

log4j.appender.DATEDFILE=biz.minaret.log4j.DatedFileAppender
log4j.appender.DATEDFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATEDFILE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%C{1}.%M] - %m%n

log4j.appender.DATEDFILE.Prefix=omklassning.
log4j.appender.DATEDFILE.Suffix=.log
log4j.appender.DATEDFILE.Directory=//localhost/WebSphereLog/omklassning/
</code>```

Log value.

Please log values from the application.

Log prefix.

State which part of the application it is that the logging is written from, preferably with something for the project agreed prefix e.g. PANDORA_DB

The amount of text.

Be careful so that there is not too much logging text. It can influence the performance of the app.

Loggning format:

-There are several variants and methods to use with log4j but we would like a uniform use of the following format, when we log at exceptions:

logger.error("PANDORA_DB2: Fel vid hämtning av frist i
TP210_RAPPORTFRIST", e);

In the example above it is assumed that we have set log4j properties so that it automatically write the class and the method.

Always use logger and not the following:

System.out.println(), System.err.println(), e.printStackTrace()

If the web app uses our framework you can get very detailed error information from EJB, if using try-catch in the handler and logging according to the model above:

In our project we use this conversion pattern with which method and class names are written out automatically . Here we use two different pattents for console and for datedfileappender:

```<code>log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.appender.DATEDFILE.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
</code>```

In both the examples above method and class wioll be written out. In the console row number will also be written our.

toString()

Please have a toString() for every object.
EX:

```<code>@Override
public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append(" DwfInformation [ ");
  sb.append("cc: ").append(cc);
  sb.append("pn: ").append(pn);
  sb.append("kc: ").append(kc);
  sb.append("numberOfPages: ").append(numberOfPages);
  sb.append("publicationDate: ").append(publicationDate);
  sb.append("version: ").append(version);
  sb.append(" ]");
  return sb.toString();
}
</code>```

instead of special method which make these outputs

```<code>public void printAll()
{
    logger.info("inbet: " + getInbetInput());
    logger.info("betdat: " + betdat);
    logger.info("betid: " + betid);
    logger.info("send: " + send);
    logger.info("appr: " + appr);
    logger.info("rereg: " + rereg);
    logger.info("NY: " + ny);
    logger.info("CNT: " + cnt);
}
</code>```

So is there anything you can add, comment or find questionable with these ways of using the logging? Feel free to answer or comment even if it is not related to Java, Java and log4j is just an implementation of how this is reasoned.

答: One thing I would suggest would be that you have a means of having multiple logging contexts associated with any particular log file, and arrange so that anything written to any logging context will get logged unless code explicitly asks the logging context to discard its contents.  Such a design will allow one to capture rather detailed logs during an operation and discard them if the operation succeeds, but have them available if the operation fails.  Absent such a logging feature, having good logs available when something fails may require that an application waste lots of time logging useless data in the 99.99% of times when everything works.

Title: Rules and advice for logging?


问:
When and Where should we use hoisting in Javascript
I'm new to Javascript. I'm learning the concept of hoisting in Javascript.

Based on the Javacsript tutorials in Mozilla website, I came across this word hoisting. According to those tutorials, variables in JavaScript is that you can refer to a variable declared later, without getting an exception. But, my question is on what circumstances is it suitable to use hoisting in a  client-side Javascript or why should we use hoisting in Javascript. What are its advantages.

答:
I've never heard the term "hoisting" used.  If you are referring to this usage of hoisting by Ben Cherry: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html, then from what I can gather, he is simply echoing Douglas Crockford from Javascript: The Good Parts, and saying that you should never use hoisting.  His assertion at the end is that all variables should be declared at the top of your function (as Crockford and JSLint suggest).

Or, in the words of Mr. ChristopherBrown, it's not a feature to use, per-say, but simply a quirk related to how the browser interprets Javascript.

So, in short: never and nowhere.


问:
How to reuse c++ code?
How do I call functions defined outside a source file given you shouldn't use header files?

-- EDIT: generic(?) question below

So, first, a problem should be broken down into simpler subproblems.  Then, each subproblem is solved by implementing new code for a subsolution or reusing an existing subsolution.  If done correctly, then each subsolution exists on its own, uncoupled to any other subsolution and called by the interface it provides.  That is how I understand modularity.

To solve the superproblem, the sum of all subproblems, one central logic, the supersolution, brings together all the subsolutions and coordinates every subsolution such that the superproblem is solved.

If the solution scheme above is flawed, please clarify.

Now, how do you accomplish coding the supersolution in c++?  Particularly, how can you reuse a subsolution for a different superproblem?

+ Example:

superproblem_1: isolate dialog in a novel's text file

possible subproblem_1: how to get text between quotes?

possible subsolution_1: split(novelLine, '\"')

superproblem_2: isolate dialog in a list separated by commas

possible subproblem_2: how to get text between commas?

possible subsolution_2: split(dialogList, ',')

common subsolution: split(string, character)

So, when you break up both superproblems, a common subsolution exists.  If I made the programs modular, I can extract that common subsolution out of both.  How can I then use the subsolution in both superproblems given that I just extracted it?

答:
If I can #include "your_library.h" and then type "ThatGuysModularClass obj;" and continue to do exactly what I want it to do, with a well documented API (i.e.: "this method does this, that one does that", etc.) you have successfully created something modular, in my opinion.

Example:

I need to calculate the area of a triangle. For this I will need a height, base, and another object I can use to represent "2" to do the division. This is because in some parallel universe the number "2" is impossible to represent as an integer (bare with me). Well, let us use John Doe's modular library Two.h.

```<code>#include "Two.h"
Two the2;

int base, height;
base = 5; height = 12;

// do some stuff
// problem solved
</code>```

I can also use John's Two.h to solve another problem, like finding the circumference of a circle given its area, or whatever.

Two.h is said to be modular, because we can re-use it.

Title: How to reuse c++ code?

Body:
If I can #include "your_library.h" and then type "ThatGuysModularClass obj;" and continue to do exactly what I want it to do, with a well documented API (i.e.: "this method does this, that one does that", etc.) you have successfully created something modular, in my opinion.

Example:

I need to calculate the area of a triangle. For this I will need a height, base, and another object I can use to represent "2" to do the division. This is because in some parallel universe the number "2" is impossible to represent as an integer (bare with me). Well, let us use John Doe's modular library Two.h.

#include "Two.h"
Two the2;

int base, height;
base = 5; height = 12;

// do some stuff
// problem solved

I can also use John's Two.h to solve another problem, like finding the circumference of a circle given its area, or whatever.

Two.h is said to be modular, because we can re-use it.


问:
Is it bad software design to mix JDBC SQL calls and use an ORM in an application?
Is it bad software design to have JDBC/raw SQL and also use an ORM?  I don't mind using an ORM for boilerplate CRUD, but some queries are better in SQL (for me).  I'm not arguing for or against ORMs.  I've read about them until I'm blue in the face.

I used JDBC in my question, but it could have been DBI, or some other database interface.  ORM can be any of them.

How about maintainability?  Would mixing the strategies complicate it?  To me the maintainability of an application efficiently becomes even more blurrier, if it is a compiled language vs. a scripting language.  I have to recompile Java.  I don't have to recompile Python or PHP.

If my SQL is in a model layer, does that change anything?

EDIT:  If I use find a point where I need to use SQL in my ORM, in my model, what kind of data is sent back?  I won't be able to use something like person.save('somevalue'), for example, will I?

答:
Object-Relational Mappers are not an all-or-nothing proposition.  You use ORM's so that you don't have to go through the tedium of writing CRUD queries, which can comprise about 80% of your application.

But every ORM still has a mechanism for using raw SQL or stored procedures, or allows you to write such procedures outside of the ORM.  This allows you to optimize that small part of your program (perhaps the remaining 20%) that doesn't satisfactorily lend itself to orthodox object-relational mapping.


答:
It's usually bad because the ORM will cache data, so by going around it you won't be able to take advantage of that caching. You also can't share things like prepared statments.  If you intermix things too much, you could possibly also wind up with a deadlock if your JDBC code and the ORM don't use the same locking strategy, or you have lock promotion issues.

Some ORMs provide the ability to execute statements within the same context as the ORM, which can eliminate many of the problems.

Title: Is it bad software design to mix JDBC SQL calls and use an ORM in an application?

Body:
Is it bad software design to have JDBC/raw SQL and also use an ORM?  I don't mind using an ORM for boilerplate CRUD, but some queries are better in SQL (for me).  I'm not arguing for or against ORMs.  I've read about them until I'm blue in the face.

I used JDBC in my question, but it could have been DBI, or some other database interface.  ORM can be any of them.

How about maintainability?  Would mixing the strategies complicate it?  To me the maintainability of an application efficiently becomes even more blurrier, if it is a compiled language vs. a scripting language.  I have to recompile Java.  I don't have to recompile Python or PHP.

If my SQL is in a model layer, does that change anything?

EDIT:  If I use find a point where I need to use SQL in my ORM, in my model, what kind of data is sent back?  I won't be able to use something like person.save('somevalue'), for example, will I?


答:
Hoisting describes a feature of how Javascript is interpreted by the browser, and isn't so much a feature to be used.

When interpreting Javascript, browsers scope function-level variables at the beginning of the function.  Example:

```<code>function AddTwoAndTwo() {
    var two = 2;
    var result = two + two;
    return result;
}
</code>```

In the posted code, both variables "two" and "result" exist at the start of function scope (obviously, as they're declared there.)  However, because the browsers are "hoisting" the variables, the following becomes legal Javascript code.

```<code>function AddTwoAndTwo() {
    result = 5;
    alert(result);
    var two = 2;
    var result = two + two;
    return result;
}
</code>```

The net effect here is that you have variables in use before you declare them, and that can cause confusion, especially with global-scope variables. Example:

```<code>var result = 6;

function AddTwoAndTwo() {
    alert(result);  // should this be 6 or undefined?
    var two = 2;
    var result = two + two;
    return result;
}
</code>```

To avoid confusion, declare your variables at the top of a function.

Title: When and Where should we use hoisting in Javascript

Body:
I'm new to Javascript. I'm learning the concept of hoisting in Javascript.

Based on the Javacsript tutorials in Mozilla website, I came across this word hoisting. According to those tutorials, variables in JavaScript is that you can refer to a variable declared later, without getting an exception. But, my question is on what circumstances is it suitable to use hoisting in a  client-side Javascript or why should we use hoisting in Javascript. What are its advantages.

Body:
Hoisting describes a feature of how Javascript is interpreted by the browser, and isn't so much a feature to be used.

When interpreting Javascript, browsers scope function-level variables at the beginning of the function.  Example:

function AddTwoAndTwo() {
    var two = 2;
    var result = two + two;
    return result;
}

In the posted code, both variables "two" and "result" exist at the start of function scope (obviously, as they're declared there.)  However, because the browsers are "hoisting" the variables, the following becomes legal Javascript code.

function AddTwoAndTwo() {
    result = 5;
    alert(result);
    var two = 2;
    var result = two + two;
    return result;
}

The net effect here is that you have variables in use before you declare them, and that can cause confusion, especially with global-scope variables. Example:

var result = 6;

function AddTwoAndTwo() {
    alert(result);  // should this be 6 or undefined?
    var two = 2;
    var result = two + two;
    return result;
}

To avoid confusion, declare your variables at the top of a function.


问:
Logging in a latency sensitive system
Requirements:

My application is latency sensitive. Millisecond level responsiveness matters. Not all the time, but when it acts, it needs to be fast.

My application needs to log information about what it's done in those times.

The actual writing of the logs does not need to be that fast, just the actions.

However, the log files need to be written at human speed, in other words, I cannot set immediateFlush to false.

So, obviously, certain kinds of logging are getting offloaded to another thread. I am using logback as a framework, but for certain sorts of log messages I still want to offload the work to another thread.

Here is how the system currently works:

Each part of the latency sensitive system gets a particular logger interface injected. Each of these log methods has a signature specific to the sorts of things I know the logger will need to log.

A SimpleLogger implementation is written for each case. This writes to the log on the same thread.

I have also written a ThreadedLogger which implements ALL the logging interfaces, and gets a "backing" logger implementation injected for each sort of logger.

Whenever a log method is called in ThreadedLogger, it wraps the request in an SomeLogObject implements LogCommand, throws the objected into a LinkedBlockingQueue, and returns. This is similar to the Go4 Command pattern

There is a consumption thread that blocks on BlockingQueue.take() waiting for log objects to come in. When they do, it calls LogCommand.execute(), which calls the appropriate method in the backing Logger in ThreadedLogger.

Currently the LogCommand implementations are very stupid. They just call the appropriate method in the proper injected logger.

I am trying to decide if I should refactor this system. Currently, if I need to create a new place to do these offloaded logs, I have to create:

A new interface

A new implementation of this interface

Two new DI bindings (one for the simple logger, one for the ThreadedLogger backer)

A new LogCommand implementation

A new method for creating this LogCommand object

Code for injecting and storing as a field the appropriate logger in ThreadedLoggger

It seems to me that it would be a lot simpler to offload the creation of the LogObject to the calling threads, but I am concerned that I'm exposing too much of the internal workings of the log system if I do that. Not that this is necessarily a problem, but it seems unclean. Another possibility would be to combine the functionality of the simple logger implementations with their respective log objects, so the objects change from being "I am an object that does logging when given log data" to "I am a log event that knows how to log myself", and these objects can be created by a log factory.

答:
You have made your design overly complex by creating specific logger signatures for the various latency sensitive parts.

A better design would have been to use the Logger interface from logback for all parts of the application. If performance measurements have shown that the logging causes a bottleneck for some low-latency parts, then you can offload the logging in this way:

You create a ThreadedLogger class that implements the Logger interface and a ThreadedLogReader class.

These two classes communicate using LogCommand objects. The LogCommand class contains all the required log information (which logger to use, the severity level and the actual log message).

The ThreadedLogReader class runs on a separate thread and injects the log messages in the received LogCommand objects into the logback framework.

This way, your logging framework remains free from knowledge about the latency-sensitive parts of the code. If you want to make it really fancy, you could even implement a custom version of the LoggerFactory class which decides if a certain logger should be a ThreadedLogger or a regular Logger.

Title: Logging in a latency sensitive system


答:
I'd say yes, you should probably avoid it if at all possible.

Code is read drastically more regularly than it is written.  When you're maintaining an application, having code that works and reads the same way throughout is much more maintainable than having bits that work one way, and bits that work another.


问:
mysql, store a single piece of data per row
I am preparing to write a database system using PHP and MYSQL which will store every piece of info sent to it as an individual row.  Each row will store several piece of meta data (time stamp, who created it, version number, attribute number) and one piece of 'true' data (file name, phone number, username, etc.)  Rows my also be used to store serialized data.  The goal is to create a system that is easy to incrementally back up, search on single rows,  and review based on its state at a particular date.  Is this an effective design or should I alter my approach?

The database will be used to drive a custom CMS system which is intended to store a interconnected system of data.  It will involve customer data, location data and job data.  We want to be able to track individual database changes based on time so that we can maintain an on-site backup (the system will be cloud based) which we can use in the event that we lose internet connectivity.  The system will be strongly permission based, only allowing people to see/change information that they are authorized to see.  Most of the data will be viewed in a timeline format, based on the time that the info is entered into the system.

答:
This approach is sometimes used in unusual situations, such as having tables that would have a huge number of columns each sparsely populated, or having user defined data where the columns are not known until the application is running.

The reason it isn't used more is that it's not how relation databases like MySQL are designed to work, and therefore doing so is problematic.  The way indexes work is based on columns, and if your column is really holding a bit of everything then you will have to index everything or nothing, and the query optimizer will have a hard time determining when it will be useful.  You are depriving the database of the accurate meta-data it would otherwise have, and this will cost you in performance.

Furthermore, the SQL you write will be more difficult.  If you want to get a bunch of related data, say everything from one web page, you will have to group by... something that you put in the database to allow to group.  Most likely you will end up having a table table, a row table, a column table, and a value table, and group by the row table.  This is a pain.

As far as your stated goals of being easy to incrementally back up, search on single rows, and review based on it's state on a particular date, it doesn't help back-up, it doesn't make it easier to search on a single value (and makes it harder to search multiple values in a logical row), and at best does nothing to help you review it's state on a particular date (the timestamp is the key to that).

So, based on the information you provided I don't think you are a good candidate for using this design.  If so, you should consider yourself lucky - it's a pain.


答:
It depends on your application needs. For example, I've been working for banking, and when you have to generate thousands of invoice payments orders, it's better to have an stored procedure to do the task (it'll be by far faster) and to update the model tables directly in the database.

Then you can show the results with ORM, even update a payment order (but not thousands).

If your application is not performance critical, it's better for programming mantainability to deal with ORM, so that you don't need to know about the underlaying DB technology.

So that one more time, it depends on your needs and if you keep the code organized and clean (apply a DAO pattern for it, for example), it's not a bad architecture nor unmaintainable code.


问:
What's a DRY alternative to c++ header files?
In c++, is there any other way, besides header files, to use a function defined in file A.cpp, inside file B.cpp that would be considered good programming practice?</p>

答:
With your restriction of "besides header files", the answer is: No.

The C++ compiler compiles each source file independently. If you intend to use a declaration that appears only once, it must appear in a header file.

(This does not consider things that wouldn't be considered good programming practice, such as including one .cpp file within another, or using -D compiler command line macros to define extern symbols in more than one source file.)


答:
The easiest test of a die-roll is simply to repeat it several hundred-thousand times, and validate that each possible result was hit roughly (1 / number of sides) times.  In the case of a 6-sided die, you should see each possible value hit about 16.6% of the time.  If any are off by more than a percent, then you have a problem.

Doing it this way avoids allows you to refactor the underlying mechanic of generating a random number easily, and most importantly, without changing the test.


问:
How to design my code so that it can use alternative information to help create an object
I have a class named Product, which takes a product model number and number of wheels for that product as part of its creation information, and then it instantiates the product by doing a computation on the number of wheels and on various base parameters

For example, Product(5, 22) creates a model 5 product with 22 wheels on it, where that particular product's weight and dimensions are computed from the number of wheels and from the base specifications for that model number.  Right now base specifications are part of the class itself and are hardcoded into the class, along with the computation formulas.

My Issue:  in the (legacy) code I am working with, I cannot always use the model number directly.  It may not be available.  Instead, an unrelated product_id is given, where the link between product_id and model_number is in the database.

I want to keep my class as simple as possible.  As such I do not want to introduce another constructor that allows product_id as an input parameter, in addition to the existing model_number, as it will be duplication of code.  Also, I am not too keen on putting database logic inside the class, but maybe I can, as thinking about it now, this may be a good candidate for a database-wrapper class, i.e. active record (where my base specifications can be moved off from the code and into the database).

Question:  How do I create and return the object while following good object oriented principles when the model_number I typically use for its creation is not available, but another parameter is available instead (product_id in this case), which links 1:1 to model_number?

Sample solutions that I don't quite  like:

Do not involve the database -- since I am working with just a few Products at this time, and Products do not change often, I can create a "conversion function" that serves as a map between product_id and model_number and not touch the database.  Similarly, create a Convert object that has same functionality and use it before creating the object.  Problem:  duplicating DB functionality in the code.

Put DB functionality inside code and add alternate constructor.  Problem:  multiple entry-points of Product creation for the class create code duplication.

Update:

There basically are 3 aspects here:

base data (whether hardcoded or part of the database)

finding base data by various parameters be it model number or other identifying information

doing computation using base data as per model number

答: Maybe this -- give up the idea of a Product class and create a DB-wrapper where I will say $pf = ProductFinder(), then do $pf->findById() and $pf->findByModel() as needed.  Problem:  Where do I put my computation code?  It can't be in the same place, as it it will violate Single Responsibility Principle.  aka, computation and data handling should be separate.  Then maybe Product class can be the computational part, and ProductFinder be the database pulling part.


答: Lazy C++ can automate the generation of .h and .cpp files from a common .cpp-like source, so you don't have to repeat yourself by maintaining the header file yourself.

Title: What's a DRY alternative to c++ header files?

Body: In c++, is there any other way, besides header files, to use a function defined in file A.cpp, inside file B.cpp that would be considered good programming practice?</p>


答: Maybe create a ProductFactory, with methods to create a Product given a number of wheels and either a product ID or a model number.  Given a model number it defers to the class' constructor, and if given a product ID it performs the DB lookup, gets the model number, then defers to the class constructor.

Title: How to design my code so that it can use alternative information to help create an object

Body:
I have a class named Product, which takes a product model number and number of wheels for that product as part of its creation information, and then it instantiates the product by doing a computation on the number of wheels and on various base parameters

For example, Product(5, 22) creates a model 5 product with 22 wheels on it, where that particular product's weight and dimensions are computed from the number of wheels and from the base specifications for that model number.  Right now base specifications are part of the class itself and are hardcoded into the class, along with the computation formulas.

My Issue:  in the (legacy) code I am working with, I cannot always use the model number directly.  It may not be available.  Instead, an unrelated product_id is given, where the link between product_id and model_number is in the database.

I want to keep my class as simple as possible.  As such I do not want to introduce another constructor that allows product_id as an input parameter, in addition to the existing model_number, as it will be duplication of code.  Also, I am not too keen on putting database logic inside the class, but maybe I can, as thinking about it now, this may be a good candidate for a database-wrapper class, i.e. active record (where my base specifications can be moved off from the code and into the database).

Question:  How do I create and return the object while following good object oriented principles when the model_number I typically use for its creation is not available, but another parameter is available instead (product_id in this case), which links 1:1 to model_number?

Sample solutions that I don't quite  like:

Do not involve the database -- since I am working with just a few Products at this time, and Products do not change often, I can create a "conversion function" that serves as a map between product_id and model_number and not touch the database.  Similarly, create a Convert object that has same functionality and use it before creating the object.  Problem:  duplicating DB functionality in the code.

Put DB functionality inside code and add alternate constructor.  Problem:  multiple entry-points of Product creation for the class create code duplication.

Update:

There basically are 3 aspects here:

base data (whether hardcoded or part of the database)

finding base data by various parameters be it model number or other identifying information

doing computation using base data as per model number


问:
From a TDD perspective, am I a bad person if I test against a live endpoint instead of a mock?
I follow TDD religiously.  My projects typically have 85% or better test coverage, with meaningful test cases.

I do a lot of work with HBase, and the main client interface, HTable, is a real pain to mock.  It takes me 3 or 4 times longer to write my unit tests than it does to write tests that use a live endpoint.

I know that, philosophically, tests that use mocks should take priority over tests that use a live endpoint.  But mocking HTable is a serious pain, and I'm not really sure it offers much of an advantage over testing against a live HBase instance.

Everyone on my team runs a single-node HBase instance on their workstation, and we have single-node HBase instances running on our Jenkins boxes, so it's not an issue of availability.  The live endpoint tests obviously take longer to run than the tests that use mocks, but we don't really care about that.

Right now, I write live endpoint tests AND mock-based tests for all my classes.  I'd love to ditch the mocks, but I don't want quality to decline as a result.

What do you all think?

答:
TL;DR - The way I see it, it depends on how much effort you end up spending on tests, and whether it would have been better to spend more of it on your actual system instead.

Long version:

Some good answers here, but my take on it is different: testing is an economic activity that needs to pay back for itself, and if the time you spend isn't returned in development and system reliability (or anything else you look to get out of tests) then you may be making a bad investment; you're in the business of building systems, not writing tests. Therefore, reducing the effort to write and maintain tests is crucial.

For example, some main values I gain from tests are:

Reliability (and therefore development speed): refactor code/integrate a new framework/swap a component/port to a different platform, be confident that stuff still works

Design feedback: classic TDD/BDD "use your code" feedback on your low/mid-level interfaces

Testing against a live endpoint should still provide these.

Some drawbacks for testing against a live endpoint:

Environment setup - configuring and standardizing the test running environment is more work, and subtly different environment setups could result in subtly different behavior

Statelessness - working against a live endpoint can end up promoting writing tests that rely on a mutating endpoint state, which is fragile and hard to reason against (i.e. when something is failing, is it failing because of weird state?)

Test running environment is fragile - if a test fails, is it the test, the code, or the live endpoint?

Run speed - a live endpoint is usually slower, and sometimes is harder to parallelize

Creating edge cases for testing - usually trivial with a mock, sometimes a pain with a live endpoint (e.g tricky ones to set up are transport/HTTP errors)

If I were in this situation, and the drawbacks didn't seem to be a problem whereas mocking the endpoint slowed down my test writing considerably, I'd test against a live endpoint in a heartbeat, as long as I'd be sure to check again after a while to see that the drawbacks don't turn out to be a problem in practice.


答:
You don't want to duplicate the DB mapping product_id -> model_number by hardcoding the logic, that makes sense. So the first thing you need is a function  like

```<code>int mapProductIdToModelNumber(int product_id)
</code>```

which does this mapping by getting the information from the database (consider caching when this function is used very often).

What remains is how to make this function available to your Product class without tight coupling. You have the following alternatives:

pass the function directly to the code blocks whereever Product objects are created (depends on your programming language how to accomplish that)

implement the function in a ProductFactory class. Derive ProductFactory from an interface IProductFactory and pass an object of this type to the code areas where you currently want a new Product(). Use the factory the way @TMN suggested.

That way, your legacy code stays decoupled from the database, since it won't depend directly from a database-bound ProductFactory, only from IProductFactory, which can be easily mocked out (for example, for testing purposes).

Body:
You don't want to duplicate the DB mapping product_id -> model_number by hardcoding the logic, that makes sense. So the first thing you need is a function  like

int mapProductIdToModelNumber(int product_id)

which does this mapping by getting the information from the database (consider caching when this function is used very often).

What remains is how to make this function available to your Product class without tight coupling. You have the following alternatives:

pass the function directly to the code blocks whereever Product objects are created (depends on your programming language how to accomplish that)

implement the function in a ProductFactory class. Derive ProductFactory from an interface IProductFactory and pass an object of this type to the code areas where you currently want a new Product(). Use the factory the way @TMN suggested.

That way, your legacy code stays decoupled from the database, since it won't depend directly from a database-bound ProductFactory, only from IProductFactory, which can be easily mocked out (for example, for testing purposes).


答:
From a testing perspective there are some requirements that are an absolute must:

Testing (unit or otherwise) must never have a way to touch production data

The results from one test must never affect the results of another test

You must always start from a known position

That's a big challenge when connecting to any source that maintains state outside of your tests.  It's not "pure" TDD, but the Ruby on Rails crew solved this issue in a way that might be able to be adapted for your purposes.  The rails test framework worked in this way:

Test configuration was automatically selected when running unit tests

The database was created and initialized at the start of running unit tests

The database was deleted after unit tests were run

If using SqlLite, the test configuration used a RAM database

All this work was built into the test harness, and it works reasonably well.  There's a lot more to it, but the basics are enough for this conversation.

On the different teams that I've worked with over time, we would make choices that would promote code getting tested even if it wasn't the most correct path.  Ideally, we would wrap all calls to a data store with code we controlled.  In theory, if any of these old projects got new funding we could go back and move them from being database bound to Hadoop bound by focusing our attention on just a handful of classes.

The important aspects are not to mess with production data, and make sure you are truly testing what you think you are testing.  It's really important to be able to reset the external service to a known baseline on demand--even from your code.

Title: From a TDD perspective, am I a bad person if I test against a live endpoint instead of a mock?

Body:
I follow TDD religiously.  My projects typically have 85% or better test coverage, with meaningful test cases.

I do a lot of work with HBase, and the main client interface, HTable, is a real pain to mock.  It takes me 3 or 4 times longer to write my unit tests than it does to write tests that use a live endpoint.

I know that, philosophically, tests that use mocks should take priority over tests that use a live endpoint.  But mocking HTable is a serious pain, and I'm not really sure it offers much of an advantage over testing against a live HBase instance.

Everyone on my team runs a single-node HBase instance on their workstation, and we have single-node HBase instances running on our Jenkins boxes, so it's not an issue of availability.  The live endpoint tests obviously take longer to run than the tests that use mocks, but we don't really care about that.

Right now, I write live endpoint tests AND mock-based tests for all my classes.  I'd love to ditch the mocks, but I don't want quality to decline as a result.

What do you all think?


问:
Should I expose a "computed" value as a property or a method?
I have a C# class that represents a content type in a web content management system.

We have a field that allows a web content editor to enter an HTML template for how the object is displayed.  It basically uses the handlebars syntax for substituting object property values into the HTML string:

```<code><h1>{{Title}}</h1><p>{{Message}}</p>
</code>```

From a class design perspective, should I expose the formatted HTML string (with substitution) as a property or method?

Example as property:

```<code>public class Example
{
  private string _template;
  public string Title { get; set; }
  public string Message { get; set; }
  public string Html
  {
    get
    {
      return this.ToHtml();
    }
    protected set { }
  }

  public Example(Content content)
  {
    this.Title = content.GetValue("title") as string;
    this.Message = content.GetValue("message") as string;
    _template = content.GetValue("template") as string;
  }

  private string ToHtml()
  {
    // Perform substitution and return formatted string.
  }
}
</code>```

Example as method:

```<code>public class Example
{
  private string _template;
  public string Title { get; set; }
  public string Message { get; set; }

  public Example(Content content)
  {
    this.Title = content.GetValue("title") as string;
    this.Message = content.GetValue("message") as string;
    _template = content.GetValue("template") as string;
  }

  public string ToHtml()
  {
    // Perform substitution and return formatted string.
  }
}
</code>```

I'm not sure from a design standpoint does it make a difference or are there reasons why one approach is better than the other?

答:
UPDATE: This question was the subject of my blog in May 2014. Thanks for the great question!

To add to Robert Harvey's answer: a property should be:

logically a property of the class, the way that say its color or year or model are the properties of a car.

not more than, let's say, ten times slower to compute than fetching from a field.

something you don't mind being computed while debugging. The VS debugger automatically computes properties.

unable to fail. Getters should always return a value no matter what the state of the object is.

I don't think your proposed Html property hits any of those.  Don't make it a property unless it hits all of them.


问:
Mobile/Global User Authentication? (Non-domain and non-enterprise)
What is the current way to authenticate users in a mobile/global fashion?  In other words, assume a mobile application.  And if there is a database server in the backend, how would these users typically register/login?  Is there a current standard for non-domain, non-enterprise authentication?

I was thinking just having a basic username/password combination, and hashing (and salting) the password on registration and login, and passing that over the wire to the cloud database.  That gets a little fuzzy with password resetting, emailing, etc. though.

Is there an easier way (API, methodology, etc.) or more-accepted way to do this?  It's simple, but that simplicity is a good thing, I think.  I don't need the complexities of other membership frameworks.  I'm more curious if this is an accepted and secure approach.

I am aware of ASP.NET's membership model, but the complexity is just way too much for a one-dimensional security model (users and auth, no need for roles, authorization, etc.).  Not to mention, outside of an ASP.NET application, what would be used?

答:
In general, if your mobile app is based on remote web services, you should establish a secure connection (ssl/tls) to the remote server and pass the username/password directly to the server for processing on the server, not on the client.

I presume this is some kind of a web server. You are almost definitely not going to be connecting directly from your mobile app to a bare database server, right?

What you would not do would be to hash the user-supplied password on the phone, then pass the hash across the wire for comparison on the server. The authenticating server's job is to confirm that the remote party knows the correct password for the supplied username, not that the remote party knows the correct password hash for the username.

Otherwise, an attacker who might have gotten access to your credentials database could just pass a username and password hash and never need to know the actual password at all. Oops! :-).

If you're going to roll your own authentication on the server, then you would need to store at least 3 fields:

the username

password hash

salt (randomly generated entropy, unique per user)

You should also consider storing:

a password hash version id, so that you can switch to an upgraded algorithm in the future without automatically invalidating all of your existing passwords

a password expiration date/time (or some variation of this concept) so that you can expire passwords when you need to, or have them auto-expire after a certain age

The salt and password hash are byte arrays when fully reconstituted in computer memory. Convert them to Base64-encoded strings for storage.

Simply hashing the password is considered insufficient now:

even if you use salt and even if you use a substantial hash algorithm like SHA256 or SHA512

using straight hashing without salt was what got a certain large business networking service into so much trouble with their latest user account breach

dictionary attack methods using the GPU's on powerful video cards combined with dictionaries or rainbow tables makes it necessary to make password comparisons slow enough not to be worth the effort

MD5 just isn't up to the task at all, and hasn't been for a long time

SHA1 has theoretical exploits and is considered to be weak now (at least potentially, just a matter of time before it's exploited)

SHA256 or SHA512 are better, but still too fast

Use an algorithm actually designed for hashing passwords, such as bcrypt, scrypt or PBKDF2.

These types of algorithms build on hashing algorithms like SHA1 or SHA256, plus HMAC algorithms, then iterate many times (perhaps thousands, or more) feeding the result of each iteration back into the algorithm to make it infeasibly slow for a brute force attacker to run billions of comparisons from a dictionary/rainbow table, while still being fast enough to reasonably verify individual legitimate user logins.

You can vary the number of iterations to suit your own purposes (speed vs. security).

An attacker will have to know what algorithm you use, and also know the number of iterations you have chosen

The authentication algorithm id comes into play here; if you increase the number of iterations, then you break all your existing user credentials unless you have id'd the algorithm and continue to support the old algorithm (say, PBKDF2 with 1,000 iterations) for existing passwords while requiring the new algorithm (say, PBKDF2 with 10,000 iterations) for new and updated passwords

If the processing load becomes too much for your server (presumably a web server), you can offload authentication to a separate server.

A lot of the cool kids are doing PBKDF2, although bcrypt allegedly makes it more difficult for a GPU-based attack to compare many passwords quickly. Scrypt may be an improvement over bcrypt. I'm not making any value judgements here. Do your own research on these. PBKDF2 may be FIPS compliant, for example, while bcrypt and scrypt are not, but FIPS compliance may not be a requirement for you.


问:
At what point does data access\manipulation logic becomes business logic?
Consider a service which updates PersonDetail tables in database. I am Using EF which maps the table to this Entity. When a record is updated, it is not actually updated but a new record is created and old one is made history by setting HistoryCode to 0

```<code>Class PersonDetail
{
  int age;
  Date birthDate;
  DateTime effectiveDate;
  int sequenceNumber; //An incremental number.
  int HistoryCode; //0 represents history record and 1 current record
}
</code>```

Now we have a service that updates the person details

```<code>if(newPersonDetail.effectiveDate < currentPersonDetails.effectiveDate)
{
  //update sequence number of currentPersonDetails by 1
  //insert a new Person Details record and assign its sequenceNumber as the sequence number
  //of currentPersonDetails and HistoryCode as 0 to represent this is an history record
}
else
{
   //Make the currentPersonDetails HistoryCode to 0 from 1
   //Insert a newPersonDetail with sequence number incremented by 1 and HistoryCode set to 0
}
</code>```

Logic? I am trying to move the data-access logic out of service layer to repository layer but not able to clearly figure out what part of this is considered as business logic and what is considered as Data Access logic.

答: The PersonDetail class is part of the data access.  The service that updates PersonDetail  is business logic.  Note that, if you don't actually need this separation (i.e. you won't need to transplant the service layer to some other program, independently of the data access), it may not matter (you're coupled to the data layer anyway, due to the presence of the POCO's).


问:
How compilers know about other classes and their properties?
I'm writing my first programming language that is object orientated and so far so good with create a single 'class'.  But, let's say I want to have to classes, say ClassA and ClassB. Provided these two have nothing to do with each other then all is good. However, say ClassA creates a ClassB--this poses 2 related questions:

-How would the compiler know when compiling ClassA that ClassB even exists, and, if it does, how does it know it's properties?

My thoughts thus far had been: instead of compiling each class at a time (i.e scan, parse and generate code) each "file (not really file, per se, but a "class") do I need to scan + parse each first, then generate code for all?

答:
Older languages sometimes are more strict; consider what is possible in Java:

```<code>public interface Ifc {
    public static final Ifc MY_CONSTANT = new Implem();
}

public class Implem implements Ifc {
}
</code>```

I have seen the anti-pattern above, and it is really ugly (I would have forbidden it). Both compilation units use each other. But Ifc can be compiled to code without having a compiled Implem. The compiled code, .class, comparable to a C .obj, contains "linkage information:" an import of Implem, calling a parameterless constructor Implem(). The Implem class can then compiled without problem. Partly the ClassLoader - doing initialisation/build JVM class data, and partly the Java Virtual Machine itself, play a bit as linker, integrating all.

For instance compiling with one version of a specific library, and running with another version of that library will recognize runtime errors.

So the answer: Compilation delivers units of compiled object code, which one has to see as code + data + API for linking together.

The compiler should afterwards also do a packing together, and verify the linkage API; a second phase.

This might irritate and look inelegant, but mathematical proofs may operate in the same way: in proving the entire correctness one may already consider a part to hold true till verification.

Body:
Older languages sometimes are more strict; consider what is possible in Java:

public interface Ifc {
    public static final Ifc MY_CONSTANT = new Implem();
}

public class Implem implements Ifc {
}

I have seen the anti-pattern above, and it is really ugly (I would have forbidden it). Both compilation units use each other. But Ifc can be compiled to code without having a compiled Implem. The compiled code, .class, comparable to a C .obj, contains "linkage information:" an import of Implem, calling a parameterless constructor Implem(). The Implem class can then compiled without problem. Partly the ClassLoader - doing initialisation/build JVM class data, and partly the Java Virtual Machine itself, play a bit as linker, integrating all.

For instance compiling with one version of a specific library, and running with another version of that library will recognize runtime errors.

So the answer: Compilation delivers units of compiled object code, which one has to see as code + data + API for linking together.

The compiler should afterwards also do a packing together, and verify the linkage API; a second phase.

This might irritate and look inelegant, but mathematical proofs may operate in the same way: in proving the entire correctness one may already consider a part to hold true till verification.


问:
Software trial: limited time or limited functionality?
I am currently developing my first serious piece of software in C#. It is a good learning experience so far.

My software is basically a task scheduling tool with some advanced features and capabilities.

I am not near the finishing stages yet, but I was wondering what people's opinions are on trial versions of software. Do you think it would be more beneficial, in general, to have a limited time trial (say 30 days) or a limited functionality version of the software?

I think I know which I would go with, however I always like to listen to the opinions of others.

Thanks,

答:
I would recommend neither. Go full open-source for this one project. Your first public software release is primarily a learning experience, and you'll learn more from an open-source project than from a free trial. You need to get some experience managing your user community, predicting and responding to needs, and understanding how people will use the things that you build. Open-source means that your more experienced users can more easily help you with these tasks.

By the time you get to a point where trialware is a reasonable option for you, you'll already know the answer to this question for the software you build


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
```<code>val (minors, adults) = people.partition(_.age < 18)
</code>```

The above line of Scala code partitions people (a list of Persons) into two lists based on their respective ages.

It takes the following much of code to do the same thing in Java:

```<code>List<Person> minors = new ArrayList<Person>();
List<Person> adults = new ArrayList<Person>();
for(Person p : people) {
  if(p.age < 18) {
    minors.add(p);
  } else {
    adults.add(p);
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
val (minors, adults) = people.partition(_.age < 18)

The above line of Scala code partitions people (a list of Persons) into two lists based on their respective ages.

It takes the following much of code to do the same thing in Java:

List<Person> minors = new ArrayList<Person>();
List<Person> adults = new ArrayList<Person>();
for(Person p : people) {
  if(p.age < 18) {
    minors.add(p);
  } else {
    adults.add(p);
  }
}


问:
Does the GPL allow anyone to obtain GPL software without paying for it?
I've spotted a nice WordPress (GPL) theme for sale.

I know somebody who bought it.

I have 2 questions:

Has the company selling it the obligation to send the source code to whoever (customers or not) ask it?

Can the person who bought it give me a copy for free which I could use in production?

答:
FOR ALL PRACTICAL PURPOSES, under the GPL, if the company does not distribute the source code WITH the binary, then the company is obligated to give the source code to anyone who requests it.

Scenario: AcmeSoft distributes a widget binary under the GPL selling it to Betty, accompanying it with a promise to deliver the source on request.  Betty redistributes a copy of the binary to Chuck.  Chuck gives a copy of the binary to Dave.  Dave passed it along to Eddie.  Eddie gives it to Freddy.  Freddy asks Eddy for the source code.  Eddie calls Dave.  Dave says "Talk to Chuck."  Chuck says "Talk to Betty, I got it from her."  Betty tell Chuck to "Call AcmeSoft."  The message gets back down to Freddy, and Freddy calls AcmeSoft.

At this point, under the GPL, AcmeSoft is absolutely obliged to give Freddy the source code.

It does not matter how long the Betty-Chuck-Dave-...-Iola-...-Tomas chain might be.  At each step in the chain, distributing the binary obligates the distributor to make the source available, as provided in the GPL, and confers upon the recipient the right to receive the source code from the appropriate person higher up the chain.

In theory, the company could demand that Freddy prove that he in fact has a copy of the binary.  In fact, a company that did that would get a very lousy reputation, very quickly.

The company MAY demand a token payment, to cover their actual reasonable duplication and distribution costs.  Back in the Dark Ages of Big Iron, that covered the cost of a magnetic tape, the labor of writing the tape, and the cost of postage.  Today, in the day of the World Wide Web, that cost is negligible, if not actually too small to bother measuring.

Now, IF AcmeSoft had instead distributed the source WITH the binary, they would be allowed to tell Freddy that they had done so, and that he should have received the source with the binary he received from whoever gave it to him.

Yes, absolutely.  The GPL specifically forbids the licensor or any subsequent distributor from imposing additional restrictions on subsequent down-the-chain distribution of binary OR SOURCE.

Stallman et al actually went to a great deal of trouble to rig the GPL so it would work this way, so that nobody would be able to "take the code private", the way someone allegedly did with an early version of EMACS.  That episode left a VERY bad taste in Stallman's mouth, after he was forced by the threat of litigation to rewrite his baby.


问:
CoffeeScript and Named Functions
Elsewhere, an argument has arisen over the terminology of a named function in CoffeeScript. In particular someone referred to something like this:

```<code> foo = ->
    console.log("bar")
</code>```

as a named function. But its been objected that everything in CoffeeScript is anonymous functions and there are no named functions. This is certainly true, CoffeeScript only has function expressions which can then be stored in a variable. But I don't think that means it is wrong to call this a named function.

As I see it, it is a named function because its a function that has been given a name. True, its not a named function in the same way that some other languages have named functions, but I think its close enough that it's not inappropriate to call it a named function. To insist otherwise just seems to be nitpicking.

Am I out to lunch in thinking that insisting that this isn't a named function is just nitpicking?

答:
Definitely not a nitpick, imo. I use it extensively for readability:

```<code>readfile()
dothis()
dothat()
thistoo()
writefile()

function readfile() {
    ...
}
...
</code>```

Thus:

Real named function in "coffeescript"

```<code>hello()

`function hello() {`
console.log 'hello'
dothings()
`}`
</code>```

You escape pure JS via the backtick `

Note that you can't indent on your function body.

Cheers

Title: CoffeeScript and Named Functions

Body:
Definitely not a nitpick, imo. I use it extensively for readability:

readfile()
dothis()
dothat()
thistoo()
writefile()

function readfile() {
    ...
}
...

Thus:

Real named function in "coffeescript"

hello()

`function hello() {`
console.log 'hello'
dothings()
`}`

You escape pure JS via the backtick `

Note that you can't indent on your function body.

Cheers