问:
Best approach for a database of long strings
I need to store questions and answers in a database. The questions will be one to two sentences, but the answers will be long, at least a paragraph, likely more.

The only way I know about to do this right now is an SQL database. However, I don't feel like this is a good solution because as far as I've seen, these databases aren't used for data of this type or size. Is this the correct way to go or is there a better way to store this data? Is there a better way than storing raw strings?

答:
There is no problem storing big strings or binary data. I worked with a database with more than one terabyte of binary data and worked very well (postgres) and the only bad thing was the backup time.

The big question is: "Will you need do constant searches in this text?"

If you are going to search for strings in the text, you can think in one index solution:

In database there are some thats depends on vendor, like Postgres Full text: http://www.postgresql.org/docs/9.4/static/textsearch.html

In application side there are many good options like Lucene (Java): http://lucene.apache.org/core/


问:
Const means Thread-safe?
I was put onto this video:

http://channel9.msdn.com/posts/C-and-Beyond-2012-Herb-Sutter-You-dont-know-blank-and-blank

By https://codereview.stackexchange.com/users/39810/glampert

Because I asked this question:

https://codereview.stackexchange.com/questions/82616/const-cast-of-stdmutex-in-get-member

Marking a class std::mutex as mutable is the right answer to my original question and the video is an excellent and enjoyable discussion around that. I am grateful to glampert.

However I disagree with the premise of the talk that "const == thread-safe" (see time-point 16:00).

Below is my proposal for how we should interpret const in a multi-threaded world. It's not as simple as Herb's proposal but (let's face it) if you think any of the answers in multi-threading are simple you've completely failed to grasp the challenge of multi-threading.

Comments please. What do you think const means for multi-threaded programs? Has its meaning fundamentally changed?

const means logically unmodified by dereferences through the const
  reference in question.

Multi-threading footnote #1:  In objects that form part of the shared
  state of a multi-threaded program “logically unmodified” will mean
  “logically const member functions only perform reads on the object” and so any
  implementation that actually performs writes (such as cached values,
  instrumentation and even employs synchronization mutexes) needs to
  adequately make them thread-safe to maintain the ‘logical’ appearance
  of ‘only reads’.

Single-threading footnote : Of course even in a single threaded
  application const is by no means a guarantee that an object won’t
  change during the lifetime of a given const reference. There may be
  non-const references (aliases) and even a single threaded program
  might use to modify an object which has one or more const
  references.

Multi-threaded footnote #2: That lack of guarantee that an object will
  not be modified just because there is a const reference to it is true
  in spades for multi-threaded applications. So in many senses – no
  change there.

I think my greatest concern is that through I am sure Herb Sutter would confirm them as dreadful fallacies, I fear that reading const as ‘thread-safe’ leads too easily to:

The fallacy that adding std::lock_guard guard(this->mutex) to the start of all methods and the destructor of a class somehow make any use of it ‘thread-safe’.

The fallacy that if you only call const methods on a class your application has a thread-safe guarantee and you can complain to the implementer if not.

Finally, the fallacy that if you don’t modify any mutable members and don’t cast away const anywhere you don’t need to worry about thread-safety because (apparently) “const means thread-safe”.

Fallacy 1 is best exemplified by supposing you can get any sense iterating through a collection that is being modified by another thread just because you know the methods are lock-guarded.

Fallacy 2 pushes a potentially onerous (and even impossible) burden on to implementers who can (of course) add lock-guards to all their methods but may (at best) be wasting time and (at worst) just setting you up for fallacy 1.

Fallacy 3 is the fallacy that thread-safety is all about competing for simultaneous access. Memory caching however means that to obtain a coherent state within a const method there may still be a requirement to ensure some kind of memory barrier has been performed (e.g. at least “acquire”).

答:
Although const as a language feature does not guarantee thread safetyness, lot of the constant functions, by their nature, happens to be threadsafe as they typically just read some constant variables, calculate a result and give it back. This is the bitwise constant mentioned in the video. The cases where internal synchronization is needed (I beleive) are in minority.

You see this by itself creates a (false) security feeling in a programmer who intuitively thinks a function is threadsafe because it is constant.

So I personally support the convention, that if a function is constant, but not bitwise constant, then synchronize inernally to make it threadsafe, because potential users will expect it to be.

This convention is followed in the STL as mentioned in the presentation, which further strengthens the expactation of the users.

The fallacy that if you only call const methods on a class your application has a thread-safe guarantee and you can complain to the implementer if not.

I beleive this is intended. As a user of a library, it does not cause any harm if you are careful about it, but as a library implementor you would better follow this convention.

Fallacy 3 is the fallacy that thread-safety is all about competing for simultaneous access. Memory caching however means that to obtain a coherent state within a const method there may still be a requirement to ensure some kind of memory barrier has been performed (e.g. at least “acquire”).

Maybe const == thread-safe would have been better written as const ==> thread-safe. I don't think Herb Sutter's intention was to state that const is the ultimate silver bullet in thread safetyness. In my interpretation the message is no more, then that when you write a const function, your intention should be to also make it threadsafe.

ContentLicense: CC BY-SA 3.0

Title: Const means Thread-safe?


问:
OCaml criticism: is it still valid?
I am a complete newbie with OCaml. I have recently stumbled into this page listing a good amount of criticism towards OCaml.

Seeing that the page it quite old (2007): which of the bullets points listed there are still true today? For instance: is it still true that it is impossible to print a generic object?

I want to make it clear that I am not looking for a discussion of the opinions expressed therein. I am asking whether the information listed, such as the fact that integers overflow without warnings, is still correct for more recent versions of OCaml

答:
This article is discussed at several places:

caml.inria.fr

Hacker News

Reddit

To summarize: yes, OCaml is not a Lisp, and no, it is not perfect (what does that mean?). I don't think the points mentioned in the blog post are relevant for day-to-day O'Caml programmers.

Having studied O'Caml, I think it is an interesting language which can help you build programs you would not even dare write in, say, C/C++/Java: for example, have a look  at
Frama-C.

For an up-to-date description of O'Caml, I encourage you to read about its features: the language promotes strong static type checking techniques which allows implementations to focus on producing performant, yet safe, runtimes.

Important: I am no OCaml expert: if you are one of them and see I wrote something horribly wrong, please correct me. I'll edit this post accordingly.

Static type checking

False Sense of Security

This is true, but obvious.

Static typing gives you proofs you can trust about a subset of your program's properties. Unless you accept to go all formal, an average (non-toy) program will be subject to programming error bugs which can be witnessed only at runtime.

That's when dynamic checking techniques can be applied: the OCaml compiler has flags to generate executables with debugging information, and so on... Or, it can generate code that blindly trust the programmer and erase type information as much as possible. Programmers who wants robust programs should implement dynamic checks explicitly.

The same thing applies to e.g. Common Lisp, but reversed: dynamic types first, with optional type declarations and compiler directives second.

Few Basic Types

Still applies: the core language has not changed (or not dramatically).

Silent Integer Overflow

This is the norm in most languages that integer overflow are checked by hands.
I don't know of any library that would type-check operations to verify whether  overflow can occur.

Module Immutability

Author mentions Functors but I fail to see how his example cannot be implemented. Reading the First Class Modules chapter of https://realworldocaml.org, it seems that modules can be used to compose and build new modules. Of course, modifying an existing module requires source code modification, but again, this is not unusual among programming languages.

"Semantically, functions are compiled INLINE"

The reddit thread above disagrees, saying that binding are resolved at link time. However, this is an implementation detail and I think that the emphasized Semantically relates to the way functions are resolved. Example:

```<code> let f x y = x + y ;;
 let g a b = f b a ;;
 let f x y = x * y ;;
 exit (g 2 3) ;;
</code>```

The above program compiles, and when executed, returns 5, because g is defined with the first version of f, just as-if the calling function g inlined the call to f. This is not "bad", by the way, it is just consistent with O'Caml's name shadowing rules.

To summarize: yes, modules are immutable. But they are also composable.

Polymorphism Causes Run-time Type Errors

I can't reproduce the mentioned error. I suspect it to be a compiler error.

No Macros

Indeed, there are no macros but preprocessors (OcamlP4, OcamlP5, ...).

Wrappers (with-open-file)

Knowing how UNWIND-PROTECT can be useful, this is indeed painful to see it absent from more languages. Here are some options:

Improving Exception Management In OCaml

Extend OCaml Syntax

Places

I don't think generalized references exist in OCaml.

Minor Language Suckiness

Record field naming hell

True, but you should use modules:

Two fields of two records have same label in OCaml

Resolving field names

Syntax

Still applies (but really, this is just syntax).

No Polymorphism

Still applies, but somehow there are people who prefer that instead of Lisp's numerical tower (I don't know why). I suppose it helps with type inference.

Inconsistent function sets

See the OCaml Batteries Included project.
In particular,  BatArray, for an example of map2 for arrays.

No dynamic variables

Can be implemented:

http://okmij.org/ftp/ML/dynvar.txt

http://okmij.org/ftp/ML/index.html#dynvar

Optional ~ arguments suck

By language restriction, you can't mix optional and keywords arguments in Common Lisp.
Does it mean it sucks? (off course, this can be changed with macros (see e.g. my answer)).
See O'Caml's documentation for optional and named arguments in O'Caml.

Partial argument application inconsistency

I don't think it this is really annoying in practice.

Arithmetic's readability

It holds, but you can use R or Python for numerical problems if you prefer.

Silent name conflict resolution

Still applies, but note that this is well documented.

No object input/output

Still applies.

Implementation, libraries

These keep changing every day: there is no definitive answer.

Finally,

"You should try OCaml (or, better yet, Haskell) even if you think
  it sucks and you are not planning to use it. Without it, your
  Computer Science education is incomplete, just like it is incomplete
  without some Lisp and C (or, better yet, Assembly) exposure."

... still applies.

Title: OCaml criticism: is it still valid?

Body:
This article is discussed at several places:

caml.inria.fr

Hacker News

Reddit

To summarize: yes, OCaml is not a Lisp, and no, it is not perfect (what does that mean?). I don't think the points mentioned in the blog post are relevant for day-to-day O'Caml programmers.

Having studied O'Caml, I think it is an interesting language which can help you build programs you would not even dare write in, say, C/C++/Java: for example, have a look  at
Frama-C.

For an up-to-date description of O'Caml, I encourage you to read about its features: the language promotes strong static type checking techniques which allows implementations to focus on producing performant, yet safe, runtimes.

Important: I am no OCaml expert: if you are one of them and see I wrote something horribly wrong, please correct me. I'll edit this post accordingly.

Static type checking

False Sense of Security

This is true, but obvious.

Static typing gives you proofs you can trust about a subset of your program's properties. Unless you accept to go all formal, an average (non-toy) program will be subject to programming error bugs which can be witnessed only at runtime.

That's when dynamic checking techniques can be applied: the OCaml compiler has flags to generate executables with debugging information, and so on... Or, it can generate code that blindly trust the programmer and erase type information as much as possible. Programmers who wants robust programs should implement dynamic checks explicitly.

The same thing applies to e.g. Common Lisp, but reversed: dynamic types first, with optional type declarations and compiler directives second.

Few Basic Types

Still applies: the core language has not changed (or not dramatically).

Silent Integer Overflow

This is the norm in most languages that integer overflow are checked by hands.
I don't know of any library that would type-check operations to verify whether  overflow can occur.

Module Immutability

Author mentions Functors but I fail to see how his example cannot be implemented. Reading the First Class Modules chapter of https://realworldocaml.org, it seems that modules can be used to compose and build new modules. Of course, modifying an existing module requires source code modification, but again, this is not unusual among programming languages.

"Semantically, functions are compiled INLINE"

The reddit thread above disagrees, saying that binding are resolved at link time. However, this is an implementation detail and I think that the emphasized Semantically relates to the way functions are resolved. Example:

 let f x y = x + y ;;
 let g a b = f b a ;;
 let f x y = x * y ;;
 exit (g 2 3) ;;

The above program compiles, and when executed, returns 5, because g is defined with the first version of f, just as-if the calling function g inlined the call to f. This is not "bad", by the way, it is just consistent with O'Caml's name shadowing rules.

To summarize: yes, modules are immutable. But they are also composable.

Polymorphism Causes Run-time Type Errors

I can't reproduce the mentioned error. I suspect it to be a compiler error.

No Macros

Indeed, there are no macros but preprocessors (OcamlP4, OcamlP5, ...).

Wrappers (with-open-file)

Knowing how UNWIND-PROTECT can be useful, this is indeed painful to see it absent from more languages. Here are some options:

Improving Exception Management In OCaml

Extend OCaml Syntax

Places

I don't think generalized references exist in OCaml.

Minor Language Suckiness

Record field naming hell

True, but you should use modules:

Two fields of two records have same label in OCaml

Resolving field names

Syntax

Still applies (but really, this is just syntax).

No Polymorphism

Still applies, but somehow there are people who prefer that instead of Lisp's numerical tower (I don't know why). I suppose it helps with type inference.

Inconsistent function sets

See the OCaml Batteries Included project.
In particular,  BatArray, for an example of map2 for arrays.

No dynamic variables

Can be implemented:

http://okmij.org/ftp/ML/dynvar.txt

http://okmij.org/ftp/ML/index.html#dynvar

Optional ~ arguments suck

By language restriction, you can't mix optional and keywords arguments in Common Lisp.
Does it mean it sucks? (off course, this can be changed with macros (see e.g. my answer)).
See O'Caml's documentation for optional and named arguments in O'Caml.

Partial argument application inconsistency

I don't think it this is really annoying in practice.

Arithmetic's readability

It holds, but you can use R or Python for numerical problems if you prefer.

Silent name conflict resolution

Still applies, but note that this is well documented.

No object input/output

Still applies.

Implementation, libraries

These keep changing every day: there is no definitive answer.

Finally,

"You should try OCaml (or, better yet, Haskell) even if you think
  it sucks and you are not planning to use it. Without it, your
  Computer Science education is incomplete, just like it is incomplete
  without some Lisp and C (or, better yet, Assembly) exposure."

... still applies.


问:
Sharing code logic between controllers, through the Model layer?
As I originally conceived my Model layer, it was only supposed to hold data and no code.
I receive DTOs from web-services, they are mapped into my Model objects. Those model objects usually end up being either composed or specialized into ViewModel objects.
In most cases, a controller calls some web-services and create a ViewModel object that it hands to the View. In reality, I sometimes have to create a class in the Model layer, next to my data objects, that hold some business logic. The reason for that is that this logic is shared between controllers. When some code is not specific at all and doesn't require much « configuration » I create short static methods, what I understand to be what one commonly calls « helpers ». I created a « Helpers » folder at the same level as my « Controllers », « Views », « Models », « ViewModels » folders. Is it right in terms of project structure ? Don't know.

Now it happens that I need to share some code, that requires some configuration, between controllers. For example, at some point, the business code has to call a web-service with various parameters related to the ongoing computation. Among thoses parameters is a session key. This session key therefore has to be configured to the business object before the treatment begins.

After the business code did his job, the controller hands the model to a view. This model, while not varying in terms of object class, could use data built by various business objects. In my case, I have a partial view showing a tree. The data of the tree can come from different web-services that require different inputs and yield different results. Only the resulting model has a constraint of object type.

In the beginning I had this...

The controller retrieved the data from the web-service and then builded a tree structure with some treatment. This structure was handed to a ViewModel object, which was then handed to the view.

But then, as I needed to access the code building the tree structure from an other controller, I isolated this code in what I instinctivelly called a « builder ». This object was to be initialized by any controller that needed it, before calling the BuildHierarchy() method.
Now, I need to create a second tree building logic, based on other data from another web-service. But I wish to use the same view to display those data.

From a more general point of view, here is how I currently imagine the structure of such a code...

So I have two questions :

I read a bit about the Builder pattern, and I understand I shouldn't call my object a « builder » and that this pattern is not well suited to this case. Is there some pattern corresponding to what I wish to accomplish ?

In my project structure, where should I actually put those business objects ? Am I right to put them in the Model layer, or should it be somewhere else ?

答:
So in the ideal world your controller should not contain any business logic or business objects. These should be completely located in your domain model layer. Referencing to "Patterns of Enterprise Application Architecture" by Martin Fowler the controller is even part of the presentation layer, so only responsible to pass the input data to your business objects and return the view.

I'm not sure what you're actually doing with your builder, but if I got it right you should think about the factory pattern. A factory decides by the logic in the factory how an object shall be build, beginning from which class to use, but also which dependencies to inject (which could relate to your configuration).


问:
Reducing the complexity of over-designed code
I have just started working at a company where I have inherited a C# codebase from a previous developer. I know programming well, have an engineering degree + an (unfinished, several year long) PhD education in computer science and > 10 years of previous experience of "practical" programming, mainly in C++ and Java but also in other languages.

My problem is that the code that I have inherited is, in my opinion, absurdly over-engineered. I have enormous problems following the program flow and finding any concrete implementations of anything. The amount of abstractions are totally mind-boggling and there is no documentation whatsoever. Furthermore, it's difficult to debug the application since it's a server application which is split up into a "GUI-client" server and a "Control-Server" (also a relatively pointless abstraction since they always run on the same machine and there is a 1:1 relationship between them) which interfaces with industrial hardware which is not available.

To give an illustratory example, one of the classes have a field like this:

```<code>IClientFactory<IClient<ICommunicationService>> communicationFactory;
</code>```

I have a hard time wrapping my head around it since the previous programmer also wrote this code (i.e. not using a bit-shift, and this is one of the few things that is documented):

```<code>public static bool IsBitHigh(int value, int bitIndex) {
    int valueAbs = Math.Abs(value);
    if (bitIndex < 0)
        throw new ArgumentException("Bit index must be above or equal to 0");
    int result = valueAbs & Convert.ToInt32(Math.Pow(Convert.ToDouble(2.0), Convert.ToDouble(bitIndex - 1)));

        return (result > 0);
    }
</code>```

There are also indications that the previous programmer was surprised by the fact that casting floats to ints "rounds them down", and that's after several years in the industry.

So given this I have two questions:

Is this how code typically looks like in the industry? (I have an engineering/research background so I was under the illusion that people were still using for-loops.)

And more importantly:

Is there any easy way to reduce the complexity of the code, i.e. replace the interfaces with their concrete implementations? (To reverse-refactor the code in a sense.)

答:
My problem is that the code that I have inherited is, in my opinion,
  absurdly over-engineered. I have enormous problems following the
  program flow and finding any concrete implementations of anything. The
  amount of abstractions are totally mind-boggling and there is no
  documentation whatsoever.

Its not you, I find that a lot of C# and Java (and other "developer productivity languages" that also have tools for refactoring and 'twiddling' with code) have a preponderance of this kind of codebase, possibly because if its easy to write then there is plenty of time left over for tinkering. One company I worked for showed me a reference implementation of a webservice that had 1 method that took 1 parameter and returned a string... and was implemented using 32 C# class files in 6 assemblies. And to top it off there was a comment in one of them saying he would have used dependency injection but didn't want to over-complicate it!!! (A C equivalent would have been 32 lines of code)

So... I think the best thing to do is to work with it until you understand its layers, as I'm sure the previous developer managed to hold the overall structure in his head so he could work with it, with time you could get the same mental model of where all the bits are in order to maintain them.

An alternative is to understand the parts that fit together and consolidate them to remove much of the interfacing. eg your client-GUI and Control server can be merged but I feel this isn't the best place to attack - it might be a lot more work to add a control to the GUI (as you have to cascade the changes through both components) but that's common practice for n-tier development anyway.

Even with the morass of interfaces, they're probably OK overall. Maybe you need to consolidate some of them - not necessarily to their concrete classes as this won't give you much, but to remove much of the abstract plumbing that the interfaces were put in to support. ICommunicationService sounds like a good interface, a IClient<ICommunicationService> sounds unnecessary fluff, and getting rid of that might see IClientFactory going too as collateral damage.

All in all, you do what you can. But unfortunately it is somewhat common in the industry. Nobody understands KISS anymore :-(


问:
Should I focus on being deep or broad
I have been a professional developer for just over half a year and have been amazed at how big the world really is out of college. I have continued to learn in my free time but I am wondering where should I focus?

FOCUS 1) The development stack used by my company. Quickest payoff in my day to day development. #Deepest

FOCUS 2) A different language with the same paradigm. See if I can generalize my knowledge and way of thinking.

FOCUS 3) Different language, different paradigm. Expand my borders and learn new ways to do things. #Broadest

If anyone has a different focus feel free to put that out there.

答:
Yes.

I would say that you need to do both.  Start with #1 as that has the immediate payoff, and you haven't been doing this for very long.  But you definitely need to do some of #2 and #3.

ContentLicense: CC BY-SA 2.5

Title: Should I focus on being deep or broad


答:
I think you are missing 1 or maybe 2 layers in your design which is why you are not sure where to put business logic or 'builder' code. You should consider adding a service and possibly repository layer.

The service layer is a layer that interfaces between controllers and the model/repository. It may contain business logic or may just be a thin API layer. The repository layer is responsible for returning model objects to services or controllers (I think this is the builder concept you have mentioned).

Although, the extra layers add complexity, I prefer to separate out the responsibilities - it's usually easier to test that way and you have less problems later on when you want to replace your UI, add a web services interface etc.

Title: Sharing code logic between controllers, through the Model layer?

Body:
As I originally conceived my Model layer, it was only supposed to hold data and no code.
I receive DTOs from web-services, they are mapped into my Model objects. Those model objects usually end up being either composed or specialized into ViewModel objects.
In most cases, a controller calls some web-services and create a ViewModel object that it hands to the View. In reality, I sometimes have to create a class in the Model layer, next to my data objects, that hold some business logic. The reason for that is that this logic is shared between controllers. When some code is not specific at all and doesn't require much « configuration » I create short static methods, what I understand to be what one commonly calls « helpers ». I created a « Helpers » folder at the same level as my « Controllers », « Views », « Models », « ViewModels » folders. Is it right in terms of project structure ? Don't know.

Now it happens that I need to share some code, that requires some configuration, between controllers. For example, at some point, the business code has to call a web-service with various parameters related to the ongoing computation. Among thoses parameters is a session key. This session key therefore has to be configured to the business object before the treatment begins.

After the business code did his job, the controller hands the model to a view. This model, while not varying in terms of object class, could use data built by various business objects. In my case, I have a partial view showing a tree. The data of the tree can come from different web-services that require different inputs and yield different results. Only the resulting model has a constraint of object type.

In the beginning I had this...

The controller retrieved the data from the web-service and then builded a tree structure with some treatment. This structure was handed to a ViewModel object, which was then handed to the view.

But then, as I needed to access the code building the tree structure from an other controller, I isolated this code in what I instinctivelly called a « builder ». This object was to be initialized by any controller that needed it, before calling the BuildHierarchy() method.
Now, I need to create a second tree building logic, based on other data from another web-service. But I wish to use the same view to display those data.

From a more general point of view, here is how I currently imagine the structure of such a code...

So I have two questions :

I read a bit about the Builder pattern, and I understand I shouldn't call my object a « builder » and that this pattern is not well suited to this case. Is there some pattern corresponding to what I wish to accomplish ?

In my project structure, where should I actually put those business objects ? Am I right to put them in the Model layer, or should it be somewhere else ?


问:
VCS a Vagrant box
I have two computers (1 Laptop with Ubuntu that I use for development in 99% of my time but I also have a pretty much unused PC with Windows. I also have an unused server machine at home. I would like to use my PC for development actively because it has 2 monitors which can be extremely useful when speed is important in development.

I already have a Vagrant machine on my laptop (yes, development machine in a development machine) but it is like 50GB now which is hard to sync, even on local network. I thought of versioning my box with the server but I couldn't find any other method but uploading it and downloading it.

I thought of versioning just my files with Git to the server but I use lots of custom softwares that I don't want to bring with me on a pendrive every time I go upstairs to my PC.

The stuff I need to sync:

node.js dependencies with -g attribute (not installed locally into the source)

PHPStorm configuration (build and layout)

My latest commands in the terminal (I do lots of security stuff and I like to roll back to my last used commands if I found them with hard work

Other smaller programs

AND of course my Gimp configuration which looks 80% like PhotoShop.

Lots of these things are not on Vagrant (eg. PHPStorm) but I still need to sync them. I have enough hardware to build multiple servers if needed but I would like to keep the two computers in sync. I can install Ubuntu on my Windows machine if needed and I am open to any option that is less effort than copying 50GB to a server and then downloading it each time I change machines.

答:
What you're describing (in part) is automating the configuration of an environment. There are plenty of tools out to help with this; Puppet, Ansible, Chef to name but three.

Configuration involves making sure that the environment that your application is running in contains all the things it needs: packages, services, files, users. You could do all this by hand, but that's time consuming and error-prone. Instead, you should automate it.

The code for most (all?) configuration automation tools is plaintext, which is perfect for version controlling.

As a bonus, Vagrant supports a bunch of provisioning tools out of the box. By version controlling both your provisioning code and the Vagrantfile, you can completely automate the creation of an environment to run your application in.

But what about my IDE and such?

What you're describing, in part, is having a reproducible development environment. This can be achieved by separating the environment for you application (using Vagrant and automated configuration) from that of your machine.

Once you've automated your application environment, you have a couple of options for making a reproducible development environment:

Create an image of your primary machine, and restore that on to other machines. When you make changes to your primary machine, recreate the image and redeploy it to other machines.

Use a configuration automation tool to take a fresh install of the OS up to a desired state.

For plaintext configuration files (like those for PHPStorm), you can store them in version control and check them out as you setup the development environment.

Title: VCS a Vagrant box


问:
Do today's modern compilers perform run time checks?
This is regarding compilers.

Do compilers perform run time dependency checks to decide to vectorize a loop ? In other words, do compilers trace through the logic as it would in run-time to determine if a loop can be vectorized?

Is it that when the compiler compiles a code and if auto-vectorization is enabled(default) then the output is a vectorized code targeted with lets say AVX assembly instructions then when did it perform the dependency checks ?

答:
For a compiler to do run time checks (to find warnings and errors that cannot be found at compile time, including loop vectorization), it starts to get dangerously close to the Halting Problem.

Alan Turing proved in 1936 that a general algorithm to solve the halting problem for all possible program-input pairs cannot exist. A key part of the proof was a mathematical definition of a computer and program, which became known as a Turing machine; the halting problem is undecidable over Turing machines. It is one of the first examples of a decision problem.

Consider the following Java program:

```<code>public class Halting {
  public static void main(String... args) {
    while(isCondition()) {

    }
  }

  private static boolean isCondition() {
    return true;
  }
}
</code>```

This program returns no errors or warnings by the compiler. It would have to trace through the logic to see that it is an infinite loop. What's to stop the theoretical run time checker from getting stuck in an infinite loop the same way? The compiler can't get stuck in an infinite loop, it's not smart enough.

Notice, on the other hand, that this does have an error:

```<code>public class Halting {
  public static void main(String... args) {
    String foo = null;
    System.out.println(foo.charAt(0));
  }
}
</code>```

This yields the warning:

Null pointer access: The variable foo can only be null at this location

Such checks are the best the compiler can do. But notice that this has no warning, even though it's the same problem:

```<code>public class Halting {
  public static void main(String... args) {
    String foo = getFoo();
    System.out.println(foo.charAt(0));
  }

  private static String getFoo() {
    return null;
  }
}
</code>```

Body:
For a compiler to do run time checks (to find warnings and errors that cannot be found at compile time, including loop vectorization), it starts to get dangerously close to the Halting Problem.

Alan Turing proved in 1936 that a general algorithm to solve the halting problem for all possible program-input pairs cannot exist. A key part of the proof was a mathematical definition of a computer and program, which became known as a Turing machine; the halting problem is undecidable over Turing machines. It is one of the first examples of a decision problem.

Consider the following Java program:

public class Halting {
  public static void main(String... args) {
    while(isCondition()) {

    }
  }

  private static boolean isCondition() {
    return true;
  }
}

This program returns no errors or warnings by the compiler. It would have to trace through the logic to see that it is an infinite loop. What's to stop the theoretical run time checker from getting stuck in an infinite loop the same way? The compiler can't get stuck in an infinite loop, it's not smart enough.

Notice, on the other hand, that this does have an error:

public class Halting {
  public static void main(String... args) {
    String foo = null;
    System.out.println(foo.charAt(0));
  }
}

This yields the warning:

Null pointer access: The variable foo can only be null at this location

Such checks are the best the compiler can do. But notice that this has no warning, even though it's the same problem:

public class Halting {
  public static void main(String... args) {
    String foo = getFoo();
    System.out.println(foo.charAt(0));
  }

  private static String getFoo() {
    return null;
  }
}


问:
How to use unit tests when using BDD?
I am trying to understand BDD. I've read some articles and as I understood BDD is "the next step" from TDD.
I say that because I find both to be very similar, and as I could read in this article, BDD was born as an improvement from TDD.
Great, I really like the idea.

There is one practical point that I do not get, though: there is a .feature file in which the BA will write all the expected behavior in the system. As a BA, he has no idea how the system is built, so we will write something like this:

+Scenario 1: Account is in credit+

Given the account is in credit

And the card is valid

And the dispenser contains cash

When the customer requests cash

Then ensure the account is debited And ensure cash is dispensed

And ensure the card is returned

Ok, this is great, but there are many parts of the system that will collaborate so that it can happen (think of Account obj, Dispenser obj, Customer obj and so on). To me this looks like an integration test.

I would like to have Unit Tests.  How do I test the code that checks if the dispenser has money? Or that the cash is dispensed? Or that the account is debited when required?
How can I mix unit tests with "BA Created" tests?

答:
Disclaimer: I am not an expert in BDD, but I try to give you my point of view on the article you linked to.

TDD is an implementation technique - you first write a test, then you implement the method, run your test, refactor, and add further tests for the same method or for a new method. TDD does actually not define any rules for how to choose class or method names, that's up to you. TDD also does not tell you "when you are done".

So whenever you write a test for a new method, you have to choose a method name - and that is the point where BDD comes in. By choosing method names using the business terms from the scenario above, and by choosing them in a way describing the behaviour of your class, you are doing BDD. Whenever you ask yourself "do I have to add further tests", you can look the the scenarios given by your BA and check if you have implemented all the needed parts them completely. If not, you will need to add more tests.

The author of the article also suggest to use a more behaviour-related naming scheme when choosing the names of your tests, that's why he suggests to replace JUnit by a tool which does not rely on a naming scheme where each test case has to start with the name "test". Though I don't know JBehave, I think that's the main difference between that tool and Junit.

Moreover, the BDD scenarios will also be a blueprint for integration tests - which you will typically add after you have fleshed out the method names by TDD and after you added a reasonable amount of unit tests.

So, to my understanding, TDD is an instrument you can use as part of BDD, and BDD helps you to write the right tests and give them better names.

ContentLicense: CC BY-SA 4.0

Title: How to use unit tests when using BDD?


答:
Being a specialist can make you more expensive. But job opportunities requiring that high level will be limited, both in their numbers and geographically.

Being a generalist perhaps pays less but opens a wide variety of job opportunities to you, potentially around the world.

Also for higher level and managerial jobs it is preferred to have a person experienced in a variety of things, techniques and technologies. Knowing edges and being able to see a big picture makes you a valuable asset.

Title: Should I focus on being deep or broad

Body:
I have been a professional developer for just over half a year and have been amazed at how big the world really is out of college. I have continued to learn in my free time but I am wondering where should I focus?

FOCUS 1) The development stack used by my company. Quickest payoff in my day to day development. #Deepest

FOCUS 2) A different language with the same paradigm. See if I can generalize my knowledge and way of thinking.

FOCUS 3) Different language, different paradigm. Expand my borders and learn new ways to do things. #Broadest

If anyone has a different focus feel free to put that out there.


答:
I don't think any do, but it should be possible. For example gcc 4.8 (scroll down to IA-32/x86-64 section) has both a builtin  __builtin_cpu_supports function and function multiversioning support  that the developer can use to write different code for different architectures. I don't see why the compiler couldn't generate different codepaths dependant on the runtime using these features automatically.

For example, manually:

```<code>__attribute__ ((target ("default")))
int foo(void)
{
  return 1;
}

__attribute__ ((target ("sse4.2")))
int foo(void)
{
  return 2;
}

int main (void)
{
  int (*p) = &foo;
  assert ((*p)() == foo());
  return 0;
}
</code>```

Title: Do today's modern compilers perform run time checks?

Body:
This is regarding compilers.

Do compilers perform run time dependency checks to decide to vectorize a loop ? In other words, do compilers trace through the logic as it would in run-time to determine if a loop can be vectorized?

Is it that when the compiler compiles a code and if auto-vectorization is enabled(default) then the output is a vectorized code targeted with lets say AVX assembly instructions then when did it perform the dependency checks ?

Body:
I don't think any do, but it should be possible. For example gcc 4.8 (scroll down to IA-32/x86-64 section) has both a builtin  __builtin_cpu_supports function and function multiversioning support  that the developer can use to write different code for different architectures. I don't see why the compiler couldn't generate different codepaths dependant on the runtime using these features automatically.

For example, manually:

__attribute__ ((target ("default")))
int foo(void)
{
  return 1;
}

__attribute__ ((target ("sse4.2")))
int foo(void)
{
  return 2;
}

int main (void)
{
  int (*p) = &foo;
  assert ((*p)() == foo());
  return 0;
}


问:
Should I use multiple state machines for a layered protocol?
When implementing a layered communications protocol are layers commonly implemented as state machines?

I have an implementation of PMBus I am currently working on for an embedded device. I have a interrupt driven interface for handling how the I2C uses the H/W driver to receive and transmit bytes onto and off of a buffer, essentially serialising the data.

A state machine then implements the "middle" SMBus layer taking the data from the buffer and forming messages from it according to how the protocol dictates what to expect for a generic type message, this state machine may also adds information based on input from additional I/O lines.

A second state machine then caps the stack with the PMBus layer by checking the generic message as it applies to specific types of messages, again adding some further information from I/O lines and subsequently looks up a command handler according to the message and passes it data from the message.

The whole caboodle then works in reverse for transmitting responses from the command handler or requests by other parts of the system (which works from a third state machine) to change output on I/O lines, such as recording an error status requiring a request for service signal.

I'm coming from a low level embedded background with little real-job programming experience consequently having only a little idea of the expected and accepted design patterns for common problems. Thus my question; is such state machine layering a common or logically expected solution to implementing layered protocols?

It seemed effective and robust to me (a soft requirement is that the layer functionality be encapsulated) when I thought it up some time ago but looking back on it it begins to seem somewhat over-engineered and that there could be some simpler method.

EDIT: I remembered the main reason that I followed this route is so that the execution of the higher layers is de-coupled from the interrupt driven interface. This is handy because from an interrupt for data being received up to the return from the command handler for the transmitted data may (depending on how the implementation is to be used) may constitute a relatively long time in comparison to my device's main business logic which operates quite fast and has a worst-case execution time requirement. Thus my business logic state machine (the third one from above) is what calls the protocol state machines, from the top on down, when it has time to. This means that while data receipt and transmission is asynchronous, the processing of the data is not.

答:
I don't know about industry standards, but I have used state-machines in multiple layers of a communication protocol stack (sp. the PS/2 protocol) for the same reasons you gave; it worked pretty well: it allowed me to coordinate and control everything that was going on, esp. the interrupt-driven stuff.

Even though it went ok for me, I think you should pay heed to the advice and warnings of @thepacker and @caveman, because there is more overhead and complexity involved in running and coordinating multiple machines; you also have to be rigorous so that the design doesn't get away from you.

I should also mention that I have not had to maintain the stack -- it was a one-off project -- so I'm not sure how things would grow over time.

Problem areas I recall having had when designing things (it's been a few years and more than a few projects since I worked on this, so my recollection may be inaccurate) were having the machines of the different layers communicate with each other -- I ended up using static data, with accessor functions, shared between layers -- and controlling error handling. In the end my design had machines in each layer controlling the machine(s) in the layer below it for transmission; I forget how exactly reception was structured, but it was sort of on a separate band of control from the transmission.

As an alternative to using state-machines you might check out functional reactive programming (this looks like a nice tutorial on reactive programming). Though you probably won't be able to use it directly in an embedded project, it might give you some ideas on how to approach things.

If you still want to use state-machines, I've had good experience implementing them in C with this approach:

Use 3 functions to define and control the machine:

```<code>// get the next state based on the current
// state and the transition input --
// this should be a pure function
static State findNextState(prevState, input);

// react to a state transition --
// side-effects go in here
static void reactToStateTransition(prevState, nextState, input);

static State currentState = INIT;

// control the machine's state and
// call the other two functions
void transitionStates(input)
{
    State prevState = currentState;
    State nextState = findNextState(prevState, input);

    if (prevState != nextState)
    {
        reactToStateTransition(prevState, nextState, input);
        currentState = nextState;
    }
}
</code>```

Then you can use this to transition states in, say, an interrupt:

```<code>void isr()
{
    transitionStates(SOMETHING_HAPPENED);
}
</code>```

Or, better yet, have the interrupt flag for the transition to be carried out by non-interrupt-level code.

This structure works well for small- to medium-sized flat machines, but if you get a lot of states with a lot of transitions or, worse yet, nested state-machines, it doesn't handle things so well.

Body:
I don't know about industry standards, but I have used state-machines in multiple layers of a communication protocol stack (sp. the PS/2 protocol) for the same reasons you gave; it worked pretty well: it allowed me to coordinate and control everything that was going on, esp. the interrupt-driven stuff.

Even though it went ok for me, I think you should pay heed to the advice and warnings of @thepacker and @caveman, because there is more overhead and complexity involved in running and coordinating multiple machines; you also have to be rigorous so that the design doesn't get away from you.

I should also mention that I have not had to maintain the stack -- it was a one-off project -- so I'm not sure how things would grow over time.

Problem areas I recall having had when designing things (it's been a few years and more than a few projects since I worked on this, so my recollection may be inaccurate) were having the machines of the different layers communicate with each other -- I ended up using static data, with accessor functions, shared between layers -- and controlling error handling. In the end my design had machines in each layer controlling the machine(s) in the layer below it for transmission; I forget how exactly reception was structured, but it was sort of on a separate band of control from the transmission.

As an alternative to using state-machines you might check out functional reactive programming (this looks like a nice tutorial on reactive programming). Though you probably won't be able to use it directly in an embedded project, it might give you some ideas on how to approach things.

If you still want to use state-machines, I've had good experience implementing them in C with this approach:

Use 3 functions to define and control the machine:

// get the next state based on the current
// state and the transition input --
// this should be a pure function
static State findNextState(prevState, input);

// react to a state transition --
// side-effects go in here
static void reactToStateTransition(prevState, nextState, input);

static State currentState = INIT;

// control the machine's state and
// call the other two functions
void transitionStates(input)
{
    State prevState = currentState;
    State nextState = findNextState(prevState, input);

    if (prevState != nextState)
    {
        reactToStateTransition(prevState, nextState, input);
        currentState = nextState;
    }
}

Then you can use this to transition states in, say, an interrupt:

void isr()
{
    transitionStates(SOMETHING_HAPPENED);
}

Or, better yet, have the interrupt flag for the transition to be carried out by non-interrupt-level code.

This structure works well for small- to medium-sized flat machines, but if you get a lot of states with a lot of transitions or, worse yet, nested state-machines, it doesn't handle things so well.


问:
Difficulty in deciding correct data structure
Two objects are interacting (Object Alpha, Object Beta)

Each contain a point (x,y) which will be used to make comparisons, among other things.

Object Alpha's point (x,y) attribute is dynamic and will change.

Object Beta's point (x,y) attribute is final.

I need to construct a data structure that contains all Object Beta's.

I was thinking of some sort of multidirectional arraylist with an index corresponding to the values of the point attribute so I can simply iterate backward and forwards to find the closest Beta's within a given range, however, how would I construct a datastructure like this?

Perhaps a linked multidimensional array?  Although this would be incredibly complex when one adds or removes elements.

Any other thoughts?

Use case - Object Beta essentially is an object occupying an object in real space.  Ie, it's point attribute corresponds to it's GPS location.  Object Alpha is another object in real space and it's point attribute also corresponds to a GPS location. I want to quickly find the closest x amount of Beta's to Alpha's present location.  Also add and remove Beta from this structure without completely redefining the entire structure.  There could potentially be 1000+ object Beta's in this data structure.

答:
I recommend using an R-tree (link to Wikipedia). This is the standard data structure that most use for doing this sort of spatial indexing.

R-trees are tree data structures used for spatial access methods, i.e., for indexing multi-dimensional information such as geographical coordinates, rectangles or polygons. The R-tree was proposed by Antonin Guttman in 1984[1] and has found significant use in both theoretical and applied contexts.[2] A common real-world usage for an R-tree might be to store spatial objects such as restaurant locations or the polygons that typical maps are made of: streets, buildings, outlines of lakes, coastlines, etc. and then find answers quickly to queries such as "Find all museums within 2 km of my current location", "retrieve all road segments within 2 km of my location" (to display them in a navigation system) or "find the nearest gas station" (although not taking roads into account). The R-tree can also accelerate nearest neighbor search[3] for various distance metrics, including great-circle distance.[4]

This is a pretty thoroughly explored topic, I recommend reading the entire Wikipedia article linked at the top of the answer.

Implementations in a few different languages:

Java R-Tree

Python R-Tree

C# R-Tree


答:
Behavior Driven Development and Test Driven Development are complimentary, but not a replacement for each other.

How the application "behaves" is described in Acceptance Tests, which according to BDD would be the Features and Scenarios written in Cucumber.

The nitty gritty details of how each small component works are described in Unit Tests. The outcomes of the Unit Tests support the Scenarios you write in Cucumber.

Imagine the process for building a car.

First, the product team comes up with their ideas, and eventually boil them down to usage scenarios:

```<code>Scenario: Starting the car
    Given I am standing in front of the drivers door
    When I open the door
    Then the door should lift up DeLorean-style (yeah, baby!)
    When I get into the car
    And turn the key
    Then the engine roars to life
</code>```

I know this scenario sounds a bit silly, but it is a very high level, product and end user focused requirement. Just opening the door, turning the key and starting the engine involves a LOT of different components working together. This one test is not enough to make sure the vehicle works properly. You need to test the starter, the battery, the alternator, key, ignition switch --- and the list goes on --- just to get into the car and start it. Each of those components need their own tests.

The scenario above is a "Big Picture" test. Each component of the vehicle needs "Small Picture" tests to make sure they function properly within the whole.

Building and testing software is the same in many respects. You design from top down, then build from bottom up. Why have a door that lifts up if you can't even start the engine? Why have a starter if you have no battery?

Your product team will come up with the Acceptance Tests and flesh them out in Cucumber. This gives you the "Big Picture". Now it's up to the engineering team to design the proper components, and how they interact, then test each one separately --- these are your Unit Tests.

Once the Unit Tests are passing, start implementing the Cucumber scenarios. Once those are passing, you have delivered what the product team has asked.

Title: How to use unit tests when using BDD?

Body:
I am trying to understand BDD. I've read some articles and as I understood BDD is "the next step" from TDD.
I say that because I find both to be very similar, and as I could read in this article, BDD was born as an improvement from TDD.
Great, I really like the idea.

There is one practical point that I do not get, though: there is a .feature file in which the BA will write all the expected behavior in the system. As a BA, he has no idea how the system is built, so we will write something like this:

+Scenario 1: Account is in credit+

Given the account is in credit

And the card is valid

And the dispenser contains cash

When the customer requests cash

Then ensure the account is debited And ensure cash is dispensed

And ensure the card is returned

Ok, this is great, but there are many parts of the system that will collaborate so that it can happen (think of Account obj, Dispenser obj, Customer obj and so on). To me this looks like an integration test.

I would like to have Unit Tests.  How do I test the code that checks if the dispenser has money? Or that the cash is dispensed? Or that the account is debited when required?
How can I mix unit tests with "BA Created" tests?

Body:
Behavior Driven Development and Test Driven Development are complimentary, but not a replacement for each other.

How the application "behaves" is described in Acceptance Tests, which according to BDD would be the Features and Scenarios written in Cucumber.

The nitty gritty details of how each small component works are described in Unit Tests. The outcomes of the Unit Tests support the Scenarios you write in Cucumber.

Imagine the process for building a car.

First, the product team comes up with their ideas, and eventually boil them down to usage scenarios:

Scenario: Starting the car
    Given I am standing in front of the drivers door
    When I open the door
    Then the door should lift up DeLorean-style (yeah, baby!)
    When I get into the car
    And turn the key
    Then the engine roars to life

I know this scenario sounds a bit silly, but it is a very high level, product and end user focused requirement. Just opening the door, turning the key and starting the engine involves a LOT of different components working together. This one test is not enough to make sure the vehicle works properly. You need to test the starter, the battery, the alternator, key, ignition switch --- and the list goes on --- just to get into the car and start it. Each of those components need their own tests.

The scenario above is a "Big Picture" test. Each component of the vehicle needs "Small Picture" tests to make sure they function properly within the whole.

Building and testing software is the same in many respects. You design from top down, then build from bottom up. Why have a door that lifts up if you can't even start the engine? Why have a starter if you have no battery?

Your product team will come up with the Acceptance Tests and flesh them out in Cucumber. This gives you the "Big Picture". Now it's up to the engineering team to design the proper components, and how they interact, then test each one separately --- these are your Unit Tests.

Once the Unit Tests are passing, start implementing the Cucumber scenarios. Once those are passing, you have delivered what the product team has asked.


问:
Constructor-only subclasses: Is this an anti-pattern?
I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.

To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.

For example, consider this somewhat real-life class:

public class DataHelperBuilder
{
    public string DatabaseEngine { get; set; }
    public string ConnectionString { get; set; }

    public DataHelperBuilder(string databaseEngine, string connectionString)
    {
        DatabaseEngine = databaseEngine;
        ConnectionString = connectionString;
    }

    // Other optional "DataHelper" configuration settings omitted

    public DataHelper CreateDataHelper()
    {
        Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
        DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
        dh.SetConnectionString(ConnectionString);

        // Omitted some code that applies decorators to the returned object
        // based on omitted configuration settings

        return dh;
    }
}
```

<p>His claim is that it would be entirely appropriate to have a subclass like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class SystemDataHelperBuilder
{
    public SystemDataHelperBuilder()
        : base(Configuration.GetSystemDatabaseEngine(),
               Configuration.GetSystemConnectionString())
    {
    }
 }
</code>```

So, the question:

Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

If it is an anti-pattern, what is its name?

I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.

答:
Which of these intuitions is correct?

Your coworker is correct (assuming standard type systems).

Think about it, classes represent possible legal values. If class A has one byte field F,  you might be inclined to think that A has 256 legal values, but that intuition is incorrect. A is restricting "every permutation of values ever" to "must have field F be 0-255".

If you extend A with B which has another byte field FF, that is adding restrictions. Instead of "value where F is byte", you have "value where F is byte && FF is also byte". Since you're keeping the old rules, everything that worked for the basetype still works for your subtype. But since you're adding rules, you're further specializing away from "could be anything".

Or to think of it another way, assume that A had a bunch of subtypes: B, C, and D. A variable of type A could be any of these subtypes, but a variable of type B is more specific. It (in most type systems) cannot be a C or a D.

Is this an anti-pattern?

Enh? Having specialized objects is useful and not clearly detrimental to code. Achieving that result by using subtyping is perhaps a little questionable, but depends on what tools you have at your disposal. Even with better tools this implementation is simple, straightforward and robust.

I would not consider this an anti-pattern since it is not clearly wrong and bad in any situation.


问:
Should I use an open source client framework or create my own?
I am working at a medium sized internet company, and I was handed the task of implementing the framework for our sites rebranding.

It's quite an old (and ugly) site, and we want to update its look and feel (UI/UX) as fast as possible, but also with a good foundation for the future.

I started to check out Zurb's Foundation and Twitter's Bootstrap, and I was impressed with the features they hold (like responsiveness).

My only reservations were that we have designers made a design that will be impossible to create without massive customization, and the fact that we have some important (and ancient) HTML and JS that will be prohibitively difficult to remake with a ready made framework. So I was wondering if I should make a basic lean framework myself, that over time we can add features to, without starting to override designs and code structures that were made for similar, but different things.

答:
Spending a lot of time on yet another framework to perform CSS polyfills, implement a grid system, and handle basic responsive design is a major productivity drag. And – no offense – it's very tough to get this stuff right across browsers. So starting with a well-tested, hardened CSS boilerplate is how I would go.

That said, Bootstrap isn't the only cowboy in town these days. In my opinion Bootstrap's style is very opinionated; that is, it's difficult to make your site not appear as its using Bootstrap under the covers. Kind of like when you visit a mobile page generated with jQuery Mobile.

In this case I think Skeleton is a better choice. It will give you some CSS resets, a grid system, and basic responsive design without influencing your site's appearance.


答:
No, it's not an anti-pattern. I can think of a number of practical use cases for this:

If you want to use compile time checking to make sure collections of objects only conform to one particular subclass. For example, if you have MySQLDao and SqliteDao in your system, but for some reason you want to make sure a collection only contains data from one source, if you use subclasses as you describe you can have the compiler verify this particular correctness. On the other hand, if you store the data source as a field, this would become a run-time check.

My current application has a one to one relationship between AlgorithmConfiguration + ProductClass and AlgorithmInstance. In other words, if you configure FooAlgorithm for ProductClass in the properties file, you can only get one FooAlgorithm for that product class. The only way to get two FooAlgorithms for a given ProductClass is to create a subclass FooBarAlgorithm. This is okay, because it makes the properties file easy to use (there is no need for syntax for many different configurations in one section in the properties file), and it's very rare there will be more than one instance for a given product class.

@Telastyn's answer gives another good example.

Bottom line: There isn't really any harm in doing this. An Anti-pattern is defined to be:

An anti-pattern (or antipattern) is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive.

There is no risk of being highly counterproductive here, so it's not an anti-pattern.

Title: Constructor-only subclasses: Is this an anti-pattern?

Body:
I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.

To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.

For example, consider this somewhat real-life class:

public class DataHelperBuilder
{
    public string DatabaseEngine { get; set; }
    public string ConnectionString { get; set; }

    public DataHelperBuilder(string databaseEngine, string connectionString)
    {
        DatabaseEngine = databaseEngine;
        ConnectionString = connectionString;
    }

    // Other optional "DataHelper" configuration settings omitted

    public DataHelper CreateDataHelper()
    {
        Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
        DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
        dh.SetConnectionString(ConnectionString);

        // Omitted some code that applies decorators to the returned object
        // based on omitted configuration settings

        return dh;
    }
}
```

<p>His claim is that it would be entirely appropriate to have a subclass like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class SystemDataHelperBuilder
{
    public SystemDataHelperBuilder()
        : base(Configuration.GetSystemDatabaseEngine(),
               Configuration.GetSystemConnectionString())
    {
    }
 }
</code>```

So, the question:

Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

If it is an anti-pattern, what is its name?

I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.


答:
If all you want to do is create class X with certain arguments, subclassing is an odd way of expressing that intent, because you aren't using any of the features that classes and inheritance give you. It's not really an anti-pattern, it's just strange and a bit pointless (unless you have some other reasons for it). A more natural way of expressing this intent would be a Factory Method, which in this case is a fancy name for your "helper method."

Regarding the general intuition, both "more specific" and "a limited range" are potentially harmful ways of thinking about subclasses, because they both imply that making Square a subclass of Rectangle is a good idea. Without relying on something formal like LSP, I would say a better intuition is that a subclass either provides an implementation of the base interface, or extends the interface to add some new functionality.


问:
Setting Up "Internal" Network Between Multiple Servers?
So I have a few servers who handle different things.  One is for a forward-facing website, one is an internally used website, as well as a few servers that host DB's.

I am in the process of writing a micro-service who will be used from both the front-facing and internally-facing website.  Any traffic between either server and this micro-service will need to be encrypted, and the micro-service shouldn't be accessible from the outside world.

Not knowing how this is normally done, it would seem that setting up a VPN would be the correct move on how to secure this sort of cross-server traffic.  (If this assumption is wrong and there are better solutions, please let me know.)  Setting this sort of thing up would also have the benefit of having the DB's accessible only to those who have access to the VPN (currently handled by the DB's authentication strategy).

After researching VPN solutions, OpenVPN seemed to have came out on top.  It seems to offer the best security and seems to work on Linux servers without too much hassle.

My question is how are most OpenVPN's setup when it comes to a group of servers, one main authentication server and the network's members?  Or would you have to have multiple servers and set them up to use the same certificate?  Once you authenticate to the VPN, can you make direct connections to other servers that are on the network?

I'm imagining a situation like this:

```<code>server1 = VPNServer
server2 = VPNClient - Website
server3 = VPNClient - Service
server4 = VPNClient - DB
</code>```

Say server2 and server4 need to transmit data, will that connection go directly from server2 > server4, or will the actual traffic look like server2 > server1 > server4?  Or is it set up so that once you authenticate to the VPN, all the members of the VPN are then directly accessible?

I have a vague understanding of how VPN's work, but this understanding obviously breaks down when it comes to having multiple members on the network.

How I'm envisioning setting up the VPN currently (sorry for the low quality):

答:
Your diagram is almost spot on for some of the more common methods. The server 3 and 4 are in what is referred to as a DMZ or protected private network. Server 2 is redundant but depending on your situation and level of security you have to enforce might have a role. For this explanation, i'll remove it as it will create complications when trying to administer server #2.

One method you might consider to make this work:

Make server2 a 'multi-home' server. It's primary nic is connected to the public address or public network behind a firewall. Then, a second NIC which is homed to an internal private network. (ie: public nic 205.205.205.3, private nice, 192.168.2.3)

Your vpn device is also multi-homed (typically out of the box they come this way) and can be used to connect the public network into the private network by way of some VPN technology like IPSEC or PPTP (old microsoft vpn technology) from the public network and allow you to control who has access to this private network. This can be completely independent of server2 but would allow you to connect to the second nic of server2 as well. (ie: public nic 205.205.205.2, private nic 192.168.2.2)

Servers 3 and 4 are private nic only like 192.168.2.4 and 192.168.2.5

firewall/router at public before server 2 from the ISP might be 205.205.205.1

Adding your own public internal network like 10.1.1.0/24 behind a firewall allows you a lot of control over how ports are mapped to servers in case you have more public facing machines in the future. Again a large topic but a starting point to consider.

On server #2, most software allows you to control which IP the service responds too or you can configure a firewall on server2 to only allow certain traffic from the public network like port 80 and no filters on the internal nic as an example. I would recommend at least a hardware firewall to sit between server 2 and the public network. This way, even a compromised server still cannot answer to a public port unless the hardware firewall allows it.

Also, for clarity, database and other service calls from server #2 go directly from nic#2 (the private network nic) to the target machines. In a high security environment, this may involve other firewalls between these machines but that gets into a level of protection beyond the scope of this answer. Unless you are working with bank data or hippa data, its' probably overkill. However, it depends on your client's data security policies.

I can add more details based on feedback. This can be a huge subject but hopefully this will help you get started.


答:
A subtype is never "wrong" as long as you can always replace an instance of its supertype with an instance of the subtype and have everything still work correctly. This checks out as long as the subclass never tries to weaken any of the guarantees the supertype makes. It can make stronger (more specific) guarantees, so in that sense your coworker's intuition is correct.

Given that, the subclass you made probably isn't wrong (since I don't know exactly what they do, I can't say for sure.) You need to be wary of the fragile base class problem, and you also have to consider whether an interface would benefit you, but that's true of all uses of inheritance.


问:
Why are structs and classes separate concepts in C#?
While programming in C#, I stumbled upon a strange language design decision that I just can't understand.

So, C# (and the CLR) has two aggregate data types: struct (value-type, stored on the stack, no inheritance) and class (reference-type, stored on the heap, has inheritance).

This setup sounds nice at first, but then you stumble upon a method taking a parameter of an aggregate type, and to figure out if it is actually of a value type or of a reference type, you have to find its type's declaration. It can get really confusing at times.

The generally accepted solution to the problem seems to be declaring all structs as "immutable" (setting their fields to readonly) to prevent possible mistakes, limiting structs' usefulness.

C++, for example, employs a much more usable model: it allows you to create an object instance either on the stack or on the heap and pass it by value or by reference (or by pointer). I keep hearing that C# was inspired by C++, and I just can't understand why didn't it take on this one technique. Combining class and struct into one construct with two different allocation options (heap and stack) and passing them around as values or (explicitly) as references via the ref and out keywords seems like a nice thing.

The question is, why did class and struct become separate concepts in C# and the CLR instead of one aggregate type with two allocation options?

答:
The reason C# (and Java and essentially every other OO language developed after C++) did not copy C++'s model in this aspect is because the way C++ does it is a horrendous mess.

You correctly identified the relevant points above: struct: value type, no inheritance.  class: reference type, has inheritance.  Inheritance and value types (or more specifically, polymorphism and pass-by-value) don't mix; if you pass an object of type Derived to a method argument of type Base, and then call a virtual method on it, the only way to get proper behavior is to ensure that what got passed was a reference.

Between that and all the other messes that you run into in C++ by having inheritable objects as value types (copy constructors and object slicing come to mind!) the best solution is to Just Say No.

Good language design isn't just implementing features, it's also knowing what features not to implement, and one of the best ways to do this is by learning from the mistakes of those who came before you.


答:
I think the key to answering this question is to look at this one, particular usage scenario.

Inheritance is used to enforce database configuration options, like the connection string.

This is an anti pattern because the class is violating the Single Responsibility Principal --- It is configuring itself with a specific source of that configuration and not "Doing one thing, and doing it well." The configuration of a class should not be baked into the class itself. For setting database connection strings, most times I've seen this happen at the application level during some sort of event occurring as the application is started up.


问:
Anything wrong with direct evaluation of JSON if your own code created it?
Suppose I have a server-side variable containing JSON (named strJSON) that my own code created.  In JavaScript I can consume it like this:

```<code>var data = <%= strJSON %>;
</code>```

or use a JSON parsing library:

```<code>var data = JSON.parse('<%= HttpUtility.JavaScriptStringEncode(strJSON) %>');
</code>```

I prefer the 2nd, for safety. Is what I'm doing unnecessary?

答:
Suppose I have a server-side variable containing JSON, called strJSON that my own code created.

Was it created entirely by your code?  Are you certain that at no point does it add in a piece of user input?  Are you also certain that at no point in the future will it ever be modified to add in data that comes from user input?  If you can be 100% sure of this, then you're probably safe.  But since that's hard to be certain of, it's probably best to just use the built-in JSON parsing functions.


答:
If the JSON string is encoded entirely under your control, it is exploitable to the extent that your encoding method is broken. That said, you should be safe if you're performing a straightforward serialization using a trusted serializer, like so:

```<code>var js = new JavaScriptSerializer();
var thingy123 = ThingyRepo.Get(123);
var json = js.Serialize(thingy123);

Response.Write(json); // or whatever
</code>```

You should be safe, even if thingy123 contains user-submitted data. A well-established JSON serializer will safely encapsulate everything in a "non-executable" JSON format.

But, if you're rolling your own serialization, you'll want to be more rigorous in your validation.

Title: Anything wrong with direct evaluation of JSON if your own code created it?

Body:
Suppose I have a server-side variable containing JSON (named strJSON) that my own code created.  In JavaScript I can consume it like this:

```<code>var data = <%= strJSON %>;
</code>```

or use a JSON parsing library:

```<code>var data = JSON.parse('<%= HttpUtility.JavaScriptStringEncode(strJSON) %>');
</code>```

I prefer the 2nd, for safety. Is what I'm doing unnecessary?

Body:
If the JSON string is encoded entirely under your control, it is exploitable to the extent that your encoding method is broken. That said, you should be safe if you're performing a straightforward serialization using a trusted serializer, like so:

var js = new JavaScriptSerializer();
var thingy123 = ThingyRepo.Get(123);
var json = js.Serialize(thingy123);

Response.Write(json); // or whatever

You should be safe, even if thingy123 contains user-submitted data. A well-established JSON serializer will safely encapsulate everything in a "non-executable" JSON format.

But, if you're rolling your own serialization, you'll want to be more rigorous in your validation.


问:
Is this statement correct for floating point numbers?

The decimal point can "float" to accommodate larger numbers while
  staying in 32-bits which is why float is considered "in-accurate"

Is this an accurate statement? I want to know if I understand floating point numbers.

答:
As stated, this isn't an accurate statement.

A particular floating point representation can exactly represent some values and cannot accurately represent other values.  The same is true for all data types.  Numeric data types don't vary in their "accuracy" but rather in the values that they can accurately represent.  For instance, a single-byte unsigned integer type can represent 255, but cannot represent 257 or 0.5.

A floating point representation is no different.  It can represent some numbers, and cannot represent others.  What confuses people is that unlike integer types, values that a floating point representation cannot represent can be between values that it can represent.  So, for example, a floating point representation might be able to represent 0.25 and 0.5, but might not be able to represent 1/3rd.

What is true is that with integer types (or fixed decimal types) it is very easy to determine what values can be represented.  You know out of hand with an int that fractional values cannot be represented, nor can values greater than MAX_INT.  With a float, it would require detailed knowledge of the representation to determine whether a value can be exactly represented.

It is very difficult to programmatically test whether the result of a particular mathematical statement will produce a floating point value that cannot be exactly represented.  On the other hand, it is trivial to programmatically test whether the result of a particular mathematical statement will produce an integer value that cannot be exactly represented.  So people do these sorts of tests all the time with integers (testing for overflows), but just live with the fact that there may be rounding in floating point statements, and keep track of how close the results are to the actual value (the precision.)

Or another way to put it: saying that a given floating point value is inaccurate does not really make sense.  Instead, it is  better to say that a given set of floating point operations may produce inaccurate results.


答:
If something is a pattern or an antipattern depends significantly on what language and environment you are writing in. For example, for loops are a pattern in assembly, C, and similar languages and an anti-pattern in lisp.

Let me tell you a story of some code that I wrote long ago...

It was in a language called LPC and implemented a framework for casting spells in a game.  You had a spell superclass, which had a subclass of combat spells that handled some checks, and then a subclass for single target direct damage spells, which was then subclassed to the individual spells - magic missile, lightning bolt and the like.

The nature of how LPC worked was that you had a master object that was a Singleton. before you go 'eww Singleton' - it was and it wasn't "eww" at all.  One didn't make copies of the spells, but rather invoked the (effectively) static methods in the spells.  The code for magic missile looked like:

```<code>inherit "spells/direct";

void init() {
  ::init();
  damage = 10;
  cost = 3;
  delay = 1.0;
  caster_message = "You cast a magic missile at ${target}";
  target_message = "You are hit with a magic missile cast by ${caster}";
}
</code>```

And you see that?  Its a constructor only class.  It set some values that were in its parent abstract class (no, it shouldn't use setters - its an immutable) and that was it.  It worked right.  It was easy to code, easy to extend and easy to understand.

This sort of pattern translates to other situations where you have a subclass that extends an abstract class and sets a few values of its own, but all of the functionality is in the abstract class it inherits.  Go glance at StringBuilder in Java for an example of this - not quite constructor only, but I'm pressed to find much logic in the methods themselves (everything is in the AbstractStringBuilder).

This is not a bad thing, and it is certainly not an anti-pattern (and in some languages it may be a pattern itself).

Body:
If something is a pattern or an antipattern depends significantly on what language and environment you are writing in. For example, for loops are a pattern in assembly, C, and similar languages and an anti-pattern in lisp.

Let me tell you a story of some code that I wrote long ago...

It was in a language called LPC and implemented a framework for casting spells in a game.  You had a spell superclass, which had a subclass of combat spells that handled some checks, and then a subclass for single target direct damage spells, which was then subclassed to the individual spells - magic missile, lightning bolt and the like.

The nature of how LPC worked was that you had a master object that was a Singleton. before you go 'eww Singleton' - it was and it wasn't "eww" at all.  One didn't make copies of the spells, but rather invoked the (effectively) static methods in the spells.  The code for magic missile looked like:

inherit "spells/direct";

void init() {
  ::init();
  damage = 10;
  cost = 3;
  delay = 1.0;
  caster_message = "You cast a magic missile at ${target}";
  target_message = "You are hit with a magic missile cast by ${caster}";
}

And you see that?  Its a constructor only class.  It set some values that were in its parent abstract class (no, it shouldn't use setters - its an immutable) and that was it.  It worked right.  It was easy to code, easy to extend and easy to understand.

This sort of pattern translates to other situations where you have a subclass that extends an abstract class and sets a few values of its own, but all of the functionality is in the abstract class it inherits.  Go glance at StringBuilder in Java for an example of this - not quite constructor only, but I'm pressed to find much logic in the methods themselves (everything is in the AbstractStringBuilder).

This is not a bad thing, and it is certainly not an anti-pattern (and in some languages it may be a pattern itself).


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答:
My thoughts:

Using javascript will always increase the surface area for attack, not just for you, but for your customers - almost everyone I know browses with NoScript, and this includes non-technical folks.

If I see an online shopping site that uses javascript badly I will not buy from them. I always first browse with javascript disabled, and if a site degrades gracefully I may be interested. If it is just broken I will usually assume the programmers also don't have the capability to deliver a secure shop platform.

It tends to slow everything down - despite being close to a major city, my broadband is slow enough without having to wait for some marketing idea to load. If a site takes more than 5 seconds to load basic content then I won't bother unless I have a real need.


问:
Const means Thread-safe?
I was put onto this video:

http://channel9.msdn.com/posts/C-and-Beyond-2012-Herb-Sutter-You-dont-know-blank-and-blank

By https://codereview.stackexchange.com/users/39810/glampert

Because I asked this question:

https://codereview.stackexchange.com/questions/82616/const-cast-of-stdmutex-in-get-member

Marking a class std::mutex as mutable is the right answer to my original question and the video is an excellent and enjoyable discussion around that. I am grateful to glampert.

However I disagree with the premise of the talk that "const == thread-safe" (see time-point 16:00).

Below is my proposal for how we should interpret const in a multi-threaded world. It's not as simple as Herb's proposal but (let's face it) if you think any of the answers in multi-threading are simple you've completely failed to grasp the challenge of multi-threading.

Comments please. What do you think const means for multi-threaded programs? Has its meaning fundamentally changed?

const means logically unmodified by dereferences through the const
  reference in question.

Multi-threading footnote #1:  In objects that form part of the shared
  state of a multi-threaded program “logically unmodified” will mean
  “logically const member functions only perform reads on the object” and so any
  implementation that actually performs writes (such as cached values,
  instrumentation and even employs synchronization mutexes) needs to
  adequately make them thread-safe to maintain the ‘logical’ appearance
  of ‘only reads’.

Single-threading footnote : Of course even in a single threaded
  application const is by no means a guarantee that an object won’t
  change during the lifetime of a given const reference. There may be
  non-const references (aliases) and even a single threaded program
  might use to modify an object which has one or more const
  references.

Multi-threaded footnote #2: That lack of guarantee that an object will
  not be modified just because there is a const reference to it is true
  in spades for multi-threaded applications. So in many senses – no
  change there.

I think my greatest concern is that through I am sure Herb Sutter would confirm them as dreadful fallacies, I fear that reading const as ‘thread-safe’ leads too easily to:

The fallacy that adding std::lock_guard guard(this->mutex) to the start of all methods and the destructor of a class somehow make any use of it ‘thread-safe’.

The fallacy that if you only call const methods on a class your application has a thread-safe guarantee and you can complain to the implementer if not.

Finally, the fallacy that if you don’t modify any mutable members and don’t cast away const anywhere you don’t need to worry about thread-safety because (apparently) “const means thread-safe”.

Fallacy 1 is best exemplified by supposing you can get any sense iterating through a collection that is being modified by another thread just because you know the methods are lock-guarded.

Fallacy 2 pushes a potentially onerous (and even impossible) burden on to implementers who can (of course) add lock-guards to all their methods but may (at best) be wasting time and (at worst) just setting you up for fallacy 1.

Fallacy 3 is the fallacy that thread-safety is all about competing for simultaneous access. Memory caching however means that to obtain a coherent state within a const method there may still be a requirement to ensure some kind of memory barrier has been performed (e.g. at least “acquire”).

答:
While it does not mean thread-safe per-se, for the standard-library it does:

17.6.5.9 Data race avoidance [res.on.data.races]

1 This section specifies requirements that implementations shall meet to prevent data races (1.10). Every standard library function shall meet each requirement unless otherwise specified. Implementations may prevent data races in cases other than those specified below.

  2 A C++ standard library function shall not directly or indirectly access objects (1.10) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function’s arguments, including this.

  3 A C++ standard library function shall not directly or indirectly modify objects (1.10) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function’s non-const arguments, including this.

  [...]

And that's the pattern user-defined types and functions should follow wherever reasonably possible.

Title: Const means Thread-safe?