答:
If you're doing web development with Java, consider reading up on the Spring Security framework (here is a good tutorial). It's based on Acegi Security which was absorbed into the Spring Framework. You'll quickly learn about the key principles of securing a web application:

Never trust the client (validate everything)

HTTPS is your friend

Hashing passwords is a good thing

Security is an aspect of your code (i.e implemented through filters and interceptors rather than directly within your business logic)

Anecdote

I remember one client I worked with who had employed a security firm to perform penetration tests on their code. They failed badly. One quick refactor to use Spring Security and Spring MVC instead of their home-grown approach and all their issues vanished.

Nothing is ever perfect, but you can make it so hard to get into your application that script kiddies give up leaving just the dedicated crackers to deal with. And for them, you'll need professional advice.

Title: How did you learn about security in your web development?

Body:
I've been developing intranet web sites and public web sites with no big issues concerning security. There were nothing to steal and nothing to gain. Nothing to attract people to try to reach the website behind the scene. I don't talk about login & password but more about the security against user attacks.

So, what's the best way to learn to secure the access to a site, to learn about common mistakes or weakness to think about ? Do I have to find a framework related to the language I use and rely on it or is there a source (book, website, ...) where I can find information about general design and tricks ?


问:
Is it necessary to memorize every line of code when it comes to game development?
I am currently following along a youtube tutorial here and from what I understand we are starting out by creating an engine to run the game. Should I be able to implement all of this by myself without outside help in the future or should I just make sure to have an understanding of everything that is going on? Would a professional game developer know how to implement everything that it takes to make a game or would he/she just copy and paste certain parts (like creating a buffer, or fps cap) and edit it to their taste?</p>

答:
No, it isn’t necessary to remember every line of code.  I am not a game developer but my advice is to be more concerned about the overall design and structure of a project.  Plenty of developers reuse existing code, in one form or another - there’s no shame in that. BUT, copying and pasting code - without even attempting to understand how it works - isn’t the way to go.

As the other poster has indicated "re-inventing the wheel” can either be a great waste of time (especially if the result is no better or worse) or a great learning experience - it depends on your goals.

ContentLicense: CC BY-SA 3.0


问:
Are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?
I'm a long-time Python user. A few years ago, I started learning C++ to see what it could offer in terms of speed. During this time, I would continue to use Python as a tool for prototyping. This, it seemed, was a good system: agile development with Python, fast execution in C++.

Recently, I've been using Python more and more again, and learning how to avoid all of the pitfalls and anti-patterns that I was quick to use in my earlier years with the language. It's my understanding that using certain features (list comprehensions, enumerations, etc.) can increase performance.

But are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?

答:
The Python reference implementation is the “CPython” interpreter. It tries to be reasonably fast, but it does not currently employ advanced optimizations. And for many usage scenarios, this is a good thing: The compilation to some intermediary code happens immediately before runtime, and each time the program is executed the code is compiled anew. So the time needed for optimization has to be weighed against the time gained by optimizations – if there isn't a net gain, the optimization is worthless. For a very long-running program, or a program with very tight loops, employing advanced optimizations would be useful. However, CPython is used for some jobs that preclude aggressive optimization:

Short-running scripts, used e.g. for sysadmin tasks. Many operating systems like Ubuntu build a good part of their infrastructure on top of Python: CPython is fast enough for the job, but has virtually no start-up time. As long as it's faster than bash, it's good.

CPython must have clear semantics, as it is a reference implementation. This allows simple optimizations such as “optimize the implementation of the foo operator” or “compile list comprehensions to faster bytecode”, but will generally preclude optimizations that destroy information, such as inlining functions.

Of course, there are more Python implementations than just CPython:

Jython is built on top of the JVM. The JVM can interpret or JIT-compile the provided bytecode, and has profile-guided optimizations. It suffers from high start-up time, and it takes a while until the JIT kicks in.

PyPy is a state of the art, JITting Python VM. PyPy is written in RPython, a restricted subset of Python. This subset removes some expressiveness from Python, but allows the type of any variable to be statically inferred. The VM written in RPython can then be transpiled to C, which gives RPython C-like performance. However, RPython is still more expressive than C, which allows faster development of new optimizations. PyPy is an example of compiler bootstrapping. PyPy (not RPython!) is mostly compatible to the CPython reference implementation.

Cython is (like RPython) an incompatible Python dialect with static typing. It also transpiles to C code, and is able to easily generate C extensions for the CPython interpreter.

If you are willing to translate your Python code to Cython or RPython, then you'll get C-like performance. However, they shouldn't be understood as “a subset of Python”, but rather as “C with Pythonic syntax”. If you switch to PyPy, your vanilla Python code will get a considerable speed boost, but will also be unable to interface with extensions written in C or C++.

But what properties or features prevent vanilla Python from reaching C-like levels of performance, aside from long start-up times?

Contributors and funding. Unlike Java or C#, there is no single driving company behind the language with an interest to make this language the best of its class. This restricts development to mainly to volunteers, and occasional grants.

Late binding and the lack of any static typing. Python allows us to write crap like this:

```<code>import random

# foo is a function that returns an empty list
def foo(): return []

# foo is a function, right?
# this ought to be equivalent to "bar = foo"
def bar(): return foo()

# ooh, we can reassign variables to a different type – randomly
if random.randint(0, 1):
   foo = 42

print bar()
# why does this blow up (in 50% of cases)?
# "foo" was a function while "bar" was defined!
# ah, the joys of late binding
</code>```

In Python, any variable can be reassigned at any time. This prevents caching or inlining; any access has to go through the variable. This indirection weighs down performance. Of course: if your code doesn't do such insane things so that each variable can be given a definitive type before compilation and each variable is assigned only once, then – in theory – a more efficient execution model could be chosen. A language with this in mind would provide some way to mark identifiers as constants, and at least allow optional type annotations (“gradual typing”).

A questionable object model. Unless slots are used, it's hard to figure out which fields an object has (a Python object is essentially a hash table of fields). And even once we're there, we still have no idea what types these fields have. This prevents representing objects as tightly packed structs, as is the case in C++. (Of course, C++'s representation of objects isn't ideal either: due to the struct-like nature, even private fields belong to the public interface of an object.)

Garbage collection. In many cases, GC could be avoided completely. C++ allows us to statically allocate objects which are destroyed automatically when the current scope is left: Type instance(args);. Until then, the object is alive and can be lent to other functions. This is usually done via “pass-by-reference”. Languages like Rust allow the compiler to statically check that no pointer to such an object exceeds the lifetime of the object. This memory management scheme is totally predictable, highly efficient, and suits most cases without complicated object graphs. Unfortunately, Python was not designed with memory management in mind. In theory, escape analysis can be used to find cases where GC can be avoided. In practice, simple method chains such as foo().bar().baz() will have to allocate a large number of short-lived objects on the heap (generational GC is one way to keep this problem small).

In other cases, the programmer may already know the final size of some object such as a list. Unfortunately, Python does not offer a way to communicate this when creating a new list. Instead, new items will be pushed onto the end, which might require multiple reallocations. A few notes:

Lists of a specific size can be created like fixed_size = [None] * size. However, the memory for the objects inside that list will have to be allocated seperately. Contrast C++, where we can do std::array<Type, size> fixed_size.

Packed arrays of a specific native type can be created in Python via the array builtin module. Also, numpy offers efficient representations of data buffers with specific shapes for native numeric types.

Summary

Python was designed for ease of use, not for performance. Its design makes creating highly efficient implementation rather difficult. If the programmer abstains from problematic features, then a compiler understanding the remaining idioms will be able to emit efficient code that can rival C in performance.

Body:
The Python reference implementation is the “CPython” interpreter. It tries to be reasonably fast, but it does not currently employ advanced optimizations. And for many usage scenarios, this is a good thing: The compilation to some intermediary code happens immediately before runtime, and each time the program is executed the code is compiled anew. So the time needed for optimization has to be weighed against the time gained by optimizations – if there isn't a net gain, the optimization is worthless. For a very long-running program, or a program with very tight loops, employing advanced optimizations would be useful. However, CPython is used for some jobs that preclude aggressive optimization:

Short-running scripts, used e.g. for sysadmin tasks. Many operating systems like Ubuntu build a good part of their infrastructure on top of Python: CPython is fast enough for the job, but has virtually no start-up time. As long as it's faster than bash, it's good.

CPython must have clear semantics, as it is a reference implementation. This allows simple optimizations such as “optimize the implementation of the foo operator” or “compile list comprehensions to faster bytecode”, but will generally preclude optimizations that destroy information, such as inlining functions.

Of course, there are more Python implementations than just CPython:

Jython is built on top of the JVM. The JVM can interpret or JIT-compile the provided bytecode, and has profile-guided optimizations. It suffers from high start-up time, and it takes a while until the JIT kicks in.

PyPy is a state of the art, JITting Python VM. PyPy is written in RPython, a restricted subset of Python. This subset removes some expressiveness from Python, but allows the type of any variable to be statically inferred. The VM written in RPython can then be transpiled to C, which gives RPython C-like performance. However, RPython is still more expressive than C, which allows faster development of new optimizations. PyPy is an example of compiler bootstrapping. PyPy (not RPython!) is mostly compatible to the CPython reference implementation.

Cython is (like RPython) an incompatible Python dialect with static typing. It also transpiles to C code, and is able to easily generate C extensions for the CPython interpreter.

If you are willing to translate your Python code to Cython or RPython, then you'll get C-like performance. However, they shouldn't be understood as “a subset of Python”, but rather as “C with Pythonic syntax”. If you switch to PyPy, your vanilla Python code will get a considerable speed boost, but will also be unable to interface with extensions written in C or C++.

But what properties or features prevent vanilla Python from reaching C-like levels of performance, aside from long start-up times?

Contributors and funding. Unlike Java or C#, there is no single driving company behind the language with an interest to make this language the best of its class. This restricts development to mainly to volunteers, and occasional grants.

Late binding and the lack of any static typing. Python allows us to write crap like this:

import random

# foo is a function that returns an empty list
def foo(): return []

# foo is a function, right?
# this ought to be equivalent to "bar = foo"
def bar(): return foo()

# ooh, we can reassign variables to a different type – randomly
if random.randint(0, 1):
   foo = 42

print bar()
# why does this blow up (in 50% of cases)?
# "foo" was a function while "bar" was defined!
# ah, the joys of late binding

In Python, any variable can be reassigned at any time. This prevents caching or inlining; any access has to go through the variable. This indirection weighs down performance. Of course: if your code doesn't do such insane things so that each variable can be given a definitive type before compilation and each variable is assigned only once, then – in theory – a more efficient execution model could be chosen. A language with this in mind would provide some way to mark identifiers as constants, and at least allow optional type annotations (“gradual typing”).

A questionable object model. Unless slots are used, it's hard to figure out which fields an object has (a Python object is essentially a hash table of fields). And even once we're there, we still have no idea what types these fields have. This prevents representing objects as tightly packed structs, as is the case in C++. (Of course, C++'s representation of objects isn't ideal either: due to the struct-like nature, even private fields belong to the public interface of an object.)

Garbage collection. In many cases, GC could be avoided completely. C++ allows us to statically allocate objects which are destroyed automatically when the current scope is left: Type instance(args);. Until then, the object is alive and can be lent to other functions. This is usually done via “pass-by-reference”. Languages like Rust allow the compiler to statically check that no pointer to such an object exceeds the lifetime of the object. This memory management scheme is totally predictable, highly efficient, and suits most cases without complicated object graphs. Unfortunately, Python was not designed with memory management in mind. In theory, escape analysis can be used to find cases where GC can be avoided. In practice, simple method chains such as foo().bar().baz() will have to allocate a large number of short-lived objects on the heap (generational GC is one way to keep this problem small).

In other cases, the programmer may already know the final size of some object such as a list. Unfortunately, Python does not offer a way to communicate this when creating a new list. Instead, new items will be pushed onto the end, which might require multiple reallocations. A few notes:

Lists of a specific size can be created like fixed_size = [None] * size. However, the memory for the objects inside that list will have to be allocated seperately. Contrast C++, where we can do std::array<Type, size> fixed_size.

Packed arrays of a specific native type can be created in Python via the array builtin module. Also, numpy offers efficient representations of data buffers with specific shapes for native numeric types.

Summary

Python was designed for ease of use, not for performance. Its design makes creating highly efficient implementation rather difficult. If the programmer abstains from problematic features, then a compiler understanding the remaining idioms will be able to emit efficient code that can rival C in performance.


问:
SOAP message testing
I am working in Scala/Java.

I'm testing the messaging infrastructure of a part of my system that I did several years ago with CXF and Java. More specifically, I'm re-writing the specification of the message exchange. This is because i'm changing few part of it. At the time, I was not using TDD/BDD. Now I'm driving out everything with BDD. Actually, the owner of the system specifically wants to have the BDD style Specification before i'm done with the project. I also find it actually useful anyway.

I'm particularly interested in writing an end-to-end test, where I
  would check that the server read the message properly.

Optionally I would like to send a message and in the middle check that
  what is sent is conform and forward the message to the server. (Actually i think that unit testing the sending on one side and the receiving on the other side should be enough here)

The end to end test should be something like:

->Client one prepare a message

->Client one send a message to the Server

->On reception of the message on the server verify, that the message received correspond to is expected to have been sent. In particular, check that resulting composite object constructed out of the raw message is right.

This, on its own, should drive out several unit test in the middle. The other nonfunctional constraint will also help for the matter.

The problem here is that the end-to-end test describe here actually involve writing a Test with asynchronous code. I saw things like awaitlity or scala future to handle that. However, the part is bogging me down, is the observation of an the new message received inside the server. I read things about polling the system through a probe, but i still can't figure out the probe part. In any case, in all and all, the problem is that the message received is an internal variable of the server, well encapsulated. I'm wondering how to deal with that ? What techniques could be recommended here ??? There must be some existing hooks for that? Any one has any idea? Serializing the object in a log file :), making the variable publicly accessible trough some getter? Creating some trace object for the matter. etc.... I would appreciate if someone could suggest something.

答: Sounds like you need a proxy to insert between your client and your service. You should be able to generate a skeleton from your WSDL, then stick your validate-and-forward logic in where the service methods are stubbed out.</p>

Title: SOAP message testing


问:
Phone Number based Login
I'm trying to implement a phone number based login and not sure if I should ask the users for full number, i.e country code + number or just the number.

What I have in mind so far:

Attempt optimistic login using whatever number user gives.

Most likely, it'll come back with a single user match.

In case there is a collision, throw an error (and show some helpful clue to the user asking them to enter full number)

I guess this is a simplistic approach with minimum friction and complexity (as opposed to IP detection, geography based resolution etc.).

答:
This is a classic case of YAGNI.

Sure, you might get duplicate phone numbers.  But ten digits allow for 10 billion possible phone numbers, so I doubt you're going to have this problem any time soon.

By the time you have a large enough user base that this might become a problem, it will be a good problem to solve, and you'll have the necessary resources to solve it.

Title: Phone Number based Login


答:
I would recommend to test the client and the server separately.

Client testing

The client connects to a mock server. That server verifies that the request from the client is well-formed according to your XSD specification and additional validation rules and sends a canned response back.

The canned response from the mock server must have been validated beforehand, but that can be done by hand when creating the test case.

The test then verifies that the client sends the right message and correctly processes the response.

Server testing

For testing the server, you create a stub client that sends canned requests to the server and validates that the responses are as expected.

Now, you also have the possibility to test the server's behaviour when unexpected or malformed messages are received, which is far harder in an end-to-end test with a correctly functioning client.

Title: SOAP message testing

Body:
I am working in Scala/Java.

I'm testing the messaging infrastructure of a part of my system that I did several years ago with CXF and Java. More specifically, I'm re-writing the specification of the message exchange. This is because i'm changing few part of it. At the time, I was not using TDD/BDD. Now I'm driving out everything with BDD. Actually, the owner of the system specifically wants to have the BDD style Specification before i'm done with the project. I also find it actually useful anyway.

I'm particularly interested in writing an end-to-end test, where I
  would check that the server read the message properly.

Optionally I would like to send a message and in the middle check that
  what is sent is conform and forward the message to the server. (Actually i think that unit testing the sending on one side and the receiving on the other side should be enough here)

The end to end test should be something like:

->Client one prepare a message

->Client one send a message to the Server

->On reception of the message on the server verify, that the message received correspond to is expected to have been sent. In particular, check that resulting composite object constructed out of the raw message is right.

This, on its own, should drive out several unit test in the middle. The other nonfunctional constraint will also help for the matter.

The problem here is that the end-to-end test describe here actually involve writing a Test with asynchronous code. I saw things like awaitlity or scala future to handle that. However, the part is bogging me down, is the observation of an the new message received inside the server. I read things about polling the system through a probe, but i still can't figure out the probe part. In any case, in all and all, the problem is that the message received is an internal variable of the server, well encapsulated. I'm wondering how to deal with that ? What techniques could be recommended here ??? There must be some existing hooks for that? Any one has any idea? Serializing the object in a log file :), making the variable publicly accessible trough some getter? Creating some trace object for the matter. etc.... I would appreciate if someone could suggest something.


问:
Unit testing - should tests for a method validate the results of other methods?
One thing that bothers me while I'm writing unit tests of my code is if tests of methods should include validation of the outcome of other methods? Of course, public methods. Let's see a - rather trivial - example:

```<code>public int Solve(string forumla)
{
    if (forumla.Contains("+"))
    {
        return SolveAddition(formula);
    }
    if (forumla.Contains("-"))
    {
        return SolveSubstraction(formula);
    }
    throw new ArgumentException();
}

public int SolveAddition(string formula)
{
    var strings = formula.Split('+');
    if (strings.Length != 2)
    {
        throw new ArgumentException();
    }
    int firstFactor = int.Parse(strings[0]);
    int secondFactor = int.Parse(strings[0]);
    return firstFactor + secondFactor;
}
</code>```

In this case, should tests of Solve methods only test control flow, or each possible scenario of SolveAddition? Let's assume, that SolveAddition and  SolveSubstraction have their own tests.

Using other words, did test scenarios for Solve should contains only:

2+2

2-2

2:2

Or also include:

2+2+2+2

2-2-2-2

potato - hamster

Best regards

答:
For any given piece of code, there should be at most one place that is responsible for exhaustively testing that code.

There can be any number that incidentally test it; you just don't want to waste effort running up an exponentially large mountain.

For your example, the minimum set of test cases is a list of invalid forumulas, plus a list of valid formulas with expected answers. Those lists don't get any shorter overall if you split out addition and subtraction cases.

So the right place to test all three functions would be through 'Solve'.

That way, when you decide you need to handle '2 + 3 - 1', you just move it from one list to the other.


问:
Are there any (free) video formats that include channels for arbitrary time-dependant data?
I'm in the process of writing an image analysis pipeline and I've hit a bit of a roadblock.  Here's the 30,000-ft view:

Images arrive as base64-encoded PNG images over standard input

Images are decoded, and processed.  I don't think the details are particularly relevant, but I am happy to offer specifics in the form of an edit.

When the analysis is complete, the entire stream must be concatenated into a seekable, timestamped format (that is, a video file of some sort) and saved to disk.

My question pertains to stage 3.  At this final stage of the pipeline, each frame will have a set of associated features that were extracted via the image analysis performed in stage 2.  I would like for the final output format (the video format) to preserve this information alongside the frame that "owns" it.  In other words, one should think about this as a separate channel that evolves alongside the video data, locked to the same time reference.  This would notably allow me to treat features as time-series.

Here's a simple diagram to further illustrate what I'm trying to achieve.

```<code>-0 ms--16 ms--32 ms--48 ms--64 ms- ... n ms ->  # time channel
-F1----F2-----F3-----F4-----F5---- ... Fn --->  # video channel
-1.1---3.6----5.0----2.6----3.1--- ... 11.2 ->  # data channel 1
-100---105----120----96-----101--- ... 52 --->  # data channel 2
</code>```

As you can see in the above schema, there are two data channels (although, ideally, the format should support an arbitrary number of channels) whose values evolve over time.  Note that the time channel need not be an actual channel, per se, but was illustrated as such simply to show that video and data channels are represented as a function of time.

At the very least I'd like to be able to populate each "index" of each channel with an int or a float. Ideally, however, I would like to be able to hold a reference to some binary data of arbitrary length.

In addition to providing the above functionality, this hypothetical codec should support some form of modern video compression. Does such a thing exist?

答:
Subtitle files typically holds textual data, but there's no reason why you can't use it to associate arbitrary data or a reference to the data (if the actual data is too long for convenience).

Note that subtitle files are usually time based rather than frame based. If it's crucial for your app that the data are associated with precise frames, you'll need to use a subtitle format that is specified in frame intervals or adapt an existing format but replace its time intervals with frame intervals.

Some of the XML based subtitle format would be fairly easy to adapt for this.


问:
Is there a reason to define type aliases in any program
I have started to learn c++ for some time ago. It is a big subject and I am not very use to it yet. Thus is this question asked more of curiosity, than something else.
In the book that I read to now learn there is a discussion about portability. I agree that the discussion comes quite earky for someone in the beginning of their learning period, but when reading I came to Think about something.

What I wonder is: is there ever is a reason to define custom type to use instead of the fundamental builtin types? For example, would it be useful to define a type int_c as in "int custom"? The reason I think about this is since some code may be compiled for example both a 32-bit compiler and a 64-bit compiler. It seems as if it would be easier since if you change platform and all the integers are defined as int_c instead of int, since the latter would require changing type in every place an int is used?

However, I also know that <cstdint> contains definitions of different integer as int64_t. However I have not heard of a header with floating Point types.

So to conclude: Is there a reason to define custom integers or floats like int_c or double_c Or int other case what is the best apporach?

答:
There is sometimes a reason to do so, however <stdint.h>  (in C99) or <cstdint>  (in C++03 or beter) make them less obvious.

First, there is a readability issue. If you define

```<code>typedef unsigned myhash_t;
</code>```

and later always use myhash_t  for numbers which are in fact hashes, you ease the understanding of your code. This does not help much against your own mistakes (e.g. forgetting to declare a parameter as myhash_t  even if it is an hash) but it does enhance readability.

Then with <stdint.h>  (etc...) you have many new integral types (most of them being system-specific synonyms of e.g. int  and long), like int64_t  (a signed int of exactly 64 bits), uintptr_t  (an unsigned integer with the same size as pointers), int_fast8t (an integral type, which is computed quickly, of at least 8 bits, but it could be 16 bits if they run faster, etc...)

At last, you may place preprocessor tricks with e.g. #if combined to such typedef-s. For instance, you could define a color encoding as having 3 RGB (or 4, RGBA) components of

```<code> typedef uint8_t color_t;
</code>```

but some preprocessor trick might make that an uint16_t ....

FWIW, Ocaml and Ada are doing better than C++ in that respect. They are able to define private integral types (see e.g. §7.9.2 in Ocaml ref.), on which arithmetic is forbidden (unless explicitly allowed). In C++ you could have class MyHiddenInt { int x; /*etc*/ };  but it may be differently represented and handled (i.e. produce less efficient machine code) than some int.  Details are of course ABI specific. On Linux/x86-64 with -O2 optimization the GCC 4.9 generated code (e.g. for an addition) would be the same.

These private integers sometimes make sense. For example on Unix and Posix file descriptors are int-s but doing any arithmetic on them is non-sense. (likewise for myhash_t probably, but you cannot express that constraint in C++).

For floating numbers it is even more important. On some processors (e.G. some GPGPUs), double  precision arithmetic is so slow that you want to avoid it. On our laptop & dekstop PCs, it is the opposite: you almost always want to use double   (which today means IEEE754 64 bits floating point), and use float  (or short) only to squeeze memory consumption.  These choices are really processor specific (not the same on a tablet or a supercomputer).

You could go even further, and have a type analysis which take into account physical dimensions. So you forbid (at compile time) adding kilograms with amperes or watts, and that the product of a speed (in meter per second) with a time (in second) is a length (in meter) which should not be acceptable as a file descriptor or an hash.

Read about abstract data types.

Body:
There is sometimes a reason to do so, however <stdint.h>  (in C99) or <cstdint>  (in C++03 or beter) make them less obvious.

First, there is a readability issue. If you define

typedef unsigned myhash_t;

and later always use myhash_t  for numbers which are in fact hashes, you ease the understanding of your code. This does not help much against your own mistakes (e.g. forgetting to declare a parameter as myhash_t  even if it is an hash) but it does enhance readability.

Then with <stdint.h>  (etc...) you have many new integral types (most of them being system-specific synonyms of e.g. int  and long), like int64_t  (a signed int of exactly 64 bits), uintptr_t  (an unsigned integer with the same size as pointers), int_fast8t (an integral type, which is computed quickly, of at least 8 bits, but it could be 16 bits if they run faster, etc...)

At last, you may place preprocessor tricks with e.g. #if combined to such typedef-s. For instance, you could define a color encoding as having 3 RGB (or 4, RGBA) components of

 typedef uint8_t color_t;

but some preprocessor trick might make that an uint16_t ....

FWIW, Ocaml and Ada are doing better than C++ in that respect. They are able to define private integral types (see e.g. §7.9.2 in Ocaml ref.), on which arithmetic is forbidden (unless explicitly allowed). In C++ you could have class MyHiddenInt { int x; /*etc*/ };  but it may be differently represented and handled (i.e. produce less efficient machine code) than some int.  Details are of course ABI specific. On Linux/x86-64 with -O2 optimization the GCC 4.9 generated code (e.g. for an addition) would be the same.

These private integers sometimes make sense. For example on Unix and Posix file descriptors are int-s but doing any arithmetic on them is non-sense. (likewise for myhash_t probably, but you cannot express that constraint in C++).

For floating numbers it is even more important. On some processors (e.G. some GPGPUs), double  precision arithmetic is so slow that you want to avoid it. On our laptop & dekstop PCs, it is the opposite: you almost always want to use double   (which today means IEEE754 64 bits floating point), and use float  (or short) only to squeeze memory consumption.  These choices are really processor specific (not the same on a tablet or a supercomputer).

You could go even further, and have a type analysis which take into account physical dimensions. So you forbid (at compile time) adding kilograms with amperes or watts, and that the product of a speed (in meter per second) with a time (in second) is a length (in meter) which should not be acceptable as a file descriptor or an hash.

Read about abstract data types.


问:
Which license should I use in the program?
I have developed software that I would like to sell commercially. I don't know which license I should use. I've never used one before. I don't I think need/should to write one myself. Basically, I want to restrict end-used from doing these things without contacting me first:

share binary program with others

(re-)sell the software

答:
If you don't want to allow your users to make copies and you don't want to share your code, the default copyright is sufficient.

Just put in your copyright statement

Copyright 2014, Jack.
  All rights reserved.

Copying of this program is only allowed with prior permission from the author.

It might not be legally possible to prohibit reselling (if someone passes their single copy on, without keeping a copy of the software).


问:
Client-side coding: How to prevent malicious use?
Over the last few years, the trend for client-side (browser) applications has really taken off.

For my latest project, I have decided to try and move with the times and write a client-side application.

Part of this application involves sending transaction emails to users (for example, validate signup, password reset emails, etc.). I am using a third-party API to send the emails.

Normally I would have my application running on a server. I would call the third-party API from code on my server.

Running a client-side application means this now needs to happen on a user's browser. The third-party API provides the necessary JavaScript files to achieve this.

The first glaring issue I can see is I need to use an API key. This would normally be safely stored on my server, but now presumably I will need to provide this key to the client browser.

Assuming I can get round this problem, the next problem is what stops a tech-savvy user loading up the JavaScript developers tool on a browser and using the email API anyway they like, rather than say adhering to any rules I have set in the application.

I guess my general question is - how can we prevent malicious use of a client-side application?

答:
The rule here is:

Do everything client-side that doesn't affect anyone else if the user tampers with it. In particular, that means graphical effects.

Do everything server-side that needs to be secure, and just send UI events from the client (eg. then client just says "the user tapped the Buy button" while the server actually carries out the transaction). In particular, that means financial transactions.


答:
You should make them enter the whole thing in one step, and you should make the format explicit.

Phone numbers are very tricky, especially on a global site. You should take every step you can to avoid ambiguity, guesswork, and fancy country-based magic.

If you truly need to use phone number for "login" a single form can work better with "remember my credentials" features in browsers.

That said, I think you're setting yourself up for a disaster, because there are many issues to consider:

Phone number display styles and validation vary by country! For example, within Hong Kong, there are no area codes, and phone numbers are eight digits long.

Many people will have absolutely no idea what they'd need to dial internationally to reach their own phone. ("Country code? What's my country code?")

What about people who sign up using a work phone extension? Either you support that, or you force everyone in an office has to share an account. (Or to use a personal phone number.)

The phone number a person uses may not have any relationship to where their current residence or their computer is right now.

Title: Phone Number based Login

Body:
I'm trying to implement a phone number based login and not sure if I should ask the users for full number, i.e country code + number or just the number.

What I have in mind so far:

Attempt optimistic login using whatever number user gives.

Most likely, it'll come back with a single user match.

In case there is a collision, throw an error (and show some helpful clue to the user asking them to enter full number)

I guess this is a simplistic approach with minimum friction and complexity (as opposed to IP detection, geography based resolution etc.).


问:
Should I separate a web api from the webserver?
Lets say I'm building a site similar to this or Quora (or some arbitrary blog-like site). I need a real-time component that will be using web-sockets/long-polling to notify the user of new posts, questions, etc. depending on what page the user is viewing. That real time component will essentially be the site's API implemented in something like Twisted or Java NIO, and the site's web server will be sitting in front of say Flask or Pyramid.

Should the API and webpages be served by the same component or is it best to keep them separate?

(I'm asking both logically and physically)

答:
Logically, it doesn't matter where the service comes from.  Conceptually you can think of the web pages being served as simply another service.

What does matter is that the service is built in such a way that it can be used independently of other services.  In other words, it wouldn't make much sense to have a public API that only works if you must also accept the web pages it serves.

Physically, it might matter for reasons of scalability or location.  Aside from that, nothing prevents you from having both a public web API and your web pages in the same application, on the same machine.


问:
Customer is "deeply disappointed" in our software because of one bug. How to reply?
We have been building custom software for one of our customer for a few years now. Everything is going well so far.

However the customer always has an attitude that when they find a bug in the software, then they are getting really pathetic and complain that they are now really disappointed with the quality of the software: Because if they found this one bug then there surely must be other bugs, so they assume that the quality of the software is getting worse. It's almost like a proof by induction: If there is one then there must be many.

To me, there can always be bugs (the software is part of their CRM solution, so nothing like software used to run airplanes, nuclear reactors, etc.) Obviously, we have various means of testing, but we (or the customers) are not testing everything, so bugs can slip through. Which is OK in my opinion.

But how would you react to such a pathetic and emotional response? I am always totally speechless when they start this way.

答:
Same as you would to any other customer: "I'm very sorry that you had problems. What can we do to help?"

Now, you're likely not going to be able to do everything they ask, and certainly not for as free as they would like it to be. That's a matter of negotiation. But your first communication is apologies followed up by positive, constructive overtures.


问:
Modeling Associations
I am working on the design phase of a paper folding project. I have a few queries in this.
Part of the problem statement says
" A web can contain one or more  ribbons in it. It can also contain a group of ribbons folded together inside it."

How do you model the association for this? I found two solutions

i)  Maintain two associations, one between the web and ribbon and the other between  the ribbon

    and the Group class. This way, the web contains only ribbons and when you process the ribbons, you'll have to check whether it is part of a group. Note that the behaviour of the ribbon will change if it is part of a group

ii) Introduce a new class called Childelemnt and associate it to web. Both Ribbon and Group will share the interface of Childelement.

Which one do you think is better? If you have any other solution, please let me know.

Thanking you all in advance,

Pradeep

答:
It makes sense for objects to share an interface if they share operations or properties. In your case, both ribbons and groups can be part of a web, so it makes sense for then to share an interface, which is your second option (which is sometimes called the composite pattern). I recommend calling that interface WebElement.

There are some added complexities, like the fact that a ribbon can be part of the web, a group, or (conceivably) unattached. You'll need logic to enforce those rules. Since ribbons can be members of webs and groups, then you will likely have to maintain two associations, as you mention in your first option, but the two are unrelated to each other, and are a consequence of your system having two types of container (web and group).

Lastly, to alter the behavior of a ribbon depending on whether it is part of a group or not, you might want to employ the strategy pattern.

Title: Modeling Associations


问:
How did you learn about security in your web development?
I've been developing intranet web sites and public web sites with no big issues concerning security. There were nothing to steal and nothing to gain. Nothing to attract people to try to reach the website behind the scene. I don't talk about login & password but more about the security against user attacks.

So, what's the best way to learn to secure the access to a site, to learn about common mistakes or weakness to think about ? Do I have to find a framework related to the language I use and rely on it or is there a source (book, website, ...) where I can find information about general design and tricks ?

答: There's NEVER nothing to steal. Even if the data on your site is worthless, your processing time and bandwidth is still valuable to DDOS botnet operators. If you're running a computer on the internet and you're interested in being a good citizen, you have to be interested in security.</p>

ContentLicense: CC BY-SA 2.5


问:
What is meant by "OOP hides the state"?
In one of many anti-OOP rants on cat-v.org I found a passage by Joe Armstrong raising several objections against the OOP model, one of which was the following:

Objection 4 – Objects have private state

State is the root of all evil. In particular functions with side effects should be avoided.

While state in programming languages is undesirable, in the real world state abounds. I am highly interested in the state of my bank account, and when I deposit or withdraw money from my bank I expect the state of my bank account to be correctly updated.

Given that state exists in the real world what facilities should programming language provide for dealing with state?

OOPLs say “hide the state from the programmer”. The states is hidden and visible only through access functions.
  Conventional programming languages (C, Pascal) say that the visibility of state variables is controlled by the scope rules of the language.
  Pure declarative languages say that there is no state.
  The global state of the system is carried into all functions and comes out from all functions. Mechanisms like monads (for FPLs) and DCGs (logic languages) are used to hide state from the programmer so they can program “as if state didn’t matter” but have full access to the state of the system should this be necessary.

The “hide the state from the programmer” option chosen by OOPLs is the worse possible choice. Instead of revealing the state and trying to find ways to minimise the nuisance of state, they hide it away.

What exactly is meant by this?  I have very little low level or procedural experience, mostly OOP, so that probably explains how unfamiliar with this I am.  And from a more modern standpoint, now that most of the Object-Oriented hysteria is passed (at least as far as I can tell), how accurate/relevant do you guys think that passage is?

Thanks for your help.

答:
Accessibility is not a feature of OOP, it is specific to implementations such as Java and Microsoft dotNET. The main feature that defines OOP is polymorphism.

Anyway, by hiding the object state, there is no way to create a meaningful API. Presentation is a vital component of real-world OOP. Those who disagree likely have an irrational hostility towards software industry, which makes their opinion irrelevant from my point of view.

Websites like the one you linked are notorious for extremely rigid thoughts and criticism on new technology. Some people just don't get it.

Title: What is meant by "OOP hides the state"?


答:
It sounds like for the most part, you have a good relationship with this customer. ("Everything is going well so far.")
Presumably you want to keep that relationship.

But it sounds like this scenario has occurred more than once.
Perhaps you have somehow (unintentionally, perhaps) let the customer believe that you aren't bothered by these occasional bugs as much as they are.  If so, the customer may feel they should increase their own expressed level of concern over the problem in order to get more attention from you.

In such cases, the more you appear to brush off the problem, the more they will complain.

Outside of (possibly) some very expensive development processes, it is perhaps inevitable that a bug will sometimes be found after release.  But it never needs to be acceptable (or "OK") for bugs to slip through.  You can reconcile these two beliefs by making it clear that you don't want to deliver buggy software and that you take the discovery of even one bug as something to be addressed.
The next step is to figure out how to address it.

If you make the customer understand that you are on top of the situation and doing everything within reason to fix the problem, they may complain less.  If they somehow inform you of the existence of the bug (such as in an email saying, "Hey, is this supposed to happen?") before the meeting where they tell you how disappointed they are, you might even be able pre-emptively to make them understand (even before the meeting) how seriously you take this situation and in that way possibly deflect some of the criticism.

Title: Customer is "deeply disappointed" in our software because of one bug. How to reply?

Body:
We have been building custom software for one of our customer for a few years now. Everything is going well so far.

However the customer always has an attitude that when they find a bug in the software, then they are getting really pathetic and complain that they are now really disappointed with the quality of the software: Because if they found this one bug then there surely must be other bugs, so they assume that the quality of the software is getting worse. It's almost like a proof by induction: If there is one then there must be many.

To me, there can always be bugs (the software is part of their CRM solution, so nothing like software used to run airplanes, nuclear reactors, etc.) Obviously, we have various means of testing, but we (or the customers) are not testing everything, so bugs can slip through. Which is OK in my opinion.

But how would you react to such a pathetic and emotional response? I am always totally speechless when they start this way.


答:
The immediate answer to your question is to remain professional, but you have to back it up with action. Specifically, addressing the customer's concerns in a way that objective and fair.

It is important to have open lines of communication and an easy way to report and track bugs. Typically this goes through the project manager or development lead, sometimes the customer has direct access to the tracking system (e.g. Jira).

If the customer feels reassured that they can report bugs and they actually get fixed, this goes a long way toward improving their attitude toward both the software itself as well as the processes used to build it.

The important thing is to have a clearly-defined process the entire team follows when reporting bugs, scheduling them to be fixed, and validating they are fixed. Depending on the type of bug this may involve writing more test cases, or manually testing. There should be a clear regression strategy as well in case a bug for which a test does not exist (e.g. spelling error) is broken again later on. Be sure to work with the customer to identify the high risk areas to get the greatest return on investment from your QA.


答:
Your middle paragraph is the heart of the problem:

Running a client side app means this now needs to happen on a users browser. The third party API provides the necessary js files to achieve this.

Why does a client side app mean you cannot have server-side work?  The push  towards client-side programming isn't about eliminating servers, but leveraging newer technologies that browsers finally support to make better user interfaces.

As for the .js file you received, are you sure it is meant for a browser?  Could it be a node.js library?

Title: Client-side coding: How to prevent malicious use?

Body:
Over the last few years, the trend for client-side (browser) applications has really taken off.

For my latest project, I have decided to try and move with the times and write a client-side application.

Part of this application involves sending transaction emails to users (for example, validate signup, password reset emails, etc.). I am using a third-party API to send the emails.

Normally I would have my application running on a server. I would call the third-party API from code on my server.

Running a client-side application means this now needs to happen on a user's browser. The third-party API provides the necessary JavaScript files to achieve this.

The first glaring issue I can see is I need to use an API key. This would normally be safely stored on my server, but now presumably I will need to provide this key to the client browser.

Assuming I can get round this problem, the next problem is what stops a tech-savvy user loading up the JavaScript developers tool on a browser and using the email API anyway they like, rather than say adhering to any rules I have set in the application.

I guess my general question is - how can we prevent malicious use of a client-side application?


答:
Address the bug, of course, but there are a couple of factors to consider. Remember that at the end of the day it's a business relationship: a value-for-value proposition.

1) Is the overall relationship a good one? Are they using the software? Do they want to continue the business relationship? You might not be able to fix their hurt feelings, but you can certainly focus on positive, forward-looking results.

2) Sometimes people express themselves in funny ways. They talk about the end of the world, but that's just how they talk. (My little girl does that.)

3) They may be apprehensive about addressing the issue. People like the happy path. So their feelings of disappointment may be as much from having to talk about it as having the problem.

4) It might be a negotiating tactic, as in "We'd like you to do more work for us, but we need a discount because of that TERRIBLE BUG IN THE LAST VERSION." OK sure.

5) There may be a legitimate cost concern, as in, how to pay for the time to correct the issue.

I've found in dealing with external and internal customers, if I focus on results, and address any problems diligently, the interaction gets smoother as trust improves. Fix the problem, and take the long view. As you establish the basis of your relationship, you want to focus on the forward-looking stuff.

If nothing else, it's a great example of customer interaction to learn from.


答:
It sounds like you haven't been up-front about the nature of your work with the client from the beginning. I'm not sure from your question that you and your client understand that All software is buggy.

And I do mean all. Even your HelloWorld app is "buggy" if it's expected it to ... I dunno ...

Automatically translate based on locale settings

Say "hello world" out loud for hearing impaired users

Run on a toaster

Other unreasonable things

Or even if it's expected to do something kinda reasonable that wasn't initially expected:

Display "Hello World" visibly even when STDOUT is redirected to /dev/null

Bugs are often just features as seen from another perspective. If there are delusions about this on either end, clear that up.

BUT FIRST, it's wise to apologize if any of the following are true:

The bug is severe

The bug is a result of some carelessness on your end

If the client wasn't fully educated on your process, the nature of software, or the nature of bugs

The client is very upset (even if it's not your fault)

What you do from there depends on your contract and desire to keep the client. If you bill by the hour, it's between you and the client as to whether it's billable time. That may require some investigation on your part before you can determine whether the issue was related to recent billable work. If it's a fixed price for completion of X, you should probably fix it for free. But, nothing is not beyond the realm of negotiation -- even if your in a contract.

Basically, have a conversation with the client and come to an agreement. Speak like humans. Ensure that you're giving the client's needs and expectations explicit consideration. Ensure, in as polite of a tone as possible, that the client also understands your needs in the relationship (to make a living) if profitability on the project is becoming questionable.

And if this is a common occurrence:

Educate the client and agree on bug-fix and change-request procedures (and billing).

Update your development and QA process.

Update your attitude.

Your job is primarily to know what you're doing and deliver high quality work. If you don't have processes in place to ensure the client is getting a stable product, you need to fix that -- immediately. Secondly, but equally importantly, it's your job to politely educate the client when misunderstandings about the work, the product, or the process arise.

Imagine taking your car into the mechanic to replace a battery. Shortly after the replacement, you hear "funny noises" when you turn a corner. When you return with your car, your mechanic will (should) politely investigate the issue, explain the situation, and bill based on whether the newfound noise was related to the battery install.

He probably won't go to his buddies say, "I have a pathetic client", unless you've been truly unruly -- in which case, a good mechanic might offer a refund and recommend another mechanic.


答:
You are really asking on the wrong website. As a programmer, you don't reply to this at all. Your manager, or better your product manager, or maybe your sales people, they are the ones to reply to the customer.

Now if your manager, or product manager, or sales people, come to you and ask why they have so many complaints about bugs in the software, then the bad answer is "must be because I'm a pathetic developer". The good answer would be "do you remember how we told you that one week testing isn't enough? And how we told you that we shouldn't make these big changes just before the release? And how we told you that we have to spend some serious time improving quality instead of adding more features? "


问:
Should the commit history be used to convey critical information to developers?
During a meeting regarding the rollback of a third-party SDK from the latest version it was noted that the our developers already flagged in the commit history that the latest version should not be used.

Some developers argued that this was a bad practice and it should have instead been noted either in the source file (i.e. // Don't upgrade SDK Version x.y.z, see ticket 1234) or in a project level README file. Others argued that since the commit history is part of the project documentation it is an acceptable location for such information since we should all be reading it anyway.

Should the commit history be used to convey critical information to other developers or should such information be duplicated to another location such as a project README or comments in the relevant source file?

答:
History is a great place to put data intended for a reader who is consciously looking for it, and has a general sense of where it should be.  It is a very bad place to put data which must be proffered to a user, rather than searched for.

Histories are very large bodies of relatively unsorted text.  They are usually intended to provide a developer with detailed information about what changed, and why it was changed.  This can be information overload unless one knows what they are looking for.

If a user does not know what they are looking for, then the information is quickly buried under hundreds of commit logs, and they have no tool to prune down the pile of information in front of them.


答:
Something that may help is to point out that software development is similar to a production environment.  Even the most stringent of environments, such as nuclear reactors, understand that the unknown must be bounded statistically.  Their bounds are just tighter than ours.

Explain to your customers that you can bring bugs to an arbitrarily rare level, such as the elusive "6 sigma" that is so popular now days.  However, development of large applications at this grade is exceedingly expensive.  If they truly value a low bug rate, they are free to pay the cost for it.

Another approach you can take is to create more testable requirements.  If they want you to reach a very high level of reliability in your software, the requirements you are given are going to have to be more and more specific.  If I am given the requirement

Users should feel the interface is interactive

I cannot reach a high level of reliability.  If I am given the requirement

When the user clicks on the interface, it should respond within 0.1
  second 95% of the time.  In 4.99% of the remaining cases, it should
  display a 'waiting' icon while it is processing

then I can seek a high level of reliability because I can develop a testing process to mitigate bugs.

As a follow on, I would like to suggest an alternative to seek.  Your customer is acting like a customer.  If you are given the opportunity, try to work with them to turn them into a partner.  The customer/provider relationship is not as stable as the partner/partner relationship.  The latter can actually deal with bugs better.

I list this as a follow on because it doesn't really address your question, but I find it is something important to think about when dealing with longer term customers.


答:
Agree wholeheartedly with the customer that repeated bugs are a problem

Have the customer agree that more work should be done to prevent these bugs

Have the customer agree that more qa and more testing is appropriate

Have the customer agree that this will initially seem to slow things down a bit and cost more

Do more qa and write more tests during development.

Invoice accordingly


问:
Architecture for application-wide diagnostic-gathering tool?
My product owner wants us to report more information on the state of the product when a user contacts customer service through an in-app form.  The form eventually results in an email being sent to a customer service email list and handled elsewhere.

The part I'm struggling with is how to augment my existing iOS project to allow for some controller to collect diagnostic information from a variety of disparate classes, and do it in a way that's minimally invasive and won't cause a headache if refactoring later.

Blocks

I've experimented with a few ideas, including having an interface that allows an arbitrary class to register a block to be executed when attempting to collect the diagnostic information:

```<code>[DiagnosticCollectionController addBlockForDiagnosis:^(DiagnosticCollectionController *controller){
    // Add some information here to the controller to send in the diagnostic report
}];
</code>```

Notifications

Another idea I had in mind was to have the diagnostic controller broadcast a notification when it's ready to start gathering information, so that other objects can attach what they need to.  The (potential) advantage here is that I can get away from using blocks thus prevent myself from having block copy issues:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(someSelectorToHandleDiagnosticPopulation:)
                                             name:DiagnosticCollectionControllerWillSendDiagnostics
                                           object:someDiagnosticController];
// Elsewhere
- (void) someSelectorToHandleDiagnosticPopulation:(NSNotification *)note {
    DiagnosticController *controller = [note object];
    [controller addDiagnosticData:someDataDictionary];
}
</code>```

答:
I like your notification approach better than your block approach. I recommend having each pertinent subsystem or component implement an interface that can return status information when requested. They would then register themselves with a centralized status collection service. At key times, the status service could fetch status from each registered component, build a report, and attach it to the customer service email. Whether the fetching is done manually or through the iOS notification system is less important, I think.

BTW, if the objects that can provide status are transient, then you might need to be careful that the status collection service not hold references to them when they are no longer needed. A weak reference might help here.


问:
Which language introduced the idea of private (hidden) variables?
I know C++ had private variables inside classes, and Java, C#, Javascript, and others picked up on that and ran with it. Aside from variable scope, most languages before that just made everything visible. Certainly in assembly, all of memory is accessible (except as limited by hardware).

But was C++ the first language to support the idea of encapsulation?

答:
One form of Javascript encapsulation is one of scope.   There aren't modules as such - people just stuff things inside a function ((function(){ ... })(this)) and the things inside of that function can't be used outside.  You can hide quite a bit in local scope, and many languages have had it (though arguably, without first class functions this isn't enough for encapsulation of data).

Once we start mentioning first class functions and history, we firmly fall into talking about Lisp.  And there's a lot there to be said too.

Early Fortran (for the 704) didn't have subroutines or scope.  It was Fortran II that introduced these things.

My apologies for writing off Lisp (1958) with a single sentence... and not saying much about Fortran (1957), or Fortran II (1958).  Lisp had closures and Fortran II appears to have some lexical scoping...

When you talk about encapsulation and structured programming the name that should jump out at you is Niklaus Wirth.

What we often think of as encapsulation are things like private variables within a module.  Sure, you had things that could pop in and out of scope that couldn't be accessed outside of the scope.  But you didn't have "here is this module of code that has some things that you just can't see over there".

It was Modula 2 (1978) that brought us syntax like:

```<code>DEFINITION MODULE M1;
  EXPORT QUALIFIED a, b, c, P;
</code>```

Where one could then later access M1.a and M1.b but not M1.d (because that wasn't exported).

You could also do:

```<code>MODULE M2;
  FROM M1 IMPORT a, P;
</code>```

Some of the language looks downright Pythonish...

```<code>MODULE Hello;
FROM STextIO IMPORT WriteString;
BEGIN
  WriteString("Hello World!");
END Hello.
</code>```

This is more than just hiding something within some scope to not clobber name space.  This is hiding the visibility of some variables, procedures or functions from other modules. (Tutorial on modules within Modula-2)  This type of encapsulation is what we often think of now and see in languages like C++ (1983), Java (1995), and C# (2000).

Modula wasn't the only language to have some form of data hiding.  Simula was an early object oriented language that had some data encapsulation:

This particular extension was from a later extension to the language from around 1972.  This made its way into the standard of Simula 87 (the original Simula 67 had everything as public and lacked encapsulation).  This language a strong influence on C++ (A Conversation with Bjarne Stroustrup, Why I Created C++).

This protection block for an identifier allowed a class to specify if its subclasses - Hidden could only be used in the class where its declared and Protected could only be used where it was declared and its subclasses.

One more mention from another old object oriented language - Smalltalk (1972).

In Smalltalk, all instance variables were protected (visible only to the class and its subclasses) and all methods were public (Smalltalk object model).  This could be used to preform some encapsulation.

It was considered bad form to access an instance variable of the superclass from a subclass, or to invoke a method in the 'private' category).

Related reading:

History of access control modifiers such as public/private/protected

Body:
One form of Javascript encapsulation is one of scope.   There aren't modules as such - people just stuff things inside a function ((function(){ ... })(this)) and the things inside of that function can't be used outside.  You can hide quite a bit in local scope, and many languages have had it (though arguably, without first class functions this isn't enough for encapsulation of data).

Once we start mentioning first class functions and history, we firmly fall into talking about Lisp.  And there's a lot there to be said too.

Early Fortran (for the 704) didn't have subroutines or scope.  It was Fortran II that introduced these things.

My apologies for writing off Lisp (1958) with a single sentence... and not saying much about Fortran (1957), or Fortran II (1958).  Lisp had closures and Fortran II appears to have some lexical scoping...

When you talk about encapsulation and structured programming the name that should jump out at you is Niklaus Wirth.

What we often think of as encapsulation are things like private variables within a module.  Sure, you had things that could pop in and out of scope that couldn't be accessed outside of the scope.  But you didn't have "here is this module of code that has some things that you just can't see over there".

It was Modula 2 (1978) that brought us syntax like:

DEFINITION MODULE M1;
  EXPORT QUALIFIED a, b, c, P;

Where one could then later access M1.a and M1.b but not M1.d (because that wasn't exported).

You could also do:

MODULE M2;
  FROM M1 IMPORT a, P;

Some of the language looks downright Pythonish...

MODULE Hello;
FROM STextIO IMPORT WriteString;
BEGIN
  WriteString("Hello World!");
END Hello.

This is more than just hiding something within some scope to not clobber name space.  This is hiding the visibility of some variables, procedures or functions from other modules. (Tutorial on modules within Modula-2)  This type of encapsulation is what we often think of now and see in languages like C++ (1983), Java (1995), and C# (2000).

Modula wasn't the only language to have some form of data hiding.  Simula was an early object oriented language that had some data encapsulation:

This particular extension was from a later extension to the language from around 1972.  This made its way into the standard of Simula 87 (the original Simula 67 had everything as public and lacked encapsulation).  This language a strong influence on C++ (A Conversation with Bjarne Stroustrup, Why I Created C++).

This protection block for an identifier allowed a class to specify if its subclasses - Hidden could only be used in the class where its declared and Protected could only be used where it was declared and its subclasses.

One more mention from another old object oriented language - Smalltalk (1972).

In Smalltalk, all instance variables were protected (visible only to the class and its subclasses) and all methods were public (Smalltalk object model).  This could be used to preform some encapsulation.

It was considered bad form to access an instance variable of the superclass from a subclass, or to invoke a method in the 'private' category).

Related reading:

History of access control modifiers such as public/private/protected


答:
Plan for your project security before you start coding, Not after.<br/>
Also There are very good answers on SO on many similar questions : Like this and this </p>

Body:
Plan for your project security before you start coding, Not after.

Also There are very good answers on SO on many similar questions : Like this and this


问:
I recently read about unit of work and repository design patterns; working with EF wondering if this is a good design pattern
I found myself creating child records that require a master record to exist, first, so that they can reference it by the master record's primary key (if that's the right term).

To accomplish this using EF 6 I tried to call SaveChanges() twice - once to create the master record so that its identity key gets generated and once after the children have been created.

The problem I ran into was that EF doesn't like multiple calls to SaveChanges() so I had to use a transaction.  I don't like using a transaction because it feels messy for some reason I can't articulate.

It's a somewhat common problem for me to have to do this so instead of a using, try/catch and commit/rollback I figured it'd be easier to have this each time:

```<code>this._dbContextWrapper.CommitIfTrue(() =>
{
    // Multiple calls to SaveChanges() here

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

While also having BeginTransaction() exposed on my _dbContextWrapper so that if passing a Func<bool> isn't desirable.

```<code>public interface IRepository
{
    IQueryable<TModel> Query<TModel>()
        where TModel : class;

    TModel Find<TModel>(params object[] key)
        where TModel : class;

    void Add<TModel>(TModel model)
        where TModel : class;

    void Update<TModel>(TModel updated, params object[] key)
        where TModel : class;

    IDataResult SaveChanges();

    void Delete<TModel>(params object[] key)
        where TModel : class;

    IRepositoryTransaction BeginTransaction();

    IRepositoryTransaction BeginTransaction(IsolationLevel isolationLevel);

    IDataResult CommitIfTrue(Func<bool> transaction);

    IDataResult CommitIfTrue(Func<bool> transaction, IsolationLevel isolationLevel);
}

public interface IRepositoryTransaction : IDisposable
{
    void Commit();

    void Rollback();
}

public interface IDataResult
{
    bool IsSuccess { get; }

    string ErrorMessage { get; }
}
</code>```

I realize that this "IRepository" only a thin wrapper around DbContext - I'm doing it so that my classes can have a Mock implementation provided to them instead of having to mess with Fakes to get around the non-virtual aspect of DbContext's methods.

My question is:

Is my CommitIfTrue method reasonable?  Is there a way to do something similar that's also more testable/involves no Actions or Funcs?

答: I don't know why it would need to return true. Why couldn't it simply commit if no exception is thrown? That's the way it would be if you just had a transaction in a using statement. There are arguments for and against external vs. internal control of these types of things (ie. external vs internal iteration), but I don't see the need to have BOTH CommitIfTrue() and BeginTransaction(). They essentially provide the same functionality.


问:
Chasing DirectX versions
We're a small-medium size enterprise (~50 devs), working on several DirectX 9 applications. (not games)

DirectX 10 and 11 both were deep interface overhauls, as DX12 will probably be. We didn't upgrade to any of them, and since VS2013 (now migrating) working with DX9 is getting very inconvenient to say the least - while DX9 is not technically deprecated, MS is very actively pushing devs away from it.

I wonder, how are other dev shops handling the DX interface instability?  Are you actually re-writing your graphics engine every ~2-3 years?   Are you using 3rd party middleware?  Both OGRE and Unity seem like tons of code, have design goals I don't care about (cross platform), and I'm not even sure their interface is more stable.      Are there other ways I'm missing?

Important note:  We're not developing AAA games, and we've not much use for fancy shaders or a need to squeeze every bit of performance from modern hardware.    Our products just display data mostly in 3D.

it seems some clarifications are in order.  The current state of graphics development is that MS issues a completely overhauled DX interface roughly every ~2-3 years.  It seems - whether deliberately or not - they are targeting major game shops (or even: game-engine shops), which would happily devote the needed HR to rewrite the 3D graphics engine to conform to the latest and greatest.

Our shop (and I suspect many others) is nothing like that. We present a lot of data in 3D, but do not use exotic shaders and don't care about the latest consoles or GPUs.  It makes no business sense for us to rewrite our rendering engine for new features we don't care about - and yet the old engines are becoming deprecated fast.    A DX dev from MS writes:

the ability to support a Direct3D 9 application at all is diminished on the latest versions of Windows, and that's likely to continue

And regarding D3DX - while not technically deprecated, is very hard to work with on VS2013. MSDN diplomatic Quote:

Investigate alternate solutions for working with the Direct3D API.

I'm curious: how are other shops with similar 3D needs handling this?   e.g., how are you guys in the CAD business doing?

答:
Direct3D changes frequently because graphics hardware is constantly evolving. So at some point, Microsoft can no longer maintain compatibility with older D3D versions. This is why fixed-function rendering is gone. Newer hardware doesn't support it, so it cannot be exposed in the API any longer.

Now from what you've explained, your use of 3D doesn't seem very demanding, which probably means you could write a small interface layer to insulate your application from the rendering back-end. If you design the rendering interface well, the amount of actually API dependant code is very small. Even for a large game engine like Ogre3D, if you look in the source code at the API specific folder, you'll see that it consistes of some dozen files. Probably less than 1% of project's code.

With an interface layer between the rendering API and application you can add software emulation in the future if a hardware feature goes away. E.g.: Simulate the fixed pipeline with shaders; So maybe use the API change opportunity for a possible refactoring of the renderer module in a way to make it mode API agnostic.

ContentLicense: CC BY-SA 4.0

Title: Chasing DirectX versions


问:
Pure Front end JavaScript with Web API versus MVC views with ajax
This was more a discussion for what peoples thoughts are these days on how to split a web application.

I am used to creating an MVC application with all its views and controllers. I would normally create a full view and pass this back to the browser on a full page request, unless there were specific areas that I did not want to populate straight away and would then use DOM page load events to call the server to load other areas using AJAX.

Also, when it came to partial page refreshing, I would call an MVC action method which would return the HTML fragment which I could then use to populate parts of the page. This would be for areas that I did not want to slow down initial page load, or areas that fitted better with AJAX calls. One example would be for table paging. If you want to move on to the next page, I would prefer it if an AJAX call got that info rather than using a full page refresh. But the AJAX call would still return an HTML fragment.

My question is. Are my thoughts on this archaic because I come from a .net background rather than a pure front end background?

An intelligent front end developer that I work with, prefers to do more or less nothing in the MVC views, and would rather do everything on the front end. Right down to web API calls populating the page. So that rather than calling an MVC action method, which returns HTML, he would prefer to return a standard object and use javascript to create all the elements of the page.

The front end developer way means that any benefits that I normally get with MVC model validation, including client side validation, would be gone. It also means that any benefits that I get with creating the views, with strongly typed html templates etc would be gone.

I believe this would mean I would need to write the same validation for front end and back end validation. The javascript would also need to have lots of methods for creating all the different parts of the DOM. For example, when adding a new row to a table, I would normally use the MVC partial view for creating the row, and then return this as part of the AJAX call, which then gets injected into the table. By using a pure front end way, the javascript would would take in an object (for, say, a product) for the row from the api call, and then create a row from that object. Creating each individual part of the table row.

The website in question will have lots of different areas, from administration, forms, product searching etc. A website that I don't think requires to be architected in a single page application way.

What are everyone's thoughts on this?

I am interested to hear from front end devs and back end devs.

答:
Regarding the validation aspect in Web Api - It is possible to do "model validation" and respond with a 400 bad request http response.

Refer https://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api/25050285#25050285


问:
Why Microsoft’s Web API is named as ASP.Net Web API
ASP.Net is Active Server Pages using .Net Framework

Wikipedia says

It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology.

While answering this question following thought came to me – why Microsoft named it’s Web API as “ASP.Net Web API”. There are no Pages involved in Web API. Then why do some people call it as “Active Server Pages .Net Web Api” ?

I believe there are some fundamental features of ASP.Net shared with Web API. So what are they?

Another observation - why is the tag in programmers naming it as "asp.net-mvc-web-api"?

Reference:

ScottGu's Blog- ASP.NET Web API

答: Because it's part of the ASP.NET framework. Sure, ASP used to stand for "Active Server Pages" but it's really grown to be beyond that now. I've never heard anyone call it "Active Server Pages .Net Web Api", and I would be confused if they did. </p>


答:
Let's step back from this and take a higher level look.. shall we..
Did Eudora or outlook (a client side app, not even needing a browser) ever cause a financial loss for any company? No.
Anyone could write to the POP/SMTP API's and be the client. But no loss to the server.
The server didn't limit client actions, computations, storage, temperature, disk size, ram size, monitor DPI, GPU, FPU yada yada of the client but exactly specified what it would answer to and no more.
Did you ever hear of quicken or MS-Money being used to break to a bank?

Your browser (i.e. client side) app can use the same architecture.

You build your server with an API (which BTW, always boils down to derivatives of GET POST HEAD etc.).

On the server, ensure that the API only talks with an authenticated and identity verified client for each and every call.

Then you don't care who the client is.

And then you don't care if it's a browser, jailbroken device, Google glass, DOS 3.1,  or a brand new Nexus in the hands of a technophobe great-great-great-great-grandpa who has time traveled to 2014 and missed all the technology that's been flooding our lives in the last 15 decades.

Now you can start off-loading everything else to client side.

SoapBoxBegin

@KilianFoth raises an important awareness point for the naive and the reckless, mainly those who read the headlines all the time but never think it will happen to their app, their code, their employer, their client, their own bank account. Even more reckless are their employers (especially the CTO's) who would allow apps to get out that expose any systems to unmanaged/uncontrolled exposure. However I'm always puzzled at how it seems "we never learn".

SoapBoxEnd

So to summarize. Make a solid and tight server side API. Offload everything else to client based on whatever the client can handle.


问:
What is a lambda, and why would it be useful?
So far I heard about :

Lambda calculus

Lambda programming

Lambda expressions

Lambda functions

Which all seems to be related to functional programming...

Apparently it will be integrated into C++1x, so I might better understand it now:

http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions

Can somebody defines briefly what are lambdas things and give an where it can be useful ?

答:
Lambda calculus

The lambda calculus is a computation model invented by Alonzo Church in the 30s. The syntax and semantics of most functional programming languages are directly or indirectly inspired by the lambda calculus.

The lambda calculus in its most basic form has two operations: Abstraction (creating an (anonymous) function) and application (apply a function). Abstraction is performed using the λ operator, giving the lambda calculus its name.

Lambda expressions

Lambda functions

Anonymous functions are often called "lambdas", "lambda functions" or "lambda expressions" because, as I said above, λ was the symbol to create anonymous functions in the lambda calculus (and the word lambda is used to create anonymous functions in many lisp-based languages for the same reason).

Lambda programming

This is not a commonly used term, but I assume it means programming using anonymous functions or programming using higher-order functions.

A bit more information about lambdas in C++0x, their motivation and how they relate to function pointers (a lot of this is probably a repeat of what you already know, but I hope it helps explain the motivation of lambdas and how they differ from function pointers):

Function pointers, which already existed in C, are quite useful to e.g. pass a comparison function to a sorting function. However there are limits to their usefulness:

For example if you want to sort a vector of vectors by the ith element of each vector (where i is a run-time parameter), you can't solve this with a function pointer. A function that compares two vectors by their ith element, would need to take three arguments (i and the two vectors), but the sorting function would need a function taking two arguments. What we'd need is a way to somehow supply the argument i to the function before passing it to the sorting function, but we can't do this with plain C functions.

To solve this, C++ introduced the concept of "function objects" or "functors". A functor is basically an object which has an operator() method. Now we can define a class CompareByIthElement, which takes the argument i as a constructor argument and then takes the two vectors to be compared as arguments to the operator() method. To sort a vector of vectors by the ith element we can now create a CompareByIthElement object with i as an argument and then pass that object to the sorting function.

Since function objects are just objects and not technically functions (even though they are meant to behave like them), you can't make a function pointer point to a function object (you can of course have a pointer to a function object, but it would have a type like CompareByIthElement* and thus not be a function pointer).

Most functions in the C++ standard library which take functions as arguments are defined using templates so that they work with function pointers as well as function objects.

Now to lambdas:

Defining a whole class to compare by the ith element is a bit verbose if you're only ever going to use it once to sort a vector. Even in the case where you only need a function pointer, defining a named function is sub-optimal if it's only used once because a) it pollutes the namespace and b) the function is usually going to be very small and there isn't really a good reason to abstract the logic into its own function (other than that you can't have function pointers without defining a function).

So to fix this lambdas were introduced. Lambdas are function objects, not function pointers. If you use a lambda literal like [x1, x2](y1,y2){bla} code is generated which basically does the following:

Define a class which has two member variables (x1 and x2) and an operator() with the arguments (y1 and y2) and the body bla.

Create an instance of the class, setting the member variables x1 and x2 to the values of the variables x1 and x2 currently in scope.

So lambdas behave like function objects, except that you can't access the class that's generated to implement a lambda in any way other than using the lambda. Consequently any function that accepts functors as arguments (basically meaning any non-C function in the standard library), will accept lambdas, but any function only accepting function pointers will not.


问:
Architecture strategies for a complex competition scoring system
Competition description:

There are about 10 teams competing against each other over a 6-week period.

Each team's total score (out of a 1000 total available points) is based on the total of its scores in about 25,000 different scoring elements.

Most scoring elements are worth a small fraction of a point and there will about 10 X 25,000 = 250,000 total raw input data points.

The points for some scoring elements are awarded at frequent regular time intervals during the competition. The points for other scoring elements are awarded at either irregular time intervals or at just one moment in time.

There are about 20 different types of scoring elements.

Each of the 20 types of scoring elements has a different set of inputs, a different algorithm for calculating the earned score from the raw inputs, and a different number of total available points. The simplest algorithms require one input and one simple calculation. The most complex algorithms consist of hundreds or thousands of raw inputs and a more complicated calculation.

Some types of raw inputs are automatically generated. Other types of raw inputs are manually entered. All raw inputs are subject to possible manual retroactive adjustments by competition officials.

Primary requirements:

The scoring system UI for competitors and other competition followers will show current and historical total team scores, team standings, team scores by scoring element, raw input data (at several levels of aggregation, e.g. daily, weekly, etc.), and other metrics.

There will be charts, tables, and other widgets for displaying historical raw data inputs and scores.

There will be a quasi-real-time dashboard that will show current scores and raw data inputs.

Aggregate scores should be updated/refreshed whenever new raw data inputs arrive or existing raw data inputs are adjusted.

There will be a "scorekeeper UI" for manually entering new inputs, manually adjusting existing inputs, and manually adjusting calculated scores.

Decisions:

Should the scoring calculations be performed on the database layer (T-SQL/SQL Server, in my case) or on the application layer (C#/ASP.NET MVC, in my case)?

What are some recommended approaches for calculating updated total team scores whenever new raw inputs arrives? Calculating each of the teams' total scores from scratch every time a new input arrives will probably slow the system to a crawl. I've considered some kind of "diff" approach, but that approach may pose problems for ad-hoc queries and some aggegates. I'm trying draw some sports analogies, but it's tough because most games consist of no more than 20 or 30 scoring elements per game (I'm thinking of a high-scoring baseball game; football and soccer have fewer scoring events per game). Perhaps a financial balance sheet analogy makes more sense because financial "bottom line" calcs may be calculated from 250,000 or more transactions.

Should I be making heavy use of caching for this application?

Are there any obvious approaches or similar case studies that I may be overlooking?

答:
Here are my thoughts about this system.

The number of scoring elements seems to be very large and I tend to see that they are independent of each other (if not, you need to think about pre-process your large raw input so they become independent). This is the call sign for turning your system into a distributed system. You will have multiple peers each with its own SQL database running, and each with a service layer running on top of the SQL database.

There are two choices for the distributed system. A hierarchical one (meaning there is one master specialized node to do coordination, and multiple sub-coordinating nodes) or a peer-to-peer one. I would suggest you use the peer-to-peer model since they have several advantages:

This is highly robust, and you essentially have a backup system built-in in this model if you allow some redundant data on each peer node

If you can make raw input independent or they are inherently independent then you don't really need to cluster dependent raw input into a coordinating node as in hierarchical model

In order to save yourself from multiple headaches caused by concurrent modification of the data, make sure your data schema puts in additional timestamp data instead of deleting/modifying previous data in an edit. Have a timestamp system for each input piece as well. I can think of having 3 kinds of time at the moment: [1] logic time, [2] expired time, [3] write time. When an edit comes in, you add new data with new write-time while you keep the logic dates the same. In short, don't delete previous data. The timestamp is also a partial 'diff' framework for you since if part of the input data does not change, then the node responsible for that part only need to update the timestamp

Compute the component score that each peer is responsible whenever new data comes in. That way, you will not have to do much calculation when you want to get the score (current or historical). If you also put in timestamp for these scores, you also get faster historical score read time. This is in principle a cache for you. Also, do this at the service/application layer, don't do this in the SQL database layer. With timestamp, you'll have no problem with ad hoc queries.

You have to be careful with error handling and fixing things when something goes wrong at some node when you make a write. This will be non-trivial, you will have some heavy lifting done for you by SQL and message queue though.

The protocol for timestamping data and partial scores will need to be defined more specifically, but I don't see anything that is fundamentally wrong with this architecture. If you see, let me know. Many thanks!


问:
Multiple classes with the same name, but different namespaces?
I've run into some code (C# if it matters) that has classes which have the same name, but differ in their namespaces. They all tend to represent the same logical thing, but often are different "views" of the same object. The different namespaces are at times part of the same solution, and even the same dll.

I have my thoughts, but couldn't find anything definitive about this practice to be considered a clever use of the tools available or a pattern to avoid.

This question on smurf naming touches on this, but from the other direction. Disambiguating the names would likely require an arbitrary and pervasive prefix, which that question wanted to eliminate.

What are the guidelines around this practice?

答:
I'll try to give an answer against such usage, after having seen and worked on this in one of my projects as well.

Code readability

First of all, consider that code readability is important and this practice is counter to that. Someone reads a piece of code and let's just say it has a function doSomething(Employee e). This is no longer readable, because due to 10 different Employee classes existing in different packages you will have to first resort to the import declaration to find out what your input really is.

This, however, is a high-level view and we often have seemingly random name clashes, which no one cares about or even finds, because the meaning can be derived from the remaining code and which package you are in. So one could even argue that, locally, there is no problem, because of course if you see Employee within an hr package you have to know that we're talking about an HR view of the employee.

Things break apart as soon as you leave these packages though. Once you are working in a different module/package/etc and need to work with an employee, you're already sacrificing readability if you do not fully qualify its type. Additionally, having 10 different Employee classes means that your IDE's auto-completion will no longer work and you have to manually choose from the type of employee.

Code duplication

Due to the very nature of each of these classes being related to each other your code is bound to deteriorate due to lots of duplication. In most cases, you will have something like an employee's name or some identification number, which each of the classes has to implement. Even though each class adds its own sort of view, if they do not share the underlying employee data, then you will end up with huge masses of useless, but costly, code.

Code complexity

What can be so complex you may ask? After all, each of the classes can keep it as simple as it wants to. What truly becomes a problem is how you propagate changes. In a reasonably feature-rich software you may be able to change employee data - and you want to reflect that everywhere. Say that one lady just married and you have to rename her from X to Y due to that. Hard enough to do this right all over the place, but even harder when you have all of these distinct classes. Depending on your other design choices, this may easily mean that each of the classes has to implement its own sort of listener or such to be notified of changes - which basically translates to a factor being applied to the number of classes you have to deal with. And more code duplication of course, and less code readability, .. Factors like this may be ignorable in complexity analysis, but they sure are annoying when applied to the size of your code base.

Code communication

Apart from the above problems with code complexity, which are also related to design choices, you are also reducing your higher-level design clarity and lose the ability to properly communicate with domain experts. When you discuss architecture, designs, or requirements you are no longer free to make simple statements like given an employee, you can do .... A developer will no longer know what employee really means at that point. Although a domain expert will know it of course. We all do. sort of. But in terms of the software it's not so easy to communicate anymore.

How to get rid of the problem

After becoming aware of this and if your team agrees that it is a problem big enough to tackle, then you will have to work out a way to deal with it. Typically, you cannot ask your manager to give the whole team a week off so they can take out the trash. So in essence,you will have to find a way to partially eliminate these classes, one at a time. The most important part about this is to decide - with the whole team - what an Employee really is. Do not integrate all of the individual attributes into one god-employee. Think more of a core-employee and most importantly, decide where that Employee class will reside.

If you do code reviews, then it is particularly easy to ensure that the problem does at least not grow any further, i.e. stop everyone right in their track when they want to add another Employee again. Also take care that new subsystems adhere to the agreed Employee and are not allowed to access the old versions.

Depending on your programming language, you may also want to mark the classes that will eventually be eliminated with something like @Deprecated to aid your team in immediately realizing that they're working with something that will have to be changed.

As for getting rid of the outdated employee classes, you can decide for each individual case how it's best eliminated, or just agree on a common pattern. You can affix the class name and wrap it around the real employee, you can use patterns (decorator or adapter come to mind), or, or or.

To make a long story short: This "practice" is technically sound, but is choked full of hidden costs that will only occur further down the road. While you may not be able to immediately get rid of the problem, you can start immediately with containing its harmful effects.