问:
Is my understanding of abstract datatypes correct?
After reading lots of pages on various sites, I came to the conclusion that abstract datatype helps to separate the use of datastructure from its implementation. We can easily map the data into a datastructure by using an already available abstraction. And this abstraction is called ADT. Please tell me if I have understood this correctly. Also if you can give a small example, it will be very helpful. If you prefer to give any code in your example, C or Python would be helpful for me.

Addition: They are a very special implementation of data abstraction. What separates them from other instances of abstractions is that ADTs are theoretical constructs. Theoretical constructs that help map or represent data in a desired data structure. They have attributes or operations associated with them. These operations may be applied on the data that has been mapped into the ADT. How the data is actually stored inside the ADT or how the operations work are kept hidden.

EDIT: I had previously said, "ADT is like the blueprint of a datastructure". A few of the answers have explained why it's not. I didn't have a clear comprehension of what a 'blueprint' is and that was the reason for using the term. So, I've now removed it from my original text.

答:
You have understood this correctly. ADTs are portable, theoretical constructs that can then be implemented in most any given programming language.

Example: Stack

A Stack as an ADT is a list of some type that provides Last In, First Out (LIFO) access to its data members. Thus it can only be accessed at one point, the "top" of the stack.

In Python that'd look something like:

```<code>class Stack:

    def __init__(self): # initializes the stack with an empty list to hold stuff
        self.list = []

    def push(n): # pushes item n onto the stack
        stack.list.append(n)

    def pop: # removes the "top" item from the stack
        del stack.list[-1]

    def peek: # looks at the top item of the stack
        view = stack.list[-1]
        return view
</code>```

And that should about do it for one way to implement a basic stack. I've not tested this code so use at your own risk. Python in fact expects you to use lists as stacks by default so it's covered in the tutorial documentation. There's even a built in "pop" method.

Generally, you'd implement a stack as either an array or a linked list. The array can be useful if you want a little bit less memory overhead and it's generally easier to code. However, a list based stack can expand much more easily and quickly.

Body:
You have understood this correctly. ADTs are portable, theoretical constructs that can then be implemented in most any given programming language.

Example: Stack

A Stack as an ADT is a list of some type that provides Last In, First Out (LIFO) access to its data members. Thus it can only be accessed at one point, the "top" of the stack.

In Python that'd look something like:

class Stack:

    def __init__(self): # initializes the stack with an empty list to hold stuff
        self.list = []

    def push(n): # pushes item n onto the stack
        stack.list.append(n)

    def pop: # removes the "top" item from the stack
        del stack.list[-1]

    def peek: # looks at the top item of the stack
        view = stack.list[-1]
        return view

And that should about do it for one way to implement a basic stack. I've not tested this code so use at your own risk. Python in fact expects you to use lists as stacks by default so it's covered in the tutorial documentation. There's even a built in "pop" method.

Generally, you'd implement a stack as either an array or a linked list. The array can be useful if you want a little bit less memory overhead and it's generally easier to code. However, a list based stack can expand much more easily and quickly.


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
It very much depends on what's in the code.

I have seen a thousand-line routine that I had no problem with.  It was a huge switch statement, no option exceeded a dozen lines and the only control structure in any option was a single loop.  These days it would have been written with objects but that wasn't an option back then.

I'm also looking at 120 lines in a switch in front of me.  No case exceeds 3 lines--a guard, an assignment and the break.  It's parsing a text file, objects aren't a possibility.  Any alternative would be harder to read.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Can I use Dependency Injection without breaking Encapsulation?
Here is my Solution and projects:

BookStore  (solution)

BookStore.Coupler  (project)

Bootstrapper.cs

BookStore.Domain (project)

CreateBookCommandValidator.cs

CompositeValidator.cs

IValidate.cs

IValidator.cs

ICommandHandler.cs

BookStore.Infrastructure (project)

CreateBookCommandHandler.cs

ValidationCommandHandlerDecorator.cs

BookStore.Web (project)

Global.asax

BookStore.BatchProcesses (project)

Program.cs

Bootstrapper.cs:

```<code>public static class Bootstrapper.cs
{
    // I'm using SimpleInjector as my DI Container
    public static void Initialize(Container container)
    {
        container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), typeof(CreateBookCommandHandler).Assembly);
        container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>));
        container.RegisterManyForOpenGeneric(typeof(IValidate<>),
            AccessibilityOption.PublicTypesOnly,
            (serviceType, implTypes) => container.RegisterAll(serviceType, implTypes),
            typeof(IValidate<>).Assembly);
        container.RegisterSingleOpenGeneric(typeof(IValidator<>), typeof(CompositeValidator<>));
    }
}
</code>```

CreateBookCommandValidator.cs

```<code>public class CreateBookCommandValidator : IValidate<CreateBookCommand>
{
    public IEnumerable<IValidationResult> Validate(CreateBookCommand book)
    {
        if (book.Author == "Evan")
        {
            yield return new ValidationResult<CreateBookCommand>("Evan cannot be the Author!", p => p.Author);
        }
        if (book.Price < 0)
        {
            yield return new ValidationResult<CreateBookCommand>("The price can not be less than zero", p => p.Price);
        }
    }
}
</code>```

CompositeValidator.cs

```<code>public class CompositeValidator<T> : IValidator<T>
{
    private readonly IEnumerable<IValidate<T>> validators;

    public CompositeValidator(IEnumerable<IValidate<T>> validators)
    {
        this.validators = validators;
    }

    public IEnumerable<IValidationResult> Validate(T instance)
    {
        var allResults = new List<IValidationResult>();

        foreach (var validator in this.validators)
        {
            var results = validator.Validate(instance);
            allResults.AddRange(results);
        }
        return allResults;
    }
}
</code>```

IValidate.cs

```<code>public interface IValidate<T>
{
    IEnumerable<IValidationResult> Validate(T instance);
}
</code>```

IValidator.cs

```<code>public interface IValidator<T>
{
    IEnumerable<IValidationResult> Validate(T instance);
}
</code>```

ICommandHandler.cs

```<code>public interface ICommandHandler<TCommand>
{
    void Handle(TCommand command);
}
</code>```

CreateBookCommandHandler.cs

```<code>public class CreateBookCommandHandler : ICommandHandler<CreateBookCommand>
{
    private readonly IBookStore _bookStore;

    public CreateBookCommandHandler(IBookStore bookStore)
    {
        _bookStore = bookStore;
    }

    public void Handle(CreateBookCommand command)
    {
        var book = new Book { Author = command.Author, Name = command.Name, Price = command.Price };
        _bookStore.SaveBook(book);
    }
}
</code>```

ValidationCommandHandlerDecorator.cs

```<code>public class ValidationCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> decorated;
    private readonly IValidator<TCommand> validator;

    public ValidationCommandHandlerDecorator(ICommandHandler<TCommand> decorated, IValidator<TCommand> validator)
    {
        this.decorated = decorated;
        this.validator = validator;
    }

    public void Handle(TCommand command)
    {
        var results = validator.Validate(command);

        if (!results.IsValid())
        {
            throw new ValidationException(results);
        }

        decorated.Handle(command);
    }
}
</code>```

Global.asax

```<code>// inside App_Start()
var container = new Container();
Bootstrapper.Initialize(container);
// more MVC specific bootstrapping to the container. Like wiring up controllers, filters, etc..
</code>```

Program.cs

```<code>// Pretty much the same as the Global.asax
</code>```

Sorry for the long setup to the problem, I have no better way of explaining this other than detailing my actual problem.

I don't want to make my CreateBookCommandValidator public. I would rather it be internal but if I make it internal then I will not be able to register it with my DI Container.  The reason I would like it to be internal is because the only project that should have notion of my IValidate<> implementations are in the BookStore.Domain project.  Any other project just needs to consume IValidator<> and the CompositeValidator should be resolved which will fulfill all validations.

How can I use Dependency Injection without breaking encapsulation?  Or am I going about this all wrong?

答:
Another option is to make it public but put it in another assembly.

So essentially, you have a service interfaces assembly, a service implementations assembly (which references service interfaces), a service consumer assembly (which references service interfaces), and an IOC registrar assembly (which references both service interfaces and service implementations to hook them together).

I should stress, this is not always the most appropriate solution, but it is one worth considering.

OwnerDisplayName: Evan Larsen


问:
Understanding the difference between mutable and immutable classes
I faced this question in one interview. I explained that String is immutable and StringBuffer is mutable class. I don't know very much about mutable and immutable and also don't know the exact answer. What are the key concepts to be able to distinguish the two ideas?  Is there a performance impact when chosing one over the other?

答:
Used in terms of primitives (built in type), and objects (user defined type).
Immutable means you can't change the value.
Mutable means you can change the value. </p>

<p>Many think primitive variables and object variables having a final modifier in front of them are immutable, however, this isn't exactly true. Final almost doesn't mean immutable for variables. Check out this link for a code sample http://www.siteconsortium.com/h/D0000F.php. </p>

Body:
Used in terms of primitives (built in type), and objects (user defined type).
Immutable means you can't change the value.
Mutable means you can change the value.

Many think primitive variables and object variables having a final modifier in front of them are immutable, however, this isn't exactly true. Final almost doesn't mean immutable for variables. Check out this link for a code sample http://www.siteconsortium.com/h/D0000F.php.


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
Immutable means you can't change the value, and mutable means you can change the value if you think in terms of primitives, and objects.
Objects are different than primitives in Java in that they are built in types. Primitives are built in types like int, boolean, and void.

A lot of people people think that primitives and objects variables that have a final modifier infront of them are immutable,
however, this isn't exactly true. So final almost doesn't mean immutable for variables. Check out this link for a code sample:

```<code>public abstract class FinalBase {

    private final int variable; // Unset

    /* if final really means immutable than
     * I shouldn't be able to set the variable
     * but I can.
     */
    public FinalBase(int variable) {
        this.variable = variable;
    }

    public int getVariable() {
        return variable;
    }

    public abstract void method();
}

// This is not fully necessary for this example
// but helps you see how to set the final value
// in a sub class.
public class FinalSubclass extends FinalBase {

    public FinalSubclass(int variable) {
        super(variable);
    }

    @Override
    public void method() {
        System.out.println( getVariable() );
    }

    @Override
    public int getVariable() {

        return super.getVariable();
    }

    public static void main(String[] args) {
        FinalSubclass subclass = new FinalSubclass(10);
        subclass.method();
    }
}
</code>```

Body:
Immutable means you can't change the value, and mutable means you can change the value if you think in terms of primitives, and objects.
Objects are different than primitives in Java in that they are built in types. Primitives are built in types like int, boolean, and void.

A lot of people people think that primitives and objects variables that have a final modifier infront of them are immutable,
however, this isn't exactly true. So final almost doesn't mean immutable for variables. Check out this link for a code sample:

public abstract class FinalBase {

    private final int variable; // Unset

    /* if final really means immutable than
     * I shouldn't be able to set the variable
     * but I can.
     */
    public FinalBase(int variable) {
        this.variable = variable;
    }

    public int getVariable() {
        return variable;
    }

    public abstract void method();
}

// This is not fully necessary for this example
// but helps you see how to set the final value
// in a sub class.
public class FinalSubclass extends FinalBase {

    public FinalSubclass(int variable) {
        super(variable);
    }

    @Override
    public void method() {
        System.out.println( getVariable() );
    }

    @Override
    public int getVariable() {

        return super.getVariable();
    }

    public static void main(String[] args) {
        FinalSubclass subclass = new FinalSubclass(10);
        subclass.method();
    }
}


答: I think a good reason would be to model "real-life" mutable "objects", like interface windows.  I vaguely remember having read that the OOP was invented when somebody tried to write software to control some cargo port operation.</p>

Title: If immutable objects are good, why do people keep creating mutable objects?

Body:
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.


问:
Why we say Lisp are Human oriented and Fortran are Machine oriented？

Lisp and Fortran were the trunks of two separate evolutionary trees,
    one rooted in math and one rooted in machine architecture.

I see this in Hackers and Painters: Big Ideas from the Computer Age.

And someone said that Lisp are Human oriented and Fortran are Machine oriented.

Here human oriented means that the way of problem solving is more likely human do.

And machine oriented means that the way of problem solving is more likely machine do.

I think that Lisp and base on S-expression and symbol.
Fortran are base on von Neumann and Variables.

Is it right?

答:
Why we say Lisp are Human oriented and Fortran are Machine oriented？

“We” don't say that: Lisp advocates do ;-)

Both Fortran and Lisp were designed for humans. You could say that Fortran is even more human-oriented:

Don't you hate writing assembler? Where implementing a simple formula consists of confusing adds and muls and registers? Of course you hate it, you're an engineer, not a programmer. Fortran has the solution: You can now use expressions like 2.0 * (X + Y). I can't believe it's not butter math!

Whereas Lisps tend to have the extremely compiler-oriented S-Expressions for everything.

The point is that Fortran and Lisp approach the problem of programming languages from different directions:

Fortran moves away from low-level assembler towards more human-accessible formats: a high-level language. This is mostly syntactic and results in greater productivity for the programmer.

Lisp is an implementation of the lambda calculus with high-level aspects like higher-order functions, recursion and dynamic typing which it somehow tries to map to low-level machine code. But the brilliant design decision of Lisp was to make everything a list. This is less performant than Fortran's arrays, but variable-size data structures are much more flexible. Lisp reifies many language features like variables (via symbols) or functions and even code itself which facilitates metaprogramming.

Together this combination of Lisp features produces a different mind-set when programming. Some people claim that these features make Lisp more human-oriented (I wouldn't say that, because Lisp appears to be Lisp-oriented to me).

Note that most modern languages take from both traditions: C# takes Fortran's statements and expressions as building blocks of syntax, while Lambdas and its flavor of object orientation have a very Lispish feeling.


答:
This is just a gist on the subject, I strongly suggest following the links herein.

"An abstract data type defines a class of abstract objects which is completely characterized by the operations available on those objects. This means that an abstract data type can be defined by defining the characterizing operations for that type." Liskov, Zilles: Programming with abstract data types

Given the informal definition above, the following pseudo-code can be seen as an ADT:

```<code>type stack;
stack stack_create();
void stack_push(stack, T);
T stack_pop(stack);
</code>```

One point is that nothing is known about stack objects, except what can be inferred by the operations available for it -- in the case above, stack_create, stack_push and stack_pop. Every single bit of implementation and structure detail is left to the implementation side.

Now, take an OO/python class called Stack with the methods push and pop.

```<code>class Stack:

    def __init__(self):
       ...
    def push(self, element):
       ...
    def pop(self):
       ...
</code>```

If its clients know that there is a class called Stack and they have access to it, one way to see it is that the objects are characterized by the fact that they are instances of the class Stack whose structure contains push and pop fields -- regardless of the fact that they are callable. Clients also know that they can inherit from Stack to create something else and so on.

That is, much more is known/exposed to clients. Therefore, this Stack type is much less abstract than the previous one (it is exposed as a concrete structure with two fields, has a class with which you can do inheritance, etc). Consequently, one could argue this Stack type is not an Abstract Data Type conforming to the given definition. To be more strict, one would have to write something like this:

```<code>def create_stack():
   ...
def stack_push(stack, element):
   ...
def stack_pop(stack):
   ...
</code>```

And here is a possible implementation of it (in the case below, if you already have the class above and just want to make it an ADT, it is just a wrapper):

```<code>def create_stack():
   retur Stack()
def stack_push(stack, element):
   return stack.push(element)
def stack_pop(stack):
   return stack.pop()
</code>```

Now the client only knows the operations and their interfaces and use them (and only them) to infer what is the type "stack". From outside, nothing is known about the actual implementation and structure of a stack (unless they breach the abstraction by inspecting the structure of the result of create_stack).

Similarly, in C, you could mimic this by putting these function declarations on a .h header file (using a forward declaration standing as the stack type, or simply void*), and then, putting the struct definition and function implementations in the .c file.

Note on type systems: All the above, of course, are not in the context of languages with static type checking and good type systems -- such language may need to provide certain instruments to make reasonable ADTs possible. Furthermore, the way this theme is exposed in the paper cited above, "strong" type checking appears to be a matter of author preference alone; I did not see them being discussed or shown to be a requirement of ADTs -- the text actually seems to be careful in discussing type checking as something related but not essential. Plus, the explanation of a "C approach to ADT" (see above) was given by William Cook, the researcher who wrote Object-Oriented Programming Versus Abstract Data Types. [edit] On the other hand, Cook writes:

"Abstract data types depend upon a static type system to enforce type abstraction. It is not an accident that dynamic languages use objects instead of user-deﬁned abstract data types. Dynamic languages typically support built-in abstract data types for primitive types; the type abstraction here is enforced by the runtime system."

Title: Is my understanding of abstract datatypes correct?

Body:
After reading lots of pages on various sites, I came to the conclusion that abstract datatype helps to separate the use of datastructure from its implementation. We can easily map the data into a datastructure by using an already available abstraction. And this abstraction is called ADT. Please tell me if I have understood this correctly. Also if you can give a small example, it will be very helpful. If you prefer to give any code in your example, C or Python would be helpful for me.

Addition: They are a very special implementation of data abstraction. What separates them from other instances of abstractions is that ADTs are theoretical constructs. Theoretical constructs that help map or represent data in a desired data structure. They have attributes or operations associated with them. These operations may be applied on the data that has been mapped into the ADT. How the data is actually stored inside the ADT or how the operations work are kept hidden.

EDIT: I had previously said, "ADT is like the blueprint of a datastructure". A few of the answers have explained why it's not. I didn't have a clear comprehension of what a 'blueprint' is and that was the reason for using the term. So, I've now removed it from my original text.

Body:
This is just a gist on the subject, I strongly suggest following the links herein.

"An abstract data type defines a class of abstract objects which is completely characterized by the operations available on those objects. This means that an abstract data type can be defined by defining the characterizing operations for that type." Liskov, Zilles: Programming with abstract data types

Given the informal definition above, the following pseudo-code can be seen as an ADT:

type stack;
stack stack_create();
void stack_push(stack, T);
T stack_pop(stack);

One point is that nothing is known about stack objects, except what can be inferred by the operations available for it -- in the case above, stack_create, stack_push and stack_pop. Every single bit of implementation and structure detail is left to the implementation side.

Now, take an OO/python class called Stack with the methods push and pop.

class Stack:

    def __init__(self):
       ...
    def push(self, element):
       ...
    def pop(self):
       ...

If its clients know that there is a class called Stack and they have access to it, one way to see it is that the objects are characterized by the fact that they are instances of the class Stack whose structure contains push and pop fields -- regardless of the fact that they are callable. Clients also know that they can inherit from Stack to create something else and so on.

That is, much more is known/exposed to clients. Therefore, this Stack type is much less abstract than the previous one (it is exposed as a concrete structure with two fields, has a class with which you can do inheritance, etc). Consequently, one could argue this Stack type is not an Abstract Data Type conforming to the given definition. To be more strict, one would have to write something like this:

def create_stack():
   ...
def stack_push(stack, element):
   ...
def stack_pop(stack):
   ...

And here is a possible implementation of it (in the case below, if you already have the class above and just want to make it an ADT, it is just a wrapper):

def create_stack():
   retur Stack()
def stack_push(stack, element):
   return stack.push(element)
def stack_pop(stack):
   return stack.pop()

Now the client only knows the operations and their interfaces and use them (and only them) to infer what is the type "stack". From outside, nothing is known about the actual implementation and structure of a stack (unless they breach the abstraction by inspecting the structure of the result of create_stack).

Similarly, in C, you could mimic this by putting these function declarations on a .h header file (using a forward declaration standing as the stack type, or simply void*), and then, putting the struct definition and function implementations in the .c file.

Note on type systems: All the above, of course, are not in the context of languages with static type checking and good type systems -- such language may need to provide certain instruments to make reasonable ADTs possible. Furthermore, the way this theme is exposed in the paper cited above, "strong" type checking appears to be a matter of author preference alone; I did not see them being discussed or shown to be a requirement of ADTs -- the text actually seems to be careful in discussing type checking as something related but not essential. Plus, the explanation of a "C approach to ADT" (see above) was given by William Cook, the researcher who wrote Object-Oriented Programming Versus Abstract Data Types. [edit] On the other hand, Cook writes:

"Abstract data types depend upon a static type system to enforce type abstraction. It is not an accident that dynamic languages use objects instead of user-deﬁned abstract data types. Dynamic languages typically support built-in abstract data types for primitive types; the type abstraction here is enforced by the runtime system."


问:
Google App Engine overview
I have gone through many Google App Engine tutorials, and I became quite familiar with how to do basic stuff like implementing a webapp2.RequestHandler, and using ndb.Models to manage your data.

Now, I kind of reached a wall with a few small concepts that were either missing from the resources I went over, or I simply missed them. So, here they are:

What happens to class variables?

As far as I understood, once I set my app to threadsafe, it can handle multiple requests concurrently, not to mention possibly on different machines. Does that mean I simply cannot use class variables (that can be changed at anytime)?

How to model an application wide logic?

It is very straight forward to write logic associated with requests. I don't have to worry about locking or any of that stuff, since a new RequestHandler is instantiated for each request. What about application-wide logic? Like, if I had a python module called "Game", and after importing it, I do somthing like:

Game.matchmaking_queue.append(player)

As far as I can tell, there is just one Game instance, and it has an instance variable accessed from within the RequestHandler logic. Will that be OK? Must I make the matchmaking_queue backed on memcache and/or datastore in order for all requests to see it? Do I have to do any thread-saftey magic on Game?

答:
The GAE can use different processes to handle different requests. Those different processes don't even need to be on the same machine, or in the same datacenter even. Then again, different requests can be routed to the same process.

This means that any 'global' state (module global, including attributes directly on classes) will be shared between requests within one process. See App Caching in the GAE Python documentation.

In other words, you cannot count on there being a shared global state between all your requests, but you should make use of there being a shared global state between some of your requests.

If you need anything shared between all requests, you need to use the datastore.

Title: Google App Engine overview


答:
A few practices that proved useful for me.

Limit yourself to local and instance variables. (BTW immutable objects have lots of upsides, so you may not even need instance variables.)

Do not use global and class-level variables, except as constants.

For global state use a proper database. Datastore and Cloud SQL work ok.

Use memcache as much as possible. Cache everything you use often. Memcache is cheap and fast. Always checking the cached value first, then retrieving from DB if cache is stale is a bit daunting; factor it out.

Datastore has good throughput, but significant write latency and throttling, and writes are relatively expensive. Be mindful of this, else you'll run out of your free quota too fast.

Datastore is NoSQL; write large chunks of data in one operation if possible.

Datastore does not like very fast updates of the same value (e.g. having a fast-moving counter). Spread the writes if needed.

Use queues for asynchronous processes. Generally using threads is not a great idea.

If you happen to know Erlang (or maybe Play framework for Java/Scala), try to think like you're using these, in terms of messages and queues, not variables. Then GAE suddenly starts to look simple and logical :)

Title: Google App Engine overview

Body:
I have gone through many Google App Engine tutorials, and I became quite familiar with how to do basic stuff like implementing a webapp2.RequestHandler, and using ndb.Models to manage your data.

Now, I kind of reached a wall with a few small concepts that were either missing from the resources I went over, or I simply missed them. So, here they are:

What happens to class variables?

As far as I understood, once I set my app to threadsafe, it can handle multiple requests concurrently, not to mention possibly on different machines. Does that mean I simply cannot use class variables (that can be changed at anytime)?

How to model an application wide logic?

It is very straight forward to write logic associated with requests. I don't have to worry about locking or any of that stuff, since a new RequestHandler is instantiated for each request. What about application-wide logic? Like, if I had a python module called "Game", and after importing it, I do somthing like:

Game.matchmaking_queue.append(player)

As far as I can tell, there is just one Game instance, and it has an instance variable accessed from within the RequestHandler logic. Will that be OK? Must I make the matchmaking_queue backed on memcache and/or datastore in order for all requests to see it? Do I have to do any thread-saftey magic on Game?


问:
When is it okay to reassign the model for a view in MVC?
Is it ever really acceptable to reassign the model for a view in MVC? (Or MV* where applicable.) In other words, for a single view instance, is it ever ok to reassign the view's model? That is, as opposed to using setters (mutators) on the model so that it does not have to be reassigned. Under what conditions (if any) is this acceptable MVC design?

Here is an example in JavaScript, but the question is language-agnostic.

```<code>var Model = function (m) {
    var message = m;
    return {
        getMessage: function () {
            return message;
        },

        setMessage: function (m) {
            message = m;
        }
    };
};

var View = function (m) {
    var model = m;
    return {
        render: function () {
            alert(model.getMessage());
        },

        setModel: function (m) {
            model = m; // hmm, is this okay?
        }
    };
};

var model1 = new Model('hello world');
var view = new View(model1);
var model2 = new Model('hi there');
view.render();
view.setModel(model2); // reassign model
view.render();
model2.setMessage('hi again'); // mutate model via setter
view.render();
</code>```

In the line view.setModel(model2);, the model is reassigned (the approach in question). In the line model2.setMessage('hi again');, the model is instead mutated via its own setter, which in my view seems generally preferred.

One of the main drawbacks I can see to model reassignment is that it could complicate attempts to reuse the model elsewhere in the application. In some MVC applications a single shared model could be used to drive multiple views (e.g. list, editor, and display views of the same data), in which case model reassignment would be problematic -- it would at least require the added complexity of communicating the model reassignment to dependent views. Here I think the DRY principle trumps the no-mutators principle. (Open to argument here.) Can an even stronger case be made?

To recap, under what circumstances might model assignment be acceptable, if any? Perhaps in certain languages, under extreme performance constraints...? Is "do not reassign models" a good rule of thumb? A pointer to an authoritative source or real-world situation would be helpful.

答:
Why do you even want to NOT reassign the model? In any case the controller should be the one who knows how to fit everything together - load a new instance from the backend, assign it to the view, tell the view to re-render (if not implicit), get the changes from the view and communicate them to the backend to persist them.

There are even developers out there who want to avoid mutators on domain objects at all, because it is much easier to handle unmodifiable instances in concurrent systems. Some even do that when changing properties via a GUI - when the user changes a value a new instance is created based on the previous one with the modified value. That is a bit extreme IMO, however they have a point.

According your example:
in the last lines you modify model2 by using a getter. But what does it mean? For me this makes only sense based on user-input because you modify a specific property of a specific instance probably identifiable by a unique id.
If you want to simply refresh the data from the backend, using setters makes no sense to me, because you would have the effort to check whether you are updating the correct oject, do error handling (what if current instance is not the one you want to load?), etc. By replacing the whole instance, you know there is only that one instance used - clean approach, easy to understand.


答: The human brain does neither think in lists or lambda calculus nor in mathematical formulas. Therefore neither LISP nor FORTRAN can be called human like. Artificial neural networks try to mimic the way biological brains work. In this sense they could be called to be more human like. But as delnan points out, a neural network is not a programming language. I don't know any programming language working in a way similar to neural networks. Although languages might exist for the definition of neural networks. But such a language would define a static neural network architecture. The neural network is capable of learning and develops its own dynamic behavior over time.</p>

Title: Why we say Lisp are Human oriented and Fortran are Machine oriented？

Body:
Lisp and Fortran were the trunks of two separate evolutionary trees,
    one rooted in math and one rooted in machine architecture.

I see this in Hackers and Painters: Big Ideas from the Computer Age.

And someone said that Lisp are Human oriented and Fortran are Machine oriented.

Here human oriented means that the way of problem solving is more likely human do.

And machine oriented means that the way of problem solving is more likely machine do.

I think that Lisp and base on S-expression and symbol.
Fortran are base on von Neumann and Variables.

Is it right?


答:
I think first-class functions are the reason people say that and I would argue that we do in fact think in terms of lamdas/first-class funcs.

Question: "What are you going to do with it?"

How do you answer that question/solve that problem without passing a function to your answer method?

I believe the chief reason LISP and LISP-like languages have been popular for solving AI problems is primarily the noun-like verbs.


问:
Unique and primary keys on a database (mysql)
I'm having quite some doubts here... If I have a table related to username/password login how can I assure there won't be any more matches of the same username and password in the same table using sql? For example:

```<code>>username: username
>password: password
</code>```

^this user just signed up. So the following conditions apply:

1º there can't be any more users named "username"

2º most surely there can't be any more users named "username" AND with the same password

so how exactly should I put the keynames in the database? The id is primary, should I put username AND password as unique to form an unique pair and avoid another identical insertion?

答:
Usernames have to be unique, they identify a user. Passwords do not. Passwords have to be kept secret anyway. You can't tell a user "Hey, choose another password; another user is using this one already". If he is a hacker, he will love that!

You should not store the passwords anyway. Instead store their hashes. See Salted Password Hashing - Doing it Right.

If you have two columns that have to be unique, either their combination must be unique or they must be unique independently.

An example of a unique combination would be monthly data indentified by year and month stored in two separate columns. Here it would make sense to use these two columns as primary key (PK). If you already have another PK, create one unique index or unique constraint on these two columns. See also When should I use a unique constraint instead of a unique index?

An example of two independently unique columns would be a username and a nickname. The username is used for logins; the nickname is displayed to other users. Here I would use the username as PK and create a unique index on the nickname.

The PK is the primary means of identifying a record.  The PK is also referenced in foreign key constraints when defining 1 to n or 1 to 1 relationships between tables. It is a good practice not to choose a column whose value can change over time. If users were allowed to change their username, as an example, choose an auto-increment column as PK and create a unique index on the username.


答: Add a unique constraint on the username column. Any password logic should go in the application code, but best to just check that the passwords are strong enough.</p>

Title: Unique and primary keys on a database (mysql)

Body:
I'm having quite some doubts here... If I have a table related to username/password login how can I assure there won't be any more matches of the same username and password in the same table using sql? For example:

```<code>>username: username
>password: password
</code>```

^this user just signed up. So the following conditions apply:

1º there can't be any more users named "username"

2º most surely there can't be any more users named "username" AND with the same password

so how exactly should I put the keynames in the database? The id is primary, should I put username AND password as unique to form an unique pair and avoid another identical insertion?


问:
Why don't compilers support non-English keywords?
When you read C, C#, Java, Python, PHP and many other programming languages all the syntax is written in English.

Simple code like this

```<code>if (X+1 > 4) {
}
while (A == true) {
}
</code>```

Is written in English even if the programmer's native language is something else.

Would it not be more effective to allow the programmer to use their own native language in the source code, like this (my bad Spanish so forgive me if it's wrong)

```<code>si (X+1 > 4) {
}
mientras (A == verdadero) {
}
</code>```

There is no technical reason why a compiler or parser should be stuck with it's syntax hard coded. Any developer who has done internalization knows there are many easy ways to support other spoken languages.

You can run most IDE platforms in different languages. Yet, the programming language the developer is using is stuck in English.

Why have none of the major languages added support for language packs?

答:
The main reason is that all source code should be written in English. This applies as well to variable names, comments, etc.

The reason becomes obvious when you see for the first time a piece of code which is written in a language you don't know. For example:

```<code>// Записать изменения конфигурации.
var имя = this.RefreshMeta().ПолныйПуть;
this.Хостинг.Записать(имя);
</code>```

Suddenly, you can't understand it, so you can't review, modify or unit test it. Additionally, in my example, you can't even work with it because you don't have Russian keyboard. In other words, you can't work with this code any longer.

This might be acceptable for closed source projects done by small companies. With the drawback of forbidding themselves to hire one day a skillful developer abroad who doesn't speak the language the code is written in.

Working in such company where French is preferred for code comments and documentation, I notice several issues with that:

Like said above, hiring is de facto limited to people speaking French.

If the language itself is localized, this means even more hassle compared to a case where only comments or variable names are.

If one day, the code is released as open source, most developers in the world won't be able to work with it.

While we work with .NET Framework and SQL Server which are fully Unicode-compatible, colleagues are often afraid of putting appropriate accents on letters, resulting in barely readable and extremely ugly names such as DELAI_EXPIRE.

For people who don't speak French, DELAI_EXPIRE should be written DÉLAI_EXPIRÉ. Written in its first form, it makes it difficult to understand, and can have two meanings: either it means that a delay is currently expiring, or that the delay is already expired.

If keywords of a language are localized, should accents be included? Should they be removed?

Again related to accents, French keyboards are pretty bad when it comes to writing capital accented letters. You can write the letter À or Ê, but not É, such as in Également. This makes it pretty difficult to use auto-completion within an IDE.

What would happen if one of the keywords of a language begins with a character which is difficult or impossible to type on a keyboard?

A note about IDEs

IDEs are localized because:

They contain a lot of terms, sometimes complicated ones.

By comparison, most languages contain only a few dozens of keywords, which are often words learnt in schools.

They contain text which is intended to be read.

By comparison, keywords are... keywords. For example, the keyword var in C# doesn't have any meaning in English. It's an abbreviation from variable, but still not an English word. Knowing that var is an abbreviation from variable won't help me understanding the concept of implicitly typed variables. It could have been implicit or imptype or unknown.

The usage of a language in an IDE by a colleague doesn't affect other developers. One can have Eclipse in Italian, while his colleagues are happily working in Portuguese.

By comparison, using a specific language in source code means everybody should understand it, because version control won't magically translate comments or keywords written in Russian by a Russian developer to Japanese for his colleagues in Japan.

So why English (5.52% of world's population being native speakers), and not, for example, Mandarin, (14.1% of world's population being native speakers), or Spanish (5.85% of world's population being native speakers)?

Because of historical reasons, English is used internationally and learnt in schools in most countries. It's even more predominant on the web, and even more among programmers. One can either stick with that, and use English for communication with pairs, or try to change the world so that Spanish, Romanian or Kurdish become the next language every programmer agrees to use.

Body:
The main reason is that all source code should be written in English. This applies as well to variable names, comments, etc.

The reason becomes obvious when you see for the first time a piece of code which is written in a language you don't know. For example:

// Записать изменения конфигурации.
var имя = this.RefreshMeta().ПолныйПуть;
this.Хостинг.Записать(имя);

Suddenly, you can't understand it, so you can't review, modify or unit test it. Additionally, in my example, you can't even work with it because you don't have Russian keyboard. In other words, you can't work with this code any longer.

This might be acceptable for closed source projects done by small companies. With the drawback of forbidding themselves to hire one day a skillful developer abroad who doesn't speak the language the code is written in.

Working in such company where French is preferred for code comments and documentation, I notice several issues with that:

Like said above, hiring is de facto limited to people speaking French.

If the language itself is localized, this means even more hassle compared to a case where only comments or variable names are.

If one day, the code is released as open source, most developers in the world won't be able to work with it.

While we work with .NET Framework and SQL Server which are fully Unicode-compatible, colleagues are often afraid of putting appropriate accents on letters, resulting in barely readable and extremely ugly names such as DELAI_EXPIRE.

For people who don't speak French, DELAI_EXPIRE should be written DÉLAI_EXPIRÉ. Written in its first form, it makes it difficult to understand, and can have two meanings: either it means that a delay is currently expiring, or that the delay is already expired.

If keywords of a language are localized, should accents be included? Should they be removed?

Again related to accents, French keyboards are pretty bad when it comes to writing capital accented letters. You can write the letter À or Ê, but not É, such as in Également. This makes it pretty difficult to use auto-completion within an IDE.

What would happen if one of the keywords of a language begins with a character which is difficult or impossible to type on a keyboard?

A note about IDEs

IDEs are localized because:

They contain a lot of terms, sometimes complicated ones.

By comparison, most languages contain only a few dozens of keywords, which are often words learnt in schools.

They contain text which is intended to be read.

By comparison, keywords are... keywords. For example, the keyword var in C# doesn't have any meaning in English. It's an abbreviation from variable, but still not an English word. Knowing that var is an abbreviation from variable won't help me understanding the concept of implicitly typed variables. It could have been implicit or imptype or unknown.

The usage of a language in an IDE by a colleague doesn't affect other developers. One can have Eclipse in Italian, while his colleagues are happily working in Portuguese.

By comparison, using a specific language in source code means everybody should understand it, because version control won't magically translate comments or keywords written in Russian by a Russian developer to Japanese for his colleagues in Japan.

So why English (5.52% of world's population being native speakers), and not, for example, Mandarin, (14.1% of world's population being native speakers), or Spanish (5.85% of world's population being native speakers)?

Because of historical reasons, English is used internationally and learnt in schools in most countries. It's even more predominant on the web, and even more among programmers. One can either stick with that, and use English for communication with pairs, or try to change the world so that Spanish, Romanian or Kurdish become the next language every programmer agrees to use.


答:
Too much effort for too little added value.

The amount of English required to make sense of the keywords of any programming language is really very small - for the majority of second-language speakers it is probably way less than they already knew of the language even before they became programmers. Conversely, allowing all keywords to be replaced by their translations in other languages (and there are thousands of other languages!) would add to the complexity of the language implementation, would pollute the default namespace with thousands of tokens that are no longer legal identifiers, and would run the risk that whenever you have to review any code, you suddenly have to know what 'if' means in Czech to get it right. Almost all practitioners find these costs too high for the benefit of allowing people to program without rudimentary command of English.

Note that method and field names in standard or contributed libraries are another field. Most vendors stick to English for those as well, for largely the same reasons, but under particular circumstances the trade-off can be worthwhile, so there are some third-party languages with non-English public identifiers, but still a tiny minority.

Note also that this has nothing whatsoever to do with the question of whether English is particularly suited to express programming logic, or whether it is fair that U.S. and British programmers have a head start. The language has gained its present de-facto status as a computer standard largely through contingent historical processes (events that might have turned out otherwise, but in fact didn't). Although many people don't like this, few dislike it so much that they are willing to go back and deliberately re-introduce the possibility of fragmentation just to spite the Americans.

Title: Why don't compilers support non-English keywords?

Body:
When you read C, C#, Java, Python, PHP and many other programming languages all the syntax is written in English.

Simple code like this

```<code>if (X+1 > 4) {
}
while (A == true) {
}
</code>```

Is written in English even if the programmer's native language is something else.

Would it not be more effective to allow the programmer to use their own native language in the source code, like this (my bad Spanish so forgive me if it's wrong)

```<code>si (X+1 > 4) {
}
mientras (A == verdadero) {
}
</code>```

There is no technical reason why a compiler or parser should be stuck with it's syntax hard coded. Any developer who has done internalization knows there are many easy ways to support other spoken languages.

You can run most IDE platforms in different languages. Yet, the programming language the developer is using is stuck in English.

Why have none of the major languages added support for language packs?


问:
How bad can it be to lack teamwork when you are a programmer?
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?

答:
Since you're a good learner, there's one more thing you should learn, that some people already know.

Everyone is different, and they are all valuable.

There are times for being independent, and there are times for pulling together. They are both important.

Since you are in school, you can exercise your curiosity and look for new and different ways to do things. That is a good thing.

When you work with a software team, you can contribute your good ideas. Some will be accepted. Some will not. Then you all "put your shoulder to the wheel" and get the job done. That is also a good thing.

My experience on projects is there's a group morale that is low at first, when people are still trying to get the big picture in focus. Then the morale steadily rises as progress is made toward the goal. Toward the end it is very high as your "baby" comes to be "born". That's something you don't want to miss.

ContentLicense: CC BY-SA 2.5


答:
In layman's words:

They do.

In this wikipedia article you can see there are lots of programming languages/compilers/interpreters based in languages other than english.

Here is a sample source code in Linnotte, a French-based programming language:

```<code> nombre Fibonacci :
  a est un nombre
  début
   questionne a sur "Entrez un nombre :"
   affiche fibo(a)

 fibo :
  * n est un nombre
  début
   si n est < 2, retourne n
   retourne fibo(n-1) + fibo(n-2)
</code>```

.. and a hello world program in SAKO, a polish-based one:

```<code>K) PROGRAM DRUKUJE NAPIS HELLO WORLD
   LINIA
   TEKST:
   HELLO WORLD
   KONIEC
</code>```

The question would be why most languages/compilers/interpreters use english reserved words.

Compilers and languages are more useful the more people in the world have access to it and software projects are one of the disciplines that require efforts from people in difference countries. For historical reasons english has become the predominant communication language in the modern world, so it is only logical most programming languages use english keywords. Should the course of history been different perhaps programming languages would be mostly latin-based, or french-based.

English has some other advantages: it doesn't use accents and marks like áéíúóâêîôûäëïöü etc which makes it the lowest common denominator regarding keyboard layouts.

It's interesting to know that Niklaus Wirth who designed PASCAL among other languages was Swiss, yet he choose english for the reserved words, as mentioned in this MSDN article.

Another curiosity:

While Perl's keywords and function names are generally in English, it
allows modification of its parser to modify the input language, such
as in Damian Conway's Lingua::Romana::Perligata module, which allows
programs to be written in Latin or his Lingua::tlhInganHol::yIghun
Perl language in Klingon. They do not just change the keywords but
also the grammar to match the language.

Body:
In layman's words:

They do.

In this wikipedia article you can see there are lots of programming languages/compilers/interpreters based in languages other than english.

Here is a sample source code in Linnotte, a French-based programming language:

 nombre Fibonacci :
  a est un nombre
  début
   questionne a sur "Entrez un nombre :"
   affiche fibo(a)

 fibo :
  * n est un nombre
  début
   si n est < 2, retourne n
   retourne fibo(n-1) + fibo(n-2)

.. and a hello world program in SAKO, a polish-based one:

K) PROGRAM DRUKUJE NAPIS HELLO WORLD
   LINIA
   TEKST:
   HELLO WORLD
   KONIEC

The question would be why most languages/compilers/interpreters use english reserved words.

Compilers and languages are more useful the more people in the world have access to it and software projects are one of the disciplines that require efforts from people in difference countries. For historical reasons english has become the predominant communication language in the modern world, so it is only logical most programming languages use english keywords. Should the course of history been different perhaps programming languages would be mostly latin-based, or french-based.

English has some other advantages: it doesn't use accents and marks like áéíúóâêîôûäëïöü etc which makes it the lowest common denominator regarding keyboard layouts.

It's interesting to know that Niklaus Wirth who designed PASCAL among other languages was Swiss, yet he choose english for the reserved words, as mentioned in this MSDN article.

Another curiosity:

While Perl's keywords and function names are generally in English, it
allows modification of its parser to modify the input language, such
as in Damian Conway's Lingua::Romana::Perligata module, which allows
programs to be written in Latin or his Lingua::tlhInganHol::yIghun
Perl language in Klingon. They do not just change the keywords but
also the grammar to match the language.


答:
It's an error to state that "[in] programming languages all the syntax is written in English" or "Simple code (...) is written in English". Programming languages and natural languages are different things. Programming language tend to borrow some words from mostly English (the most prominent exception is probably null from German), in the same way English language borrows word "program" from French.

Other than a few words, virtually nothing from English is borrowed by programming language - syntax, tenses, conjugation, declension etc.

One may ask why English is the language tha programming languages borrow their vocabulary from. Answer is rather geopolitical than technical in nature.

Having said that, I know several people that do not speak English that are proficint coding in several programming languages.


问:
Where to store the private key?
Say I want some parts of my software to be encrypted. For example, the credentials for a database, etc. I need to store those values somewhere, but doing so in cleartext would make it easy for an attacker to gain unauthorised access.

However, if I encrypt some cleartext, then where do I store the key? Anything that software has access to, a determined attacker would have access to, no matter what level of obfuscation:

Say the key is protected by the filesystem's security model; but what about (malicious) superusers, or platforms that don't provide such fidelity?

Or the key is hardcoded into software binaries, but it could always be decompiled and what about open source software or interpreted code?

If the key is generated, such an algorithm would need to be deterministic (presumably) and then the same problem applies to the seed.

etc.

Cryptography is only as strong as the weakest link in its chain and this seems like a pretty loose one! Presuming it's the right tool for the job (humour me), then how can one secure such information robustly?

Regarding the right tool for the job: Probably, in -- for example -- the case of service access (DBs, authentication servers, etc.), you would restrict access at this tier with a service account, maybe with some service-level auditing, etc. and so having the credentials in cleartext isn't such a worry.

To me, however, that still seems inadequate: I don't want anyone poking around where they shouldn't be!

答:
First of all, I would not refer to myself as a security expert, but I have been in the position of having to answer this question.  What I found out surprised me a bit: There is no such thing as a completely secure system.  Well, I guess a completely secure system would be one where the servers are all turned off :)

Someone working with me at the time described designing a secure system in terms of raising the bar to intruders.  So, each layer of securing decreases the opportunity for an attack.

For example, even if you could perfectly secure the private key, the system is not completely secure.  But, correctly using the security algorithms and being up to date with patches raises the bar.  But, yes, a super computer powerful enough and given enough time can break encryption.  I'm sure all of this is understood, so I'll get back the question.

The question is clear so I'll first try to address each of your points:

Say the key is protected by the filesystem's security model; but what
  about (malicious) superusers, or platforms that don't provide such
  fidelity?

Yes, if you use something like Windows Key Store or a password encrypted TLS private key you are exposed to the users that have the password (or access) to the private keys.  But, I think you will agree that raises the bar.  The file system ACLs (if implemented properly) provide a pretty good level of protection.  And you are in the position to personally vet and know your super users.

Or the key is hardcoded into software binaries, but it could always be
  decompiled and what about open source software or interpreted code?

Yes, I've seen hardcoded keys in binaries.  Again, this does raise the bar a bit.  Someone attacking this system (if it is Java) has to understand that Java produces byte code (etc) and must understand how to decompile it are read it.  If you are using a language that writes directly to machine code, you can see that this raises the bar a bit higher.  It is not an ideal security solution, but could provide some level of protection.

If the key is generated, such an algorithm would need to be
  deterministic (presumably) and then the same problem applies to the
  seed.

Yes, essentially then the algorithm becomes the private key information for creating the private key.  So, it would need to now be protected.

So, I think you have identified a core issue with any security policy, key management.  Having a key management policy in place is central to providing a secure system.  And, it is a pretty broad topic.

So, the question is, how secure does your system (and, therefore the private key) need to be? How high, in your system, does the bar need to be raised?

Now, if you willing to pay, there are some people out there that produce solutions to this.  We ended up using an HSM (Hardware Security Module).  It is basically a tamper-proof server that contains a key in hardware.  This key can then be used to create other keys used for encryption.  The idea here is that (if configured correctly), the key never leaves the HSM.  HSMs cost a lot.  But in some businesses (protecting credit card data lets say), the cost of a breach is much higher.  So, there is a balance.

Many HSMs use key cards from maintenance and admin of the features.  A quorum of key cards (5 of 9 lets say) have to be physically put into the server in order to change a key.  So, this raises the bar pretty high by only allowing a breach if a quorum of super users collude.

There may be software solutions out there that provide similar features to an HSM but I'm not aware of what they are.

I know this only goes some way to answering the question, but I hope this helps.

Title: Where to store the private key?


答:
In my mind, the only way to keep this completely safe is to have the key/password encrypted with a passphrase to unlock. This way the passphrase must be given for each start or use of the secret.. Not too useful.

Another way might be to have the security system be the database account it self. Not very scalable...

If each user on a system has its own DB account, and those accounts was premade so that the application does not have rights to create accounts in DB on behalf of a user you could come pretty close though. Not a good solution either, so I guess you have to have very restricted read-access on the config-files and trust your super-users.

Title: Where to store the private key?

Body:
Say I want some parts of my software to be encrypted. For example, the credentials for a database, etc. I need to store those values somewhere, but doing so in cleartext would make it easy for an attacker to gain unauthorised access.

However, if I encrypt some cleartext, then where do I store the key? Anything that software has access to, a determined attacker would have access to, no matter what level of obfuscation:

Say the key is protected by the filesystem's security model; but what about (malicious) superusers, or platforms that don't provide such fidelity?

Or the key is hardcoded into software binaries, but it could always be decompiled and what about open source software or interpreted code?

If the key is generated, such an algorithm would need to be deterministic (presumably) and then the same problem applies to the seed.

etc.

Cryptography is only as strong as the weakest link in its chain and this seems like a pretty loose one! Presuming it's the right tool for the job (humour me), then how can one secure such information robustly?

Regarding the right tool for the job: Probably, in -- for example -- the case of service access (DBs, authentication servers, etc.), you would restrict access at this tier with a service account, maybe with some service-level auditing, etc. and so having the credentials in cleartext isn't such a worry.

To me, however, that still seems inadequate: I don't want anyone poking around where they shouldn't be!


问:
Decorator Pattern in Head First Design Patterns
I'm trying to teach myself some design patterns using a book that I was recommended, Head First Design Patterns. I came to the chapter on the Decorator Pattern, and although I understand the purpose of it, I'm a bit fuzzy on it's layout.

Here is their basic UML of the Decorator pattern:
Imgur
(Sorry for the link, but SE won't let me upload a photo here for some reason)

Here is how they wrote out the code:

```<code>public abstract class Component {
    String description = "Unknown Description";

    public String getDescription() {
        return description;
    }

    public abstract double cost();
}

public class ConcreteComponent extends Component {
    public ConcreteComponent() {
        description = "I am a concrete component";
    }

    public double cost() {
        return 1.99;
    }
}

public abstract class Decorator extends Component {
    public abstract String getDescription();
}

public class ConcreteDecorator extends Decorator {
    Component component;

    public ConcreteDecorator(Component component) {
        this.component = component;
    }

    public String getDescription() {
        return component.getDescription() + " with a decorator";
    }

    public double cost() {
        return .20 + component.cost();
    }
}
</code>```

My question is, what is the need for a Decorator class in this situation? Why not leave getDescription() abstract and let ConcreteComponents and ConcreteDecorators implement it the way they need?

As a follow up, are there actual benefits to creating a Decorator class? This example doesn't seem to cover why it's useful or how it could be useful.

答:
With a Decorator you are able to augment the code you are wrapping without changing it at all.  And in some cases, not even having to know what it does.

The Open/Closed Principle states that

software entities (classes, modules, functions, etc.) should be open
  for extension, but closed for modification

So, if you just made it abstract, what would happen if you had to then modify the description in your concrete implementation?  You would have to modify your class.

Yes, this particular example is a little contrived. But, with this pattern, you can add decorators that augment a message (like in the design of Streams), or provide aspects that are orthogonal to the process (like logging or tracing) without touching or changing the code that the Decorator is wrapping.

Also, because a Decorator is a Component you can add a second Decorator without having to know that it wrapping a Decorator.  In other words, this helps keep the Decorators separate from each other.  This leads to code that is both decoupled and cohesive.


问:
Company name already taken at github
My research-based company's name is already taken on github (mailed the owner without any luck), what is the most recognized naming conventions for company github accounts besides the name directly?

the only ones I found was ibm-dojo and ibm-research

答:
Usually, each company has their own naming convention (if any) for projects like that.  For example, IBM has policies in place regarding social media interaction as well as open-source project contributions.

Generally, it's poor form to take the main company name within a repository like GitHub.  In larger organizations, it would be a CLM (career limiting move) for a non-senior employee to take the main name and not be easily accessible.  At IBM, anyone less than a VP claiming the parent name would likely have a short conversation with Legal wherein the relinquish the account credentials.

Assuming the parent company wants its name on the project, then parentCo-subproject is a pretty common naming approach.  Even if the company isn't large enough to sponsor all that many projects, it doesn't hurt to use that pattern anyway.  Projects will come and go, and that makes life easier on future projects (as you're now finding).

Unfortunately, that's not a universal rule and not everyone thinks things through before registering their company on an OSS site.

The above answer pertains mostly to larger companies where the risk of company name collision with other companies is low, but there's a decent risk of project name collision.

Smaller firms may find there is another organization with their name, and it's unlikely that they'll be able to find some sort of arbitration regarding the name's usage (or they might lose in that arbitration).  There are a number of different collision reasons, but all of them generally end up in the 2nd party losing out on the primary name.

At that point, what I have seen is the organization adding some degree of localization to distinguish themselves.  That could be a simple -US or -CA to indicate country, or a .net to show they are foo.net and not foo.com, or they could use the full URL of their main site.

That said, I still think that companyName-project forms a good pattern for the OSS registry.  It creates a subtle shift in the branding of the account as the company is now relying more upon the project brand in order to distinguish that OSS project.

Title: Company name already taken at github


问:
What is the difference between UML Data profile and ER model?
I have been asked this question and even after a lot of research, I cannot find the answer.

When I design a database using Entity relationship (ER) and then re-draw it as UML class model (extended with Data modeling profile for UML), what are the differences and how both models can be (in their way) useful for db developer? With regard to multiplicity, foreign keys..

答:
The level of abstraction provided by Entity Relationship Diagrams created with modeling tools, the entity model provided by EF, and UML class diagrams is almost the same. When I create my POCO entities I generally put them in my Model project with my other domain classes, and so a class diagram of the domain model contains the same POCO entities found in the ERD.

While both models provide for relationships, UML can be more descriptive in its relationships which often reflect some sort of action, behavior, or complex relationships such as interface implementation or inheritance. ERD relationships, on the other hand, are all about keys and multiplicity.

I feel that the model designer provided by the Entity Framework meets my needs for modeling entities. I use a modeler to produce an ERD during the design phase, but I like the entity model to speak for itself after that.

As for UML, I find it very useful for communication and documentation of how software processes behave and interact with one another. These diagrams can be found in the system documentation in the form of use cases, activity diagrams, class diagrams, and sequence diagrams.

Hope this helps.


问:
Nested Classes or Namespace
Why do need namespaces when we have nested classes. What can be done through namespaces, can also achieved through nested classes.

so I don't understand the reasoning of having namespaces ?

答:
In C#, they are very similar.

```<code>namespace my_group {}

static class my_group {} // namespace
</code>```

Namespaces support the using keyword and the same namespace can span multiple files, however I think they cannot be defined inside a static class.

Title: Nested Classes or Namespace

Body:
In C#, they are very similar.

namespace my_group {}

static class my_group {} // namespace

Namespaces support the using keyword and the same namespace can span multiple files, however I think they cannot be defined inside a static class.


答: Well, one advantage is that you may have dozens of classes in a namespace. Have you considered what that would look like with nested classes? I mean, you can do some things with partial classes in C#, but the general case is pretty ugly. I think namespaces are there to group functionality and scope it, whereas inner classes exist to encapsulate multiple tightly-coupled pieces of functionality into one indivisible bundle.</p>

Title: Nested Classes or Namespace

Body:
Why do need namespaces when we have nested classes. What can be done through namespaces, can also achieved through nested classes.

so I don't understand the reasoning of having namespaces ?


答:
Well, currently the main difference is a namespace is designed to be augmented in separate files.  If you try to add a new nested class to a class, you get:

```<code>test1.cpp:3:7: error: redefinition of ‘class NamespaceClass’
</code>```

However, it only works that way because it was defined that way.  It wouldn't be that difficult to rework the compiler to append to a class in certain ways when it sees what is now a redefinition.

The reason they don't is that a namespace and a class are conceptually two different things, used for different reasons.  A class is meant to be instantiated, and is used to create strong cohesion between a data structure and its associated methods.  A namespace is meant to loosely gather modules to make it easier to share groups of several files without causing naming clashes.

Yes, you can approximate the behavior of one using the other, but that doesn't make them the same.  If you used a redefinition-allowed class instead of namespaces, you would have problems like:

Having to look through all header files using that class to get its entire definition, including determining if it's instantiable or not.

Wanting to use a name that denotes its purpose as a namespace, like StdNamespace instead of just std.

Needing some sort of syntax to clue you in when you do accidentally redefine a class when the compiler just thinks you mean to augment it like a namespace.

When you add up all the special cases you would need to handle to make it truly follow the open-closed principle, you may as well just call it a namespace.

Title: Nested Classes or Namespace

Body:
Well, currently the main difference is a namespace is designed to be augmented in separate files.  If you try to add a new nested class to a class, you get:

test1.cpp:3:7: error: redefinition of ‘class NamespaceClass’

However, it only works that way because it was defined that way.  It wouldn't be that difficult to rework the compiler to append to a class in certain ways when it sees what is now a redefinition.

The reason they don't is that a namespace and a class are conceptually two different things, used for different reasons.  A class is meant to be instantiated, and is used to create strong cohesion between a data structure and its associated methods.  A namespace is meant to loosely gather modules to make it easier to share groups of several files without causing naming clashes.

Yes, you can approximate the behavior of one using the other, but that doesn't make them the same.  If you used a redefinition-allowed class instead of namespaces, you would have problems like:

Having to look through all header files using that class to get its entire definition, including determining if it's instantiable or not.

Wanting to use a name that denotes its purpose as a namespace, like StdNamespace instead of just std.

Needing some sort of syntax to clue you in when you do accidentally redefine a class when the compiler just thinks you mean to augment it like a namespace.

When you add up all the special cases you would need to handle to make it truly follow the open-closed principle, you may as well just call it a namespace.


问:
Which methods should be put in an interface and which in abstract classes?
I have seen many frameworks and modules and their standard they follow is like this

UserInterface which have some predefined methods

AbstractUserClass which implements userInterface

Then GenericUserClass which extends from AbstractuserClass

Then other classes extending from that generic

Now I have seen that abstract class has additional functions to the interface, and the generic class also has additional functions.

So I am confused which methods should go where

Sometimes I see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass implements UseraInterface. What is the difference if Abstractclass already impelements Userinterface

答:
A rule of thumb is that:

Interfaces define the public API (contract) or a certain functionality if you will,

Abstract classes (may) provide a private API (for extended classes to use), such as shared functionality.

So i am confused which methods should go where

If a method should be part of the public API, add it to the interface and update dependencies where necessary (i.e. Abstract and / or Generic class).

Otherwise, implement the method as high up as is needed based on how generic or specific it is.

Sometimes i see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass implements useraInterface. what is the difference if Abstractclass already implements Userinterface

There's no difference in that case; you don't have to specify an interface twice if the ancestor already implements it, because the interpreter will throw an error if you try to break the contract.

This would only make sense if the child class implements another interface altogether. And this is a strength of interfaces; since you're defining a piece of functionality rather than a specific implementation, you can make any class implement any interface if you wanted to. This is a great help when writing mock classes for testing.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
In C# I would like to use simple switch () { ... }, but extendible with such expressions:

```<code>switch (value)
{
  // string-based operators:
  case begins "Maria": // to catch Maria Carey
    break;
  case ends "Washington": // to catch George Washington
    break;
  case like "ph": // to catch Phil, Phillip, Sophie
    break;
  case between "Aaron" and "April": // to catch all names between
    break;

  // use non-static variables in case expression:
  case Dao.GetDefaultBabyName():
    break;

  // continuable cases without breaking
  case "John":
    bonus = 25;
  case "Peter":
    salary = 500;
    break;

  // jumps between cases
  case "Aleron":
    // do something
    break;
  case "Bella":
    // do something
    jump "Aleron";
    break;

}
</code>```

And so on. The same with numbers or other types (that supports IComparable, IConvertible, ...)

This might make my code more laconic and readable.

Body:
In C# I would like to use simple switch () { ... }, but extendible with such expressions:

switch (value)
{
  // string-based operators:
  case begins "Maria": // to catch Maria Carey
    break;
  case ends "Washington": // to catch George Washington
    break;
  case like "ph": // to catch Phil, Phillip, Sophie
    break;
  case between "Aaron" and "April": // to catch all names between
    break;

  // use non-static variables in case expression:
  case Dao.GetDefaultBabyName():
    break;

  // continuable cases without breaking
  case "John":
    bonus = 25;
  case "Peter":
    salary = 500;
    break;

  // jumps between cases
  case "Aleron":
    // do something
    break;
  case "Bella":
    // do something
    jump "Aleron";
    break;

}

And so on. The same with numbers or other types (that supports IComparable, IConvertible, ...)

This might make my code more laconic and readable.


问:
Why do some projects have getters and setters for public instance variables?
I was looking into an open-source game framework project written in Java. It has several classes that:

Have public instance variables.

Have getter/setters for such variables.

Generally, I write getters/setters when I want to encapsulate some behavior that occurs when a property is modified.

However, looking at the code, it literally goes something like this:

```<code>public class Test {
    public int value;
    public void setValue(x) {
        value = x;
    }
    public void getValue() {
        return value;
    }
}
</code>```

Then I thought about checking out the rest of the framework and see how do they modify such value, which may give me a hint on why did they do the above.

From what I've seen, they do it like this:

```<code>object.value = 100;
</code>```

Without using the getters/setters.

So now I'm not sure what was the point of creating getters/setters.

So, my question is, is there a reason I would want to create getters/setters for a public value, if such getters/setters don't even implement any kind of special behaviour?

答: It sounds like the authors of the class were confused or changed their minds half-way through writing it. In most cases, public attributes are a 'bad thing', and public accessors are the way to go: they allow the class to change the implementation and even reject the operation. In short, to protect its own internal state.</p>


问:
Is my understanding of abstract datatypes correct?
After reading lots of pages on various sites, I came to the conclusion that abstract datatype helps to separate the use of datastructure from its implementation. We can easily map the data into a datastructure by using an already available abstraction. And this abstraction is called ADT. Please tell me if I have understood this correctly. Also if you can give a small example, it will be very helpful. If you prefer to give any code in your example, C or Python would be helpful for me.

Addition: They are a very special implementation of data abstraction. What separates them from other instances of abstractions is that ADTs are theoretical constructs. Theoretical constructs that help map or represent data in a desired data structure. They have attributes or operations associated with them. These operations may be applied on the data that has been mapped into the ADT. How the data is actually stored inside the ADT or how the operations work are kept hidden.

EDIT: I had previously said, "ADT is like the blueprint of a datastructure". A few of the answers have explained why it's not. I didn't have a clear comprehension of what a 'blueprint' is and that was the reason for using the term. So, I've now removed it from my original text.

答:
I'll disagree with everyone else and say that you don't have it quite right. :-)

It is like the blueprint of the datastructure.

No, it's actually the opposite of that: it's a photograph from the outside of a device or a building showing the doors and knobs with instructions on what to expect when you use them.

Secondly, ADT's are a lingua franca: a common language for discussing one kind of frequently used software component.

IMO the best lesson on ADT's and their potential implementations is the Javadocs for the container classes. Look at the interfaces and abstract classes. These are the ADT's. For example, the Queue.


问:
Why is the copying instruction usually named MOV?
In quite many assemblers, a value copying instruction is usually named "MOV" and its description in manuals usually also contains "move" (however, other words can be used, like "load", "store", "extract", etc.) It's uncommon to find an ISA ) which doesn't follow this convention.

On the other hand, in other contexts, "move" differs from "copy" in sense that source is destroyed (for example, "mv" vs. "cp" in Unix, Move[F6] in Norton Commander and clones, etc.) Assembler's "move" really has semantic "copy", keeping the source value intact.

I've found that this has started at least since IBM 1401 (1959), but, IBM 360 used this word only for in-storage copying, but not for operations between registers and storage (which used "load" and "store"). But why it's still widely used and not replaced with "copy" or "store"?

答:
You are certainly right.  Most if not all instances of a mov instruction are actually a copy.

Some dont actually even have a mov it is a pseudo instruction for

```<code>add dest=source+zero.
</code>```

Also understand that the ascii syntax is arbitrary, the machine code means something and is defined and fixed for that processor.  Most if not all of the time the processor creator/vendor creates a syntax in part to define the instruction set (machine code) and in part to define a syntax that works with a tool they also created or commissioned to convert that assembly language into machine code for their processor.  You can certainly for example go into the gnu assembler (which has a tendency to do its own thing and not follow the processor vendors syntax anyway) and add a copy pseudo instruction.

Use cases: well these days most assembly language code is compiler generated, and the mov instruction is most often used to actually move a value from one register to another so that the source register (memory location, etc) can be re-used.  For reasons of the calling convention for that processor or because some instructions or instruction sets are not orthogonal, so you have to move things around.  Certainly there are times where a copy of a value is desired and the mov may be used to make that copy.

I doubt seriously we will ever know what individual or team came up with the term first and why they chose move over copy.  Because we have become accustomed to it we tend to re-use it with every new instruction set.  As already mentioned some instruction sets use register based load and store instructions where one operand is a register and the other is an address, and mov for just the register to register case(s).  And other instruction sets use mov for register or mem for either operand.  Although you can certainly add copy to any/many of the open source assemblers, getting traction on its use will be more difficult.  If you work somewhere where you have control over the original syntax (work for a place making a new processor) where you can dictate the register to register move is called copy, you are likely to end up with the gnu assembler for example including a mov since there is so much of a comfort level with it someone will add it (and gas often goes against the processor vendors syntax and does its own thing).

Body:
You are certainly right.  Most if not all instances of a mov instruction are actually a copy.

Some dont actually even have a mov it is a pseudo instruction for

add dest=source+zero.

Also understand that the ascii syntax is arbitrary, the machine code means something and is defined and fixed for that processor.  Most if not all of the time the processor creator/vendor creates a syntax in part to define the instruction set (machine code) and in part to define a syntax that works with a tool they also created or commissioned to convert that assembly language into machine code for their processor.  You can certainly for example go into the gnu assembler (which has a tendency to do its own thing and not follow the processor vendors syntax anyway) and add a copy pseudo instruction.

Use cases: well these days most assembly language code is compiler generated, and the mov instruction is most often used to actually move a value from one register to another so that the source register (memory location, etc) can be re-used.  For reasons of the calling convention for that processor or because some instructions or instruction sets are not orthogonal, so you have to move things around.  Certainly there are times where a copy of a value is desired and the mov may be used to make that copy.

I doubt seriously we will ever know what individual or team came up with the term first and why they chose move over copy.  Because we have become accustomed to it we tend to re-use it with every new instruction set.  As already mentioned some instruction sets use register based load and store instructions where one operand is a register and the other is an address, and mov for just the register to register case(s).  And other instruction sets use mov for register or mem for either operand.  Although you can certainly add copy to any/many of the open source assemblers, getting traction on its use will be more difficult.  If you work somewhere where you have control over the original syntax (work for a place making a new processor) where you can dictate the register to register move is called copy, you are likely to end up with the gnu assembler for example including a mov since there is so much of a comfort level with it someone will add it (and gas often goes against the processor vendors syntax and does its own thing).


问:
When to use non-embedded databases over embedded databases
We are trying to start a web base project that need to develop based on MS technologies such as C#,.net, IIS etc. This is a web application suppose to sell as a product with a single installer.

Now we are discussing which kid of database we are going to use.
Some says non-embedded database (Ms Sql) Some of them idea is to use   embedded databases.
So we are in a bit of confusion stage for a batter decision.

Can you guys give some feedback according to your experience. then that will help us to come up with a good decision.

In simply what is need is When to use non-embedded over embedded databases?

Edit : Anyway We have technical understanding about how to use Non-embedded database such as MS Sql Server or Embedded database. What I need is, Conceptually in which situations usually we prefers each type of databases and what are the pros and cons of using each types.

答:
If you're hosting the product on your server, then you might create a database for each subscriber, and a master database with a table of subscribers.  This isn't 'embedded', but the databases (file systems) are separate.

If you're creating a package that will be distributed, such that you are creating web-enabled applications that run on user's servers, then you have to determine whether the users would reasonably expect to have a DBA as an employee or contractor.  If they would, you would want them to install the database first, according to their server configuration.  If they already have SQL Server used in other applications, they will merge this one with their others, if appropriate.

If you're creating a package that users will run on their own servers, but they wouldn't reasonably have a DBA, then you want to embed the database.  In this case the user is only dimly aware that a database is part of the installation - it occurs automatically and your installer program is responsible for setting it up.  This means your app will need to include some administrator tools for database backup, database repair, index rebuilds, etc.

If you distribute a product with an embedded database, be prepared to offer expanded support.  Invariably people will get into trouble, and they'll need a responsive support resource, and are usually willing to pay for it once it's determined that the problems are something you couldn't have anticipated.


答:
On top of Karl's answer, I think there is also major semantic difference.

With namespaces, you group together related classes. This is usually goal to keep cohesion high. With nested class, the new class is primarily related to the containing class, but can be unrelated to the "sibling" nested classes.

This on top of fact that classes are meant to be instantiated but namespaces included makes them two different concepts.

Title: Nested Classes or Namespace


问:
What is the difference between requirements and specifications?
I've been tasked with developing requirements and specifications for a project our group is starting.

I realized that I don't know the difference; a Google search just confused me more -- it seems some people say that specifications are requirements, but at a lower level.

答:
A specification is a requirement that passed feasibility and is ready to be implemented.
It is a requirement that has evolved to the design phase.

In other words:

A requirement is behavior (or non-behavior) "as planned" or "as
wished"

A specification is behavior (or non-behavior) "to be built" or "as built"

Example:

requirement:    1. user presses OK button 2. system prints invoice

specification:   1. user presses OK button 2. system prints invoice

As you can see, the content of both can be the same. The difference is that requirement is an analysis artifact. The specification is a design artifact.

In a final as-built documentation, you will typically find the word "specification", instead of "requirement", since the requirements have been converted to specifications.

Remark:  example above contains design elements, because of design constraint.


答: I think the better implementation is to have the usernames to be unique, but the passwords may have duplications. It's also the common practice in most web-apps. You can set the username as the primary key in your table</p>