问:
.NET software design and Oracle ODP.NET UDT
I'm working on a new common .NET software design (mainly) for WCF-based web service applications with related client frontends (all written in C#). As far I've chosen some frameworks (NUnit,Autofac/Castle Windsor) as basis for the application.

Now I'm doing some research concerning db abstraction. I'm considering NHibernate (together with FluentNHibernate) as persistence framework. But there are some concerns about NHibernate.

Database interfaces provided by our db dev team heavily rely on stored procedures and often use UDT objects as output parameters (sometimes also ref cursors). Many already existing applications are using auto-generated UDT C# classes.

NHibernate seems to work well with Oracle (with appropriate configuration and usage of ODP.NET).
See Fluent NHibernate - how to configure for oracle?, Fluent NHibernate - Configure Oracle Data Provider ODP. Also ref cursors and stored procedure calls seem to work with nhibernate (see Calling an Oracle store procedure with nHibernate and Oracle stored procedures, SYS_REFCURSOR and NHibernate).

Is it appropriate to use NHibernate in this case (stored procedures and UDT/ref cursor output)? Or would it be better to keep auto-generated UDT C# classes and implement custom data access objects?

Design A (with auto-generated UDT classes):

Create business objects in the domain model (e.g. class Product)

Define database-independent interfaces e.g. IDataAccessProduct.

Implement it in classes e.g. OracleDataAccessProduct that represent specific data
access objects. For example this class calls performs a mapping of
auto-generated UDT classes (entities) to Product domain objects and
vice versa.

Design B (with NHibernate):

Create business objects in the domain model (e.g. entity class Product : IEntity<Product>.)

Add interface an IProductRepository for the repository. In the domain model. Add ProductRepository that extends the e.g. base class Rhino.Commons.NHRepository.

Usage of hibernate-mapping for domain objects to db table (Product.hbm.xml).

So which design would you prefer?

答: nHibernate, Entity Framework and other ORM (Object Relational Mapping) tools are wonderful to represent abstractions of the database objects (Tables/Views), relationships and keys through true business objects in the data layer of an application. The motive around the ORM tools are to make the data layer robust and to support Rapid Application Development (RAD) through different design time support in Visual Studio to map and represent database objects and relationships in the data layer. ODP .Net UDT to some extent support all these philosophies. However, if you would like to truley provide complete object relational abstraction in data layer, either nHibernate or Entity Framework should be used.</p>

OwnerDisplayName: Marco Mayer


问:
Is it possible to avoid SQL injection by not using a Query Language for most tasks?
I'm coming at this from a somewhat beginners viewpoint so if this is an obvious question it's because I didn't know the right terms to search for.  Are there DBMS's that provide an alternative interface (say an API) to the usual query language text prompt, that's less flexible and less powerful for simple operations?  Ideally any task that involved user input would be handled with a combination of simple queries via this API and logic in the programming language.  SQL or another query language would be reserved for either human users or particular nearly-static queries that did not incorporate user input.

Architecturally the lack of a text stream would probably remove simple network transparency, requiring a local "server" acting as dispatch to the real server on the network.

As I said I'm currently a beginner at any of this, but this seems such an obvious design decision that I suspect it either already exists (maybe everywhere), or it is actually impossible in practice.  It would be nice to know why.

Added later:
To clarify the intent is to access the database without using reflection somewhere.  Ideally all possible locations of reflection of user input would be ruled out including any use of the system shell.  SQL is just the starting point, but under this logic Shellshock is considered the same type of vulnerability as SQL injection.

答:
I'm not 100% sure what you are asking, but I'm taking it you are wondering whether you always have to program SQL strings to query a database?
If so, that depends on the language you are working with, using C# you can write LINQ statements (Language integrated query) https://msdn.microsoft.com/en-us/library/bb386976%28v=vs.110%29.aspx.

So you can write code like

```<code> var queryLondonCustomers = from cust in customers
                       where cust.City == "London"
                       select cust;
</code>```

Keep in mind that this will still be  translated to SQL for the database, it's just a layer on top of SQL for the programmer.

ContentLicense: CC BY-SA 3.0

Body:
I'm not 100% sure what you are asking, but I'm taking it you are wondering whether you always have to program SQL strings to query a database?
If so, that depends on the language you are working with, using C# you can write LINQ statements (Language integrated query) https://msdn.microsoft.com/en-us/library/bb386976%28v=vs.110%29.aspx.

So you can write code like

 var queryLondonCustomers = from cust in customers
                       where cust.City == "London"
                       select cust;

Keep in mind that this will still be  translated to SQL for the database, it's just a layer on top of SQL for the programmer.


问:
Is recursion a declarative approach to solve the problems?
I have noticed many problems in algorithms textbook are solved by recursion (divide and conquer, backtracking,...)

As I tried to enhance my skills in writing them, I have noticed, I just need to translate a recursive definition of the problem to the code. Then I don't even need to know how it will be executed. I thought recursion may naturally belong to functional programming.

Actually I am new to functional or declarative programming (I just was studying some about them). Is it a good advice for students to think declaratively (think to relate the definitions rather how) when they want to write a recursive algorithm? Could it be a general rule for any recursive algorithm?

Beside, what is exactly the declarative approach to solve a problem (as it is in functional programming)?

答:
Broadly speaking, declarative programming concerns itself with telling the computer what to do.  Imperative programming concerns itself with telling the computer how to do it.  Any non-trivial program will necessarily contain both.

Imperative programming is typically associated with control flow, loops and mutable state.  Programs written in the procedural paradigm are typically imperative, though they don't necessarily have to be; you can write functions in a procedural language that operate in much the same way that they do in a functional language.

Imperative programming begins at the machine language level, where loops, jumps and state are common.  From there, you can create higher abstractions by writing programming languages, starting from assembly language (which, for the most part, maps to processor instructions).  You can progress to a procedural language like C, make it object-oriented (C with classes), add a lot more sophistication (C++), and still be entrenched in imperative programming for the most part.

Declarative programming is characterized more by declarations than instructions.  It encompasses domain-specific languages like SQL, functional languages like Haskell, and declarative data structures like XML.  Purely functional programming languages dispense with mutable state, preferring to store state in the spaces between function calls, rather than as private members of a class.  You can write purely functional code in an imperative/OO language, as Linq demonstrates.

The reason you see recursion a lot in purely functional languages is because those language also dispense with loops.  Without a loop (a construct that is grounded specifically in the how), one must resort to recursion to get loop-like behavior.  As you have already discovered, many problems can be expressed naturally using recursion, once you understand it.

The important thing to remember about thinking declaratively is that it's just another level of abstraction.  Should your students think about solving problems declaratively?  Absolutely, but they must also be capable of telling the computer how to solve the problem, not just what.

It's no accident that the programming languages that are considered most practical and pragmatic by their practicioners are the ones that you can write code in both declarative and imperative styles.

Further Reading

Imperative Programming

Declarative Programming


问:
Why is base-for-all-objects discouraged in C++
Stroustrup says "Don’t immediately invent a unique base for all of your classes (an Object class). Typically, you can do better without it for many/most classes." (The C++ Programming Language Fourth Edition, Sec 1.3.4)

Why is a base-class-for-everything generally a bad idea, and when does it make sense to create one?

答:
Having one root object limits what you can do and what the compiler can do, without much payoff.

A common root class makes it possible to create containers-of-anything and extract what they are with a dynamic_cast, but if you need containers-of-anything then something akin to boost::any can do it without a common root class.  And boost::any also supports primitives -- it can even support the small buffer optimization and leave them almost "unboxed" in Java parlance.

C++ supports and thrives on value types.  Both literals, and programmer written value types.  C++ containers efficiently store, sort, hash, consume and produce value types.

Inheritance, especially the kind of monolithic inheritance Java style base classes imply, requires free-store based "pointer" or "reference" types.  Your handle/pointer/reference to data holds a pointer to the interface of the class, and polymorphically could represent something else.

While this is useful in some situations, once you have married yourself to the pattern with a "common base class", you have locked your entire code base into the cost and baggage of this pattern, even when it isn't useful.

Almost always you know more about a type than "it is an object" at either the calling site, or in the code that uses it.

If the function is simple, writing the function as a template gives you duck-type compile time based polymorphism where information at the calling site is not thrown away.  If the function is more complex, type erasure can be done whereby the uniform operations on the type you want to perform (say, serialization and deserialization) can be built and stored (at compile time) to be consumed (at run time) by the code in a different translation unit.

Suppose you have some library where you want everything to be serializable.  One approach is to have a base class:

```<code>struct serialization_friendly {
  virtual void write_to( my_buffer* ) const = 0;
  virtual void read_from( my_buffer const* ) = 0;
  virtual ~serialization_friendly() {}
};
</code>```

Now every bit of code you write can be serialization_friendly.

```<code>void serialize( my_buffer* b, serialization_friendly const* x ) {
  if (x) x->write_to(b);
}
</code>```

Except not a std::vector, so now you need to write every container.  And not those integers you got from that bignum library.  And not that type you wrote that you didn't think needed serialization.  And not a tuple, or an int or a double, or a std::ptrdiff_t.

We take another approach:

```<code>void write_to( my_buffer* b, int x ) {
  b->write_integer(x);
}
template<class T,
  class=std::enable_if_t< void_t<
    std::declval<T const*>()->write_to( std::declval<my_buffer*>()
  > >
>
void write_to( my_buffer* b, T const* x ) {
  if (x) x->write_to(b);
}
template<class T>
void serialize( my_buffer* b, T const& t ) {
  write_to( b, t );
}
</code>```

which consists of, well, doing nothing, seemingly.  Except now we can extend write_to by overriding write_to as a free function in the namespace of a type or a method in the type.

We can even write a bit of type erasure code:

```<code>namespace details {
  struct can_serialize_pimpl {
    virtual void write_to( my_buffer* ) const = 0;
    virtual void read_from( my_buffer const* ) = 0;
    virtual ~can_serialize_pimpl() {}
  };
}
struct can_serialize {
  void write_to( my_buffer* b ) const { pImpl->write_to(b); }
  void read_from( my_buffer const* b ) { pImpl->read_from(b); }
  std::unique_ptr<details::can_serialize_pimpl> pImpl;
  template<class T> can_serialize(T&&);
};
namespace details {
  template<class T>
  struct can_serialize : can_serialize_pimpl {
    std::decay_t<T>* t;
    void write_to( my_buffer*b ) const final override {
      serialize( b, std::forward<T>(*t) );
    }
    void read_from( my_buffer const* ) final override {
      deserialize( b, std::forward<T>(*t) );
    }
    can_serialize(T&& in):t(&in) {}
  };
}
template<class T> can_serialize::can_serialize<T>(T&&t):pImpl(
  std::make_unique<details::can_serialize<T>>( std::forward<T>(t) );
) {}
</code>```

and now we can take an arbitrary type and auto-box it into a can_serialize interface that lets you invoke serialize at a later point through a virtual interface.

So:

```<code>void writer_thingy( can_serialize s );
</code>```

is a function that takes anything that can serialize, instead of

```<code>void writer_thingy( serialization_friendly const* s );
</code>```

and the first, unlike the second, it can handle int, std::vector<std::vector<Bob>> automatically.

It didn't take much to write it, especially because this kind of thing is something you only rarely want to do, but we gained the ability to treat anything as serializable without requiring a base type.

What more, we can now make std::vector<T> serializable as a first-class citizen by simply overriding write_to( my_buffer*, std::vector<T> const& ) -- with that overload, it can be passed to a can_serialize and the serializabilty of the std::vector gets stored in a vtable and accessed by .write_to.

In short, C++ is powerful enough that you can implement the advantages of a single base class on-the-fly when required, without having to pay the price of a forced inheritance hierarchy when not required.  And the times when the single base (faked or not) is required is reasonably rare.

When types are actually their identity, and you know what they are, optimization opportunities abound.  Data is stored locally and contiguously (which is highly important for cache friendliness on modern processors), compilers can easily understand what a given operation does (instead of having an opaque virtual method pointer it has to jump over, on leading to unknown code on the other side) which lets instructions be optimally reordered, and fewer round pegs are hammered into round holes.

Body:
Having one root object limits what you can do and what the compiler can do, without much payoff.

A common root class makes it possible to create containers-of-anything and extract what they are with a dynamic_cast, but if you need containers-of-anything then something akin to boost::any can do it without a common root class.  And boost::any also supports primitives -- it can even support the small buffer optimization and leave them almost "unboxed" in Java parlance.

C++ supports and thrives on value types.  Both literals, and programmer written value types.  C++ containers efficiently store, sort, hash, consume and produce value types.

Inheritance, especially the kind of monolithic inheritance Java style base classes imply, requires free-store based "pointer" or "reference" types.  Your handle/pointer/reference to data holds a pointer to the interface of the class, and polymorphically could represent something else.

While this is useful in some situations, once you have married yourself to the pattern with a "common base class", you have locked your entire code base into the cost and baggage of this pattern, even when it isn't useful.

Almost always you know more about a type than "it is an object" at either the calling site, or in the code that uses it.

If the function is simple, writing the function as a template gives you duck-type compile time based polymorphism where information at the calling site is not thrown away.  If the function is more complex, type erasure can be done whereby the uniform operations on the type you want to perform (say, serialization and deserialization) can be built and stored (at compile time) to be consumed (at run time) by the code in a different translation unit.

Suppose you have some library where you want everything to be serializable.  One approach is to have a base class:

struct serialization_friendly {
  virtual void write_to( my_buffer* ) const = 0;
  virtual void read_from( my_buffer const* ) = 0;
  virtual ~serialization_friendly() {}
};

Now every bit of code you write can be serialization_friendly.

void serialize( my_buffer* b, serialization_friendly const* x ) {
  if (x) x->write_to(b);
}

Except not a std::vector, so now you need to write every container.  And not those integers you got from that bignum library.  And not that type you wrote that you didn't think needed serialization.  And not a tuple, or an int or a double, or a std::ptrdiff_t.

We take another approach:

void write_to( my_buffer* b, int x ) {
  b->write_integer(x);
}
template<class T,
  class=std::enable_if_t< void_t<
    std::declval<T const*>()->write_to( std::declval<my_buffer*>()
  > >
>
void write_to( my_buffer* b, T const* x ) {
  if (x) x->write_to(b);
}
template<class T>
void serialize( my_buffer* b, T const& t ) {
  write_to( b, t );
}

which consists of, well, doing nothing, seemingly.  Except now we can extend write_to by overriding write_to as a free function in the namespace of a type or a method in the type.

We can even write a bit of type erasure code:

namespace details {
  struct can_serialize_pimpl {
    virtual void write_to( my_buffer* ) const = 0;
    virtual void read_from( my_buffer const* ) = 0;
    virtual ~can_serialize_pimpl() {}
  };
}
struct can_serialize {
  void write_to( my_buffer* b ) const { pImpl->write_to(b); }
  void read_from( my_buffer const* b ) { pImpl->read_from(b); }
  std::unique_ptr<details::can_serialize_pimpl> pImpl;
  template<class T> can_serialize(T&&);
};
namespace details {
  template<class T>
  struct can_serialize : can_serialize_pimpl {
    std::decay_t<T>* t;
    void write_to( my_buffer*b ) const final override {
      serialize( b, std::forward<T>(*t) );
    }
    void read_from( my_buffer const* ) final override {
      deserialize( b, std::forward<T>(*t) );
    }
    can_serialize(T&& in):t(&in) {}
  };
}
template<class T> can_serialize::can_serialize<T>(T&&t):pImpl(
  std::make_unique<details::can_serialize<T>>( std::forward<T>(t) );
) {}

and now we can take an arbitrary type and auto-box it into a can_serialize interface that lets you invoke serialize at a later point through a virtual interface.

So:

void writer_thingy( can_serialize s );

is a function that takes anything that can serialize, instead of

void writer_thingy( serialization_friendly const* s );

and the first, unlike the second, it can handle int, std::vector<std::vector<Bob>> automatically.

It didn't take much to write it, especially because this kind of thing is something you only rarely want to do, but we gained the ability to treat anything as serializable without requiring a base type.

What more, we can now make std::vector<T> serializable as a first-class citizen by simply overriding write_to( my_buffer*, std::vector<T> const& ) -- with that overload, it can be passed to a can_serialize and the serializabilty of the std::vector gets stored in a vtable and accessed by .write_to.

In short, C++ is powerful enough that you can implement the advantages of a single base class on-the-fly when required, without having to pay the price of a forced inheritance hierarchy when not required.  And the times when the single base (faked or not) is required is reasonably rare.

When types are actually their identity, and you know what they are, optimization opportunities abound.  Data is stored locally and contiguously (which is highly important for cache friendliness on modern processors), compilers can easily understand what a given operation does (instead of having an opaque virtual method pointer it has to jump over, on leading to unknown code on the other side) which lets instructions be optimally reordered, and fewer round pegs are hammered into round holes.


答:
Although you could avoid "SQL injection" attacks by not using a relational database or not using SQL to query one, they are really part of a broader range of untrusted user input attacks that need to be protected against. Even if you had a NoSQL key / value pair store you could still be vulnerable to an attacker deleting all the data in your store.

The lesson behind the warning against SQL injection attacks is really to not execute user input directly but to sanitise it in some way.

Title: Is it possible to avoid SQL injection by not using a Query Language for most tasks?

Body:
I'm coming at this from a somewhat beginners viewpoint so if this is an obvious question it's because I didn't know the right terms to search for.  Are there DBMS's that provide an alternative interface (say an API) to the usual query language text prompt, that's less flexible and less powerful for simple operations?  Ideally any task that involved user input would be handled with a combination of simple queries via this API and logic in the programming language.  SQL or another query language would be reserved for either human users or particular nearly-static queries that did not incorporate user input.

Architecturally the lack of a text stream would probably remove simple network transparency, requiring a local "server" acting as dispatch to the real server on the network.

As I said I'm currently a beginner at any of this, but this seems such an obvious design decision that I suspect it either already exists (maybe everywhere), or it is actually impossible in practice.  It would be nice to know why.

Added later:
To clarify the intent is to access the database without using reflection somewhere.  Ideally all possible locations of reflection of user input would be ruled out including any use of the system shell.  SQL is just the starting point, but under this logic Shellshock is considered the same type of vulnerability as SQL injection.


问:
Using message queue systems - forcing synchronous processing
I have a php process producer-a which places a job on RabbitMQ a - deferring processing to a third-party service. The 3rd party service completes processing a and places a response onto queue b. I have a listener consumer-b which picks up jobs on queue b to continue processing.

I need to ensure that producer-a has completed it's process entirely before the listener consumer-b picks up the job to continue processing.

The problem which I am facing is that by using RMQ - I am asynchronously performing tasks - however I need to serialise this process whilst still using RMQ.

In case the above doesn't make sense:

Example timeline if serialised:

```<code>Process A ------> Process B ------> Process C
</code>```

Example timeline with message queue

```<code>Internal Process    Process A----------------------------------|

Deferred Process           Process B -----|

Internal Process                          |Process C---|
</code>```

Process A needs to complete fully before Process C. The problem is that Process B is deferred to a 3rd party service via a message queue, and I need to ensure that Process A which sent the job to Process B completed before Process C picks up the job from Process A. As can be seen from the timeline above, Process C has completed before Process A has completed.

Update:

I didn't think to state the obvious but seem to be getting obvious suggestions / solutions. producer-a simply needs to send a TCP message to Loggly (sometimes takes over 2s) and also needs to update the database to advise that the process was deferred. Sometimes, the message comes back and is picked up by Process C before Process A has completed.

答:
If you need producer a to have finished before consumer b starts processing then either:

producer a should add the message to queue a as the last thing it does

producer a should add a message to another queue as the last thing it does and consumer b should wait either for that flag message before it picks up the main message to process or else pick up the main message to process and then wait for the confirmation flag message on the other queue.


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

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

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

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

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

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

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

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

So my question would be rephrased:

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

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

答:
I really like Dylan's just-normal-dashes-as-they-are-easy-to-type-and-easy-to-read.

Like

```<code>result-code := write-buffer(file-stream, some-string)
</code>```

But I guess as this language is fairly obscure, this is kind of off-topic... :(

ContentLicense: CC BY-SA 2.5

Body:
I really like Dylan's just-normal-dashes-as-they-are-easy-to-type-and-easy-to-read.

Like

result-code := write-buffer(file-stream, some-string)

But I guess as this language is fairly obscure, this is kind of off-topic... :(

OwnerDisplayName: Kosta


答:
What you have is a scatter-gather problem.

Process A has to scatter his (possibly intermediate) results between Process B and the French Foreign Legion.  Process B must gather the work products from Process A and the French Foreign Legion, and cannot proceed until he has both of them.

Presumably, RabbitMQ has a capability to wait on multiple queues simultaneously.  Establish a third queue, for completion notifications from Process A to Process B.  Process B then waits on both queues, and, using magic cookies embedded in the messages, matches the French Foreign Legion dispatches to the Process A completions.  When it has both pieces of the golden ticket, Process B continues.  If it only has one piece of the cookie, it continues waiting on both queues.

Title: Using message queue systems - forcing synchronous processing

Body:
I have a php process producer-a which places a job on RabbitMQ a - deferring processing to a third-party service. The 3rd party service completes processing a and places a response onto queue b. I have a listener consumer-b which picks up jobs on queue b to continue processing.

I need to ensure that producer-a has completed it's process entirely before the listener consumer-b picks up the job to continue processing.

The problem which I am facing is that by using RMQ - I am asynchronously performing tasks - however I need to serialise this process whilst still using RMQ.

In case the above doesn't make sense:

Example timeline if serialised:

```<code>Process A ------> Process B ------> Process C
</code>```

Example timeline with message queue

```<code>Internal Process    Process A----------------------------------|

Deferred Process           Process B -----|

Internal Process                          |Process C---|
</code>```

Process A needs to complete fully before Process C. The problem is that Process B is deferred to a 3rd party service via a message queue, and I need to ensure that Process A which sent the job to Process B completed before Process C picks up the job from Process A. As can be seen from the timeline above, Process C has completed before Process A has completed.

Update:

I didn't think to state the obvious but seem to be getting obvious suggestions / solutions. producer-a simply needs to send a TCP message to Loggly (sometimes takes over 2s) and also needs to update the database to advise that the process was deferred. Sometimes, the message comes back and is picked up by Process C before Process A has completed.


问:
Why are language features more popular than compiler design?
If we had a universal interpreter for all available features of programming languages we could use a specializer to generate compilers for all languages. We could simply use any language as source (or input) and any platform as target (output).

We could all write in our favorite programming language to add features to that universal interpreter because the base Abstract Syntax Tree (used by the universal interpreter) could be a target of our favorite programming language. On top of that, you could view the 'source code' of the universal interpreter in any language because the 'source code' of that universal interpreter is actually an AST.

Despite programmers having these sort of ideas for more than 40 years most of us still seem to think that we need to choose a specific textual representation and appropriate interpreter (or specialized interpreter called compiler).

I don't get why that is. There are so much programmers around and most programmers are really passionate about their ability to create. I don't understand why we fight about different programming languages, to me they seem like a different view on the same AST.

Why are we all not using the same base as a library from which we can pick language features?

答:
You seem to think that programming languages differ only in their syntax. This is not the case. Languages can have vastly incompatible semantics as well. For example:

A functional language that uses lazy evaluation and an imperative language that allows side effects are difficult to combine.

A language that allows pointer arithmetic and a language that guarantees memory safety are difficult to reconcile.

A program involving infinite loops cannot necessarily be expressed in a language such as Coq.

A language that allows dynamic dispatch (i.e. OOP) is incompatible with a language that is completely statically typed.

Some languages don't offer dynamic memory allocation.

A program using closures does not have a straightforward representation in a language without garbage collection.

The list of incompatibilities goes on and on.

There are a couple of program representations that are common for different languages. These are called machine code or byte code. While they are functionally equivalent to the original program, most of the structure of the program is lost.

The .NET common language runtime is an interesting example of an intermediate-level language platform that supports a variety of different languages, both imperative and object-oriented (e.g. C#) and functional (e.g. F#). While programs cannot be transformed from one language to the other – slight feature mismatches exist –, different parts of the same project can be written using different languages. Due to the common feature-rich runtime, their interop facilities are practically effortless.


问:
Why use the Singleton pattern over class functions and fields?
I'm going to start by saying that I understand that programming in mostly class functions and variables can be harmful to object-orientation, and that most of the time an instance is preferred. I'll be using Java as my language for this question, but it should apply to any language which makes the distinction between class and instance scopes.

But there are still times when only a single instance is wanted, which calls for the Singleton pattern:

public class Singleton1
{
    private static Singleton1 instance;

    private Object myObject;

    private Singleton1()
    {
        myObject = new Object();
        // other initializations here
    }

    public static getInstance()
    {
        if (instance == null)
            instance = new Singleton();
        return instance;
    }

    public Object getMyObject()
    {
        return myObject;
    }

    // and so on with the non-static public and private methods
}
```

<p>This will be used as such:</p>

<pre class="lang-java prettyprint-override"><code>Singleton1 singleton1 = Singleton1.instance();
singleton1.getMyObject();
// any other method called like singleton1.method(args);
</code>```

This pattern forces programmers using the Singleton1 class to get instances via Singleton1.getInstance() instead of the usual new Singleton1(), since the only constructor is private. The main benefit of this is guaranteeing that there is only one instance of Singleton1 being used, and so any one modification rings true everywhere in the program.

My question is, why go through the rigamarole of keeping the constructor and instance private, when the static modifier takes care of all this already? See my example counterpoint below:

public class Singleton2
{
    private static Object myObject;

    static
    {
        myObject = new Object();
        // other initializations here
    }

    private Singleton2(){/*nothing*/}

    public static Object getMyObject()
    {
        return myObject;
    }

    // and so on with the static public and private methods
}
```

<p>This will be used as such:</p>

<pre class="lang-java prettyprint-override"><code>Singleton2.getMyObject();
// any other method called like Singleton2.method(args);
</code>```

To me, this seems like less code and easier to keep up with.

答:
First and foremost, calling Singleton2's getMyObject() method will crash the program because it does not create a new instance when it is null, and will just return null.

Second, there is no getMyObject in a singleton class. There is just getInstance().


问:
One dll or many?
I currently have one "library" dll that has one module for each topic: Text, Reflection, Security, Math, FileSystem, FTP, Mail, Serialization, etc.

In each module are public helper methods that may call .Net framework methods or other helper methods.

In the past, I have had multiple dlls, each dedicated to a topic. This proved to be much harder to manage as there was some inter-dependency among the dlls (why not use library methods inside the library?), and they would get out of sync. Not to mention, circular dependencies are not allowed.

Here is my library, and you can see the circular dependency in one case

I'm having difficulty grasping this:

"Uncle Bob" Martin of Clean Code:

The Release Reuse Equivalency Principle: The granule of reuse is the granule of release.

What's the best architectural standard for organizing a library of modules?

答:
Ask yourself whether it makes sense for a consumer of a library to use one part of it without using another one.

Let's say you've developed a library which parses LESS files, processes LESS files into non-minified CSS files and minifies CSS files.

Does it make sense to have a library which does just the parsing? For general use, not really. But it makes total sense for a person who wants to, say, create a linter for LESS files.

Does it make sense to have a library which does just processing? Probably not. OK, it might be that somebody writes a parser which is faster and better than yours, but this person will probably also write his own processing engine as well. Therefore, a processor without a parser is not very useful.

Does it make sense to have a library which minifies CSS and ignores everything related to LESS? Completely.

As a result, we have not one, but two libraries:

LESS parser and processor, which depends on...

...CSS minifier.

Why two instead of three? Well, the general use, as previously explained, is to use the parser and the processor together. There is a rare case where the parser can be used independently, this doesn't justify the cost of making two libraries (although you or your team may decide that such case is still important and you should have two separate libraries).

In practice:

If you are constantly seeing yourself including two libraries side by side and there are practically no cases where you include one without another one (or the other way around in a case where there is a dependency), merge the libraries.

If you constantly use only a part of the library and this part looks like being logically distinct from other parts, split the library.

I also noticed a few points I want to highlight but which are unrelated to the question itself. Consider it a sort of comment:

Have you looked at the organization of .NET Framework itself?

The "public functions that wrap .NET Framework functions" sound scary. Why doing all this work? What's the point in calling your methods instead of .NET Framework ones?

Functions and methods are not the same thing. I believe you're taking about methods here.

If you end up getting circular dependencies, it might indicate that your architecture is deeply flawed.

By new ship, do you mean a complete rewrite? If yes, you may be interested by an article by Joel Spolsky.

Title: One dll or many?


问:
How to API design architecture for long delay process
Im trying to start an API design using Django Rest Framework, and the problem Im trying to solve is the following:
Request endpoint is like this:
POST
http://server:8080/api/v1/device
attribute: create

When my server receives this API request, it will launch a backend process which takes around 20-60 seconds(Starts an SSH connection to a remote server and check periodically for status there.). I'm not sure how to respond to initial API request? Using  a 200 OK indication that request is handled with a "starting" and then offer an endpoint to provide status?

What is the best architecture for this type of requests?

答:
If the server blocks and responds only when the work is finished, HTTP 200 is indeed the way to go. Make sure you document the waiting time, since some clients may have shorter timeouts (and customers awaiting the reply may consider that something wrong happened).

Otherwise, you may return immediately, in which case HTTP 202 is the correct code:

HTTP 202 Accepted

The request has been accepted for processing, but the processing has not been completed.

Source: RFC 2616

Remark: instead of (or additionally to) making the endpoint which provides status, you may also consider WebSockets. This may reduce the bandwidth by freeing the client from sending repetitive requests for status: instead, the server will push to the client a notification when the process finishes.


问:
Does ORM promote database de-normalisation?
Doctrine and Propel both make use of single and concrete table inheritance to map object relationships. The former sees all possible fields in the class tree mapped to a single table - whereas the latter maps each class to a specific table, duplicating common fields in the inheritance hierarchy.

While this facilitates the ORM apparatus, it suggests bad database design to me. Are these bad design patterns to enforce on a database?

答:
It's impossible to say whether a particular database design is bad without knowing what the application is doing, the shape of the data, the performance expectations and so on.  While generally normalisation (to some degree) is seen as best practice, it's pretty common to denormalise areas of databases for performance reasons so good and bad are very much open for discussion without a lot more data than most people have when they start out.

Add in the many approaches that can be taken to object to relational mappings and things become even more complex as the "best" database structure will depend on the specific object model, the level of inheritance and so on.

By taking a one size fits all approach ORM persistence libraries will almost always produce a non-optimal database structure for any given situation and will use some things which can be seen as bad practice for that a given situation.

You certainly could write an ORM that normalised but you'd see fairly hefty performance implications as for every insert into a main table it needed to scan the various look up tables to see if values existed, if they did obtain their keys and if they didn't carry out the relevant inserts.

(When you do this by hand you can short cut some of this as you know you presented them with a drop down containing only valid value so you don't need to do these look ups, you can just use the key happy that it's going to be valid, the ORM couldn't make that assumption as it doesn't control the UI.)

But what you have to remember is that they aren't aiming to optimise for database performance or data integrity, they're optimising for development speed.  If the specific structure of your data is important to you then you either need to code your object / RDBMS mappings by hand, or at the very least do a detailed assessment of all the libraries available and select the one which most closely meets your needs (if one exists).

Essentially it comes down to requirements and the trade off between well structured data, database performance and development speed.  As with many trade-offs you don't get to pick all three.


问:
How to handle coding errors in my PHP AJAX code?
How do I handle coding errors in my PHP which has no GUI, only an API? I am concerned that I might never know that there are any. Note that only I will develop the client side. This is not a public API.

Do I claim that I tested so thoroughly that there are none?

Do I not handle them and wait for users to complain that the app isn't working?

Do I send an HTPP response 501, perhaps with some indication of what went wrong? If so, do I have a pop-up for the user, possibly asking them to contact me?

Or use a proprietary response code, since I am coding both sides of the AI and no one else ever will?

Or should I have my PHP code send me an email, with error details?

Any other approaches?

答:
Error handling of an API is exactly the same as error handling of any web application. Exceptions should be logged to a central syslog server, and the central log should be reviewed on regular basis. If you use a framework, the framework should handle this for you.

Sending e-mails through PHP every time an exception occurs is a risky path. What if exceptions occur within the sender itself? What if SMTP server is down and you receive no e-mails for weeks? What if a hacker is intentionally generating thousands of exceptions per second?

The response code in a case of an exception should be HTTP 500 Internal Server Error. You are not expected to invent your own response codes, since the point of the API is to use a standard interface any developer can understand. If you use a framework, the framework should handle this for you.

Never claim that you tested your app so well that there are no bugs. Bugs will be found, and your company's reputation will suffer.

How client app should react to HTTP 500 depends on the application. It may inform the user that something went wrong. Or may retry. Or dispatch an AJAX request containing the error and the stack trace. Avoid popups, since they are annoying and will be dismissed most of the time. Don't ask the user to contact you: he is already annoyed by the fact that your application is not working, so you are not in a position of asking the user anything. On the other hand, apologizing and providing a contact address for support is nice.


问:
How to manage Inquiries of more than one products?
I can't guess the perfect title of this question, so please read my case and please help me.

We have 4 different products. Each is having their own site and database, means they are totally independent.
Now I want a common system that can manage "contact us" page inquiries.
Moreover I can pull out the contact inquires from each database. And even I should be able to send bulk mail to all of them. etc etc.

So what kind of application is this? Is there any software available? If yes then which are those? Or do I need to create a new custom application?

Please advise..

答:
If I were working with this situation I would just write an app do what needs to be done.  It's highly unlikely that you find something out there to match your needs (or even get close).

Writing it yourself ensures that the correct data is being pulled from the correct field/database and delivered how/when you want it delivered.


问:
How Javascript Engines access/lookup property names?
How Javascript Engines access/lookup property names? what kind of associative array (data structure or search/lookup algorithm) did they use? (for V8, TraceMonkey, JSC, and Rhino)

For example, in C++ there are map and unordered_map that uses (mostly) RB-Tree and Hash Table, but what for JavaScript Object/{} what kind of associative array did the use for each engine?

Or maybe more specific, how they store a JSON object internally?

Some answers that I've found, in V8, they use additional Hash Table (slide 45)

答: JIT compilation tracing techniques often make "hot" objects transformed into instances of hidden (and dynamically created) classes or structures, for which property access becomes as fast as field access in a C struct


问:
How To Avoid Dependencies between Modules
We have two modules, lets call them U and F.

Module U has entities like that:

```<code>class Upload {
    Long id;
    User uploadedBy;
    Date uploadedAt;
}
</code>```

Module F has entities like that:

```<code>class Field {
    Long id;
    String displayName;
    Type type;
}
</code>```

And both have the typical manager beans with create, edit, delete and some GUI depending on them.

So now what one customer wants to have is for us to add to the entites of module U so they will look like that:

```<code>class Upload {
    // fields as above
    List<Field> fields;
}
</code>```

I don't think that's the best idea, because it would create a dependency between F and U that is not necessary for most customers. So now we are trying to find a good architecture that allows us to model what the customer wants without creating dependencies.

One thing that came to mind was to create a Module E with entities like that:

```<code>class ExtendedUpload1 {
    Upload upload;
    List<Field> fields;
}
// or...
class ExtendedUpload2 extends Upload {
    List<Field> fields;
}
</code>```

So only that module will have dependencies to both F and U, and both F and U can live separately. But we have an API in between GUI and server, meaning separate values classes and interfaces both sides work with. And while we can inject additional functionality to both GUI and server, dynamically extending the API is the actual problem. We would need to copy all the API classes to work with the new values.

What architectural patterns apply to that use case? How could we solve the problem elegantly?

答:
If I got you right, your situation is as follows:

you have customers who are happy with the vanilla Upload class

at least one other needs an extension

you want to avoid the creation of an ExtendedUpload class because it causes you too much hassle (for what reason ever)

if possible, you want to avoid the introduction of a dependency between F and U

I think in this situation, it is the best to modify the Upload class, even if that is not your preferred solution. So some variant of

```<code> class Upload {
     // fields as above
     List<X> extensionFields;
 }
</code>```

is probably the best way to go. For customers who don't need the extensions, extensionFields keeps just beeing an empty list. So the "default customer" is just a special case of the "extended customer" (you have to implement this either), which is naturally included by the empty list, so there should be no explicit handling necessary for the "default customer" when you implement that carefully.

What remains is to choose a type for X:

either you go with your first approach, X=Field. Only you know how much of a problem it is when you live with that dependency.

or you set X=FieldInterface, as @dodev suggested. That avoids the direct coupling, in fact it shifts the coupling from compile time to run time

or you set X=UploadField, where UploadField is a class residing in module U, looking similar to Field, maybe reduced to the attributes you really need from Field. The upside is that you avoid the dependency, and that UploadField has its own "lifecycle", independent from "Field". The downside is that this may result in some code duplication, and, well, UploadField has its own "lifecycle". If an "UpdateField" must be alwas identical to "Field", you now have to maintain two classes and keep them in-sync.

So pick your choice, none of the solutions is perfect, this is a trade-off only you can solve.

Body:
If I got you right, your situation is as follows:

you have customers who are happy with the vanilla Upload class

at least one other needs an extension

you want to avoid the creation of an ExtendedUpload class because it causes you too much hassle (for what reason ever)

if possible, you want to avoid the introduction of a dependency between F and U

I think in this situation, it is the best to modify the Upload class, even if that is not your preferred solution. So some variant of

 class Upload {
     // fields as above
     List<X> extensionFields;
 }

is probably the best way to go. For customers who don't need the extensions, extensionFields keeps just beeing an empty list. So the "default customer" is just a special case of the "extended customer" (you have to implement this either), which is naturally included by the empty list, so there should be no explicit handling necessary for the "default customer" when you implement that carefully.

What remains is to choose a type for X:

either you go with your first approach, X=Field. Only you know how much of a problem it is when you live with that dependency.

or you set X=FieldInterface, as @dodev suggested. That avoids the direct coupling, in fact it shifts the coupling from compile time to run time

or you set X=UploadField, where UploadField is a class residing in module U, looking similar to Field, maybe reduced to the attributes you really need from Field. The upside is that you avoid the dependency, and that UploadField has its own "lifecycle", independent from "Field". The downside is that this may result in some code duplication, and, well, UploadField has its own "lifecycle". If an "UpdateField" must be alwas identical to "Field", you now have to maintain two classes and keep them in-sync.

So pick your choice, none of the solutions is perfect, this is a trade-off only you can solve.


问:
When to use prototypical programming in JavaScript
I've spent a good bit of time developing simple widgets for projects in the following way:

```<code>var project = project || {};

(function() {

  project.elements = {
    prop1: val1,
    prop2: val2
  }

  project.method1 = function(val) {
    // Do this
  }

  project.method2 = function(val) {
    // Do that
  }

  project.init = function() {
    project.method1(project.elements.prop1)
    project.method2(project.elements.prop2)
  }
})()

project.init();
</code>```

But I've started to change my format to the following:

```<code>function Project() {
  this.elements = {
    prop1: val1,
    prop2: val2
  }

  this.method_one(this.elements.prop1);
  this.method_two(this.elements.prop2);
}

Project.prototype.method_one = function (val) {
  //
};

Project.prototype.method_two = function (val) {
  //
};

new Project();
</code>```

Granted, these are silly examples so dont get wrapped around the axel. But what is the functional difference and when should I pick one or the other?

答:
The first difference can be summarized as: this refers to the Instance of the class. prototype refers to Definition.

Let's say we have the following class:

```<code>var Flight = function ( number ) { this.number = number; };
</code>```

So here we are attaching this.number to every instance of the class, and it makes sense because every Flight should have their own flight number.

```<code>var flightOne = new Flight( "ABC" );
var flightTwo = new Flight( "XYZ" );
</code>```

In contrast, prototype defines a single property that can be accessed by all of the instances.

Now if we want to get the flight number, we can simply write the following snippet and all of our instances will get a Reference to this newly prototyped object.

```<code>Flight.prototype.getNumber = function () { return this.number; };
</code>```

The second difference is about the way that JavaScript searches for a property of an object. When you are looking for Object.whatever, JavaScript goes all the way up to the main Object object (the object that everything else has inherited from), and as soon as it finds a match it will return or call it.

But that only happens for the prototyped properties. So if you have somewhere in the higher tiers this.whatever, JavaScript won't consider it as a match and will continue the search.

Let's see how it happens in reality.

First note that [almost] everything are Objects in JavaScript. Try this:

```<code>typeof null
</code>```

Now let's see what is inside an Object (note the Uppercase O and . in the end). In Google Chrome's Developer Tools when you enter the . you will get a list of available properties inside that specific object.

```<code>Object.
</code>```

Now do the same thing for Function:

```<code>Function.
</code>```

You may notice the name method. Just go and fire it up and let's see what happens:

```<code>Object.name
Function.name
</code>```

Now let's create a function:

```<code>var myFunc = function () {};
</code>```

And let's see if we got the name method here as well:

```<code>myFunc.name
</code>```

You should get an empty string, but that's okay. You should not get an Error or Exception.

Now let's add something to that god-like Object and see if we get it in other places as well?

```<code>Object.prototype.test = "Okay!";
</code>```

And there you go:

```<code>Object.prototype.test
Function.prototype.test
myFunc.prototype.test
</code>```

In all cases you should see "Okay!".

Regarding the pros and cons of each method you can consider prototyping as a "more-efficient" way of doing things, since it keeps a reference on every instance rather copying the whole property in each object. On the other hand it's an example of Tightly Coupling which is a big no-no until you can really justify the reason. this is quite more complicated since it's relevant to context. You can find a lot of good resources for free in the internet.

That all said, both ways are just language tools and it really depends to you and the problem you're trying to solve to pick what fits better.

If you need to have a property to be relevant to every instance of a class, then use this. If you need to have a property to function the same on every instance, then use prototype.

Update

Regarding your sample snippets, the first one is an example of Singleton, so it makes sense to use this within object body. You can also improve your example by making it modular like this (and you don't need to always use this as well).

```<code>/* Assuming it will run in a web browser */
(function (window) {
    window.myApp = {
        ...
    }
})( window );

/* And in other pages ... */
(function (myApp) {
    myApp.Module = {
        ...
    }
})( myApp );

/* And if you prefer Encapsulation */
(function (myApp) {
    myApp.Module = {
         "foo": "Foo",
         "bar": function ( string ) {
             return string;
         },
         return {
             "foor": foo,
             "bar": bar
         }
    }
})( myApp );
</code>```

Your second snippet doesn't make that much sense because first you are using this and later you are trying to hack it with prototype, which doesn't work because this takes priority over prototype. I'm not sure what were your expectations from that piece of code and how it was working, but I highly recommend you to refactor it.

Update

To elaborate on this taking precedence on prototype I can show you an example and tell you how it can be explained, but I don't have any external resource to back it up.

The example is very simple:

```<code>var myClass = function () { this.foo = "Foo"; };
myClass.prototype.foo = "nice try!";
myClass.prototype.bar = "Bar";

var obj = new myClass;
obj.foo;     // Still contains "Foo" ...
obj.bar;     // Contains "Bar" as expected
</code>```

The explanation is, as we know, this is relevant to the context. So it won't come to existence until the context is ready. When context is ready? When the new instance is being created! You should guess the rest now! It means that even though there is a prototype definition, but this makes more sense to take precedence because it's all about the new instance being created at that moment.

Body:
The first difference can be summarized as: this refers to the Instance of the class. prototype refers to Definition.

Let's say we have the following class:

var Flight = function ( number ) { this.number = number; };

So here we are attaching this.number to every instance of the class, and it makes sense because every Flight should have their own flight number.

var flightOne = new Flight( "ABC" );
var flightTwo = new Flight( "XYZ" );

In contrast, prototype defines a single property that can be accessed by all of the instances.

Now if we want to get the flight number, we can simply write the following snippet and all of our instances will get a Reference to this newly prototyped object.

Flight.prototype.getNumber = function () { return this.number; };

The second difference is about the way that JavaScript searches for a property of an object. When you are looking for Object.whatever, JavaScript goes all the way up to the main Object object (the object that everything else has inherited from), and as soon as it finds a match it will return or call it.

But that only happens for the prototyped properties. So if you have somewhere in the higher tiers this.whatever, JavaScript won't consider it as a match and will continue the search.

Let's see how it happens in reality.

First note that [almost] everything are Objects in JavaScript. Try this:

typeof null

Now let's see what is inside an Object (note the Uppercase O and . in the end). In Google Chrome's Developer Tools when you enter the . you will get a list of available properties inside that specific object.

Object.

Now do the same thing for Function:

Function.

You may notice the name method. Just go and fire it up and let's see what happens:

Object.name
Function.name

Now let's create a function:

var myFunc = function () {};

And let's see if we got the name method here as well:

myFunc.name

You should get an empty string, but that's okay. You should not get an Error or Exception.

Now let's add something to that god-like Object and see if we get it in other places as well?

Object.prototype.test = "Okay!";

And there you go:

Object.prototype.test
Function.prototype.test
myFunc.prototype.test

In all cases you should see "Okay!".

Regarding the pros and cons of each method you can consider prototyping as a "more-efficient" way of doing things, since it keeps a reference on every instance rather copying the whole property in each object. On the other hand it's an example of Tightly Coupling which is a big no-no until you can really justify the reason. this is quite more complicated since it's relevant to context. You can find a lot of good resources for free in the internet.

That all said, both ways are just language tools and it really depends to you and the problem you're trying to solve to pick what fits better.

If you need to have a property to be relevant to every instance of a class, then use this. If you need to have a property to function the same on every instance, then use prototype.

Update

Regarding your sample snippets, the first one is an example of Singleton, so it makes sense to use this within object body. You can also improve your example by making it modular like this (and you don't need to always use this as well).

/* Assuming it will run in a web browser */
(function (window) {
    window.myApp = {
        ...
    }
})( window );

/* And in other pages ... */
(function (myApp) {
    myApp.Module = {
        ...
    }
})( myApp );

/* And if you prefer Encapsulation */
(function (myApp) {
    myApp.Module = {
         "foo": "Foo",
         "bar": function ( string ) {
             return string;
         },
         return {
             "foor": foo,
             "bar": bar
         }
    }
})( myApp );

Your second snippet doesn't make that much sense because first you are using this and later you are trying to hack it with prototype, which doesn't work because this takes priority over prototype. I'm not sure what were your expectations from that piece of code and how it was working, but I highly recommend you to refactor it.

Update

To elaborate on this taking precedence on prototype I can show you an example and tell you how it can be explained, but I don't have any external resource to back it up.

The example is very simple:

var myClass = function () { this.foo = "Foo"; };
myClass.prototype.foo = "nice try!";
myClass.prototype.bar = "Bar";

var obj = new myClass;
obj.foo;     // Still contains "Foo" ...
obj.bar;     // Contains "Bar" as expected

The explanation is, as we know, this is relevant to the context. So it won't come to existence until the context is ready. When context is ready? When the new instance is being created! You should guess the rest now! It means that even though there is a prototype definition, but this makes more sense to take precedence because it's all about the new instance being created at that moment.


问:
Agile. User stories, Tasks and Reporting
At the moment we are creating tasks based on (pointed) user stories. We then link the tasks to the user story in TFS and move them across the kanban board. Does this sound like a common approach? also how do we report on the tasks? Our velocity doesn't look good as the tasks aren't pointed. we might complete 2 out of 3 tasks in a sprint so how do we report on this?</p>

答:
Your approach of splitting stories into tasks and moving those tasks across the board is very standard fare in Scrum.

There should be no need to report on the task-level in TFS, because tasks don't create value to the business. It is the completed stories that create value to the business.

If a story isn't fully completed by the end of a sprint, then that story must go back to the backlog to be planned again in a future sprint (possibly the next one, depending on the priorities).

If your team has trouble completing most of the stories, then there are a couple possible reasons:

The stories are simply too big to complete in a sprint. If that is the case, then your stories are really epics that must be split into smaller stories.

There is insufficient focus on completing the stories. The team should strive to complete at least the topmost few stories.

The team is seriously over-committing themselves. If the team is consistently too optimistic about what they can accomplish (possibly with added pressure from the business), the scrum master should step in and let the team commit to a realistic number of points, based on the historic velocity. Actually making true on the commitment is a very good boost for morale.


问:
Declarative programming vs. Imperative programming
I feel very comfortable with Imperative programming. I never have trouble expressing algorithmically what I want the computer to do once I figured out what is it that I want it to do. But when it comes to languages like SQL or I often get stuck because my head is too used to Imperative programming.

For example, suppose you have the relations band(bandName, bandCountry), venue(venueName, venueCountry), plays(bandName, venueName), and I want to write a query that says: all venueNames such that for every bandCountry there's a band from that country that plays in venue of that name.

Example: I want all the venueNames in which bands from all countries (bandCountry) played. Also, by "relation" I mean an SQL table.

In my mind I immediately go "for each venueName iterate over all the bandCountries and for each bandCountry get the list of bands that come from it. If none of them play in venueName, go to next venueName. Else, at the end of the bandCountries iteration add venueName to the set of good venueNames".

...but you can't talk like that in SQL and I actually need to think about how to formulate this, with the intuitive Imperative solution constantly nagging in the back of my head. Did anybody else had this problem? How did you overcome this? Did you figured out a paradigm shift? Made a map from Imperative concepts to SQL concepts to translate Imperative solutions into Declarative ones? Read a good book?

PS I'm not looking for a solution to the above query, I did solve it.

答:
When you face a problem you usually think how to solve it.
But if you know how computer solves it for you! Then you're concern about how will be eliminated.

I try  to say how it happens.

You may already are familiar with recursive programs, in recursive programs, you define the problem rather to say how it is solved. you define the base, and define n based on n-1. (for example factorial(n) = n * factorial(n-1)) But you may already know how the computer solve it. it start from the function and call the function recursively until it reach a base definition, then evaluate all the other functions based on the base value.

It's what happen in declarative programming. you define everything based on the existing definitions. And computer knows how to derive the answer for you based on the basic functions.

In SQL you may don't relate definitions to each other but you relate objects or information to each other, you specify what you want and computer search to something (object, information) based on the relations you have provided.


问:
DDD - Effective Aggregate Design Questions
I just read Effective Aggregate Design, by Vaughn Vernon. Summarizing the takeaway:

Model true invariants

Design small aggregates

Reference other aggregates by identity

Use eventual consistency between aggregate's boundaries (before asking whose job it is)

After learning about the above, two questions sprang up:

If I'm not mistaken, one of DDD's reasons for being is avoiding spaghetti code, where business logic is scattered all around on, most of times, a fat service layer. Are you not scattering business logic when you use eventual consistency?

Is there any other way to represent the business ubiquitous language other than having a rich domain model? Can't the language be expressed in a fatter service layer?

I thank you in advance for any input.

答:
A little remark, and then a tentative answer.

Use eventual consistency between aggregate's boundaries (before asking whose job it is)

That's aggregate design by definition. We might argue whether this is a good or bad decision, but the Aggregate in Domain-Driven Design is a "unit of consistency". This is not to say that this is "the right way to do things", only that, when we talk about aggregates, this principle is somewhat implicit.

If I'm not mistaken, one of DDD's reasons for being is avoiding spaghetti code, where business logic is scattered all around on, most of times, a fat service layer. Are you not scattering business logic when you use eventual consistency?

DDD doesn't exist for avoiding spaghetti code, but to provide a sensible way of designing code in places where you have frequent evolutions (due to intrinsic domain complexity - code is changed because people learn - or to rapidly evolving domains - code is changed because we are competing with new ideas). However... spaghetti gets in the way when you are pushing for frequent changes. ;-)

"Scattering business logic" per se isn't a good or a bad thing, until you take into account Bounded Contexts and different purposes that the software might serve. If the business logic belongs to different bounded contexts, then it's fine if it's not in the same place. In CQRS/ES for example, coordination logic frequently gets placed into ProcessManagers, reacting to external Domain Events.

Is there any other way to represent the business ubiquitous language other than having a rich domain model? Can't the language be expressed in a fatter service layer?

Another little clarification is needed: there is no such thing as "the business ubiquitous language". There are many languages with different purposes. They can be made ubiquitous and consistent only within the boundary of a Bounded Context, where they will be expressed well... everywhere (that's the ubiquity), from Acceptance Tests to UI labels to database field names.

The need of a fatter service layer often arises from a misconception of what a model is. If the model is principally behavioural, then its behaviour is decoupled from what users need to see. However, this decoupling is not spread evenly: some portions of the system will look CRUD-like, while in other portions the distance between what the software is doing and what a user needs to see might be strong enough to call for distinct models.

Focusing on what users need to see leads invariably to overlapping models: things with the same name that different users use in different ways. That's because the data looks the same, forcing promiscuous sharing. When the data is promiscuous, the obvious place to put the logic is the service layer. But the problem is upstream of that.


问:
UI design for changing multiple records at once
I have a desktop application where the user has tabular views on some data records. Now we got the requirement to let the user select multiple of these records at the same time and let the him edit some properties of the selected records all at once in a separate edit dialog. The idea is

to change only the properties the user really want change

to keep all other properties unchanged

Furthermore, when the user has selected the records and opens the edit dialog, the properties with equal values in all of the selected records are shown in the corresponding UI fields, the other properties should be shown as "undefined" as long as the user does not start to enter something there. After pressing "Ok", the changes are applied to the records. This kind of UI behaviour is not "rocket science", we already found this, for example, in diagram editors (where you can select multiple drawing elements at once and change their properties.)

The problem is how to visualize the "undefined" state in an intuitive manner, especially for text properties. For boolean values, this is easy: we use just a tri-state check box. For number values, this is easy, too: the "undefined" state is displayed as an empty numeric UI field, and if there is actually a number in there, the state is "defined".

But how shall one design this for text properties? An empty text box field is actually not an "undefined" state, since many of the text properties can actually be empty. One could add a separate check box beside each text box to indicate the difference between "undefined" and "defined", but since our edit dialog contains already check boxes for boolean properties, this seems to be counterintuitive and confusing to the user.

If this matters, we are using Winforms (but I think this problem is not specfic to the actual UI framework).

答:
You could use the system used by Windows. If you open a dialog to edit multiple items, the entries where both pieces of data match is displayed with the data, where they differ a "" or similar string is displayed. The user must select an individual item to edit the multiple-value entries, or they can overwrite it which will replace the field on all items.

If you look at Visual Studio project properties, this is readily apparent.

The Preprocessor Definitions on the 2 projects I selected are different, so cannot be displayed, so VS displays a static string. I can either overwrite them for both projects or I will have to select the projects individually to see what the data is. To me that seems intuitive and obvious - I cannot edit 2 different things at the same time in a single field, so naturally I will have to edit them individually.


问:
Event sourcing and REST
I came across Event Sourcing design and I would like to use in an application where a REST client is needed (RESTful to be precise). However I fail to connect these together as REST is quite CRUD-like and event sourcing is task based. I was wondering how can you designed the creation of commands based on requests to REST server. Consider this example:

With REST you can put a new state to the resource called File. In one request you can send new file name, you can change the parent folder and/or change owner of the file and so on.

How to construct the server so I can use event sourcing. I was thinking about these possibilities:

Determine on server which fields were changed and create appropriate commands (RenameFileCommand, MoveFileCommand, ChangeOwnerCommand, ...) and dispatch these individually. However in this setup, each of the command can fail leaving others out of transaction and thus out of "atomic" change to the resource.

Dispatch only one command (UpdateFileCommand) and in the command handler, more precisely in the aggregate, determine which fields were changed and send individual events instead (FileRenamedEvent, FileMovedEvent, OwnerChangedEvent, ...)

This one I don't like at all: In the request to the server I would specify in the headers which command to use, because the UI is still task based (but communication is done via REST). However it will fail in any other use of REST communication (e.g. in external apps) as they are not bound to change only the one field in one request. Also I bring quite a big coupling into the UI, REST, and ES-based backend.

Which one would you prefer or is there any better way to handle this?

Side note: app written in Java and Axon Framework for event-sourcing.

答:
I think you may have a user-process to implementation mismatch here.

First: will a user honestly want to perform multiple changes to a file simultaneously?
A rename (which may or may not include a change of path?), change of ownership, and perhaps change of file contents (for sake of argument) seem like separate actions.

Lets take the case where the answer is "yes" - your users really do want to make these changes simultaneously.

In that case, I'd strongly recommend against any implementation that sends multiple events - RenameFileCommand, MoveFileCommand, ChangeOwnerCommand - to represent this single user intent.

Why?  Because events can fail.  Maybe its extremely rare, but your user submitted an operation that looked atomic - if a single one of the downstream events fails, then your application state is now invalid.

You are also inviting race hazards on a resource that is clearly shared between each of the event handlers.  You will need to write "ChangeOwnerCommand" in such a way that the file name and file path do not matter, because they could be out of date by the time the command is received.

When implementing a non-event driven restful system with moving and renaming files, I prefer to ensure consistency by using something like an eTag system - ensure that the version of the resource being edited is the version that the user last retrieved, and fail if it has been modified since then.  But if you are dispatching multiple commands for this single user operation, you will need to increment your resource version after each command - so you have no way to know that the resource the user is editing really is the same version as the resource they last read.

What I mean by that is - what if someone else performs another operation on the file at nearly the same time.  The 6 commands could stack up in any order.  If we had just 2 atomic commands, the earlier command could succeed and the later command could fail "resource has been modified since it was last retrieved".  But there is no protection against this when the commands are not atomic, so system consistency is violated.

Interestingly there is a movement toward something like event based architecture in REST, called "Rest without PUT", recommended in the Thoughtworks technology radar, Jan 2015.   There is a considerably longer blog about Rest without PUT here.

Essentially, the idea is that POST, PUT, DELETE and GET are fine for small applications, but when you need to start assuming how put and post and delete might be interpreted at the other end, you introduce coupling. (e.g. "when I DELETE the resource associated with my bank account, the account should be closed")  And the solution proposed is to treat REST in a more Event sourced way.  i.e. Lets POST the user intent as a single event resource.

The other case is simpler.  If your users don't want to do all those operations simultaneously, don't let them.  POST an event for each user intent.  Now you can use etag versioning on your resources.

As for the other applications which are using a very different API to your resources.  That smells like trouble.  Can you construct a facade of the old API on top of your RESTful API and point them at the facade?  i.e. expose a service that performs multiple updates to a file in sequence via the REST server?

If you neither build the RESTful interface on top of the old solution, nor build a facade of the old interface on top of the REST solution, and attempt to maintain both APIs pointing at a shared data resource, you will experience major headaches.

Title: Event sourcing and REST


问:
Can we assume that all users today have Internet access?
As the Internet is pretty much ubiquitous, can we as developers assume that all users have Internet access? Now I don't mean that the code is written in such a way that if there is no connection then the whole program crashes due to lack of error code. What I mean is, can programs today be developed under the assumption that its users will always have access to the Internet?

You may ask "What do we gain by assuming that?" The reason why I'm asking is because at uni we use quite a few programs which require Internet access due to the way it checks the licenses (it checks your IP address -- if it's not an address at campus, then you you're not allowed to use it). Note that the program itself should work fine without Internet access; it's just needed for license checking.

EDIT:
I'm talking about desktop applications here.

EDIT2:
From some of the answers I get a feeling of being accused of exploiting the users in unethical ways. I'm not endorsing what I've described in this question -- I'm just asking about it because the developers of some of the programs we use at uni have done this. Personally I think doing this is plain out stupid and wrong.

答:
Floating licensing server is a similar concept. I used a compiler on IBM's AIX, which constantly checked against a licensing server. It thus was slow and we finally ported the code to gcc.

It's fragile and annoying. I think it only makes sense for very expensive software by almost-monopolistic companies.


问:
Is recursion a declarative approach to solve the problems?
I have noticed many problems in algorithms textbook are solved by recursion (divide and conquer, backtracking,...)

As I tried to enhance my skills in writing them, I have noticed, I just need to translate a recursive definition of the problem to the code. Then I don't even need to know how it will be executed. I thought recursion may naturally belong to functional programming.

Actually I am new to functional or declarative programming (I just was studying some about them). Is it a good advice for students to think declaratively (think to relate the definitions rather how) when they want to write a recursive algorithm? Could it be a general rule for any recursive algorithm?

Beside, what is exactly the declarative approach to solve a problem (as it is in functional programming)?

答:
I think recursive functions belongs to the declarative paradigm:

Define the base: Factorial(1) = 1;

Define Factorial n : Factorial(n) = n* Factorial(n-1);

However, any recursive function shouldn't be a complete declarative function. You can define the base and relate (define) the solution of the main problem to solution (definition) of sub-problems. But for this relation you may need a procedure (imperative procedure)

For example consider merge sort:

Define the base: One element is already sorted

Define the Sort (l,h) : m=(l+h)/2; sub1=Sort(l,m); sub2=Sort(m+1,h); return merge(sub1,sub2);

In this definition merge could be an imperative procedure to relate the definition or solution of sorting the whole array to the sort of the sub-arrays.


问:
Automotive Embedded System
I really need some guidance on this, first of all, I have intermediate knowledge in programming, specifically Java. I have an idea of creating a tool for cars just like the diagnostic testers that we see mechanics use when they need to diagnose cars' issues. I want to create a tool for cars (Not exactly the same as the testers), but I do not know what I need to learn, I know I need to learn C, but what else do I need though?, I don't mind one or two years of self-teach since I am a self-taught programmer. Thanks</p>

答:
You will be fine with C. The language which you use might, to some degree, be influenced by the hardware which you use to interface to the CanBus.

Read up on CanBus. Look at OpenCan. And (eventually) - spend some money and buy some hardware to interface you with your vehicle. Google until you find what suits you, but, for instance, this is cheap and a good start-point.

Title: Automotive Embedded System


问:
How do you keep your software (anti)patterns organized?
You probably all have been there. I am working on a certain code and something is not working. I know I have seen the error before, and I also know that I solved it before. But I cannot remember how I did it. What's more frustrating is that I know that it cost me two hours of googling through various blogposts before I found the answer. I even bookmarked a site, but was it in Chrome, FF, IE that I made the bookmark? There's quite a list of bookmarks, which one was it...?

I've tried lot's of things, evernote, oneNote, mindmaps, wiki's, etc. But I Always seem to fade away from these solutions when it's crunch time. Is this solution working? Yes! Goto next issue. Basically I am to lazy and to unorganized for these solutions. Google is still my goto-guy for issues.

I am wondering how you are handeling these issues? Have you got an extensive library of patterns and solutions? How is it organized? How do you keep it up to date? Does anyone use the "answer your own question" feature of SO for this? How is that working? What to do with verbatim answers in blogposts?

答:
Indeed, I can confirm these same problems in my work. Unfortunately, I cannot claim to have found the solution, but at least I've gotten to a point where it doesn't bother me too much anymore. Here are a few ideas that help mitigating these problems:

As Basile mentioned in his comment, it is important to leave the URLs as comments for all sorts of codes that you had to lookup elsewhere. Note however, that these places are quite rare. You cannot just copy blog post code into production code (legal issues alone should stop you there, quality and other such arguments are up next). So most of the times, it is more like a nifty idea, which is explained in more depth in said blog post or stackoverflow answer. This also ties in with the next point, so in practice, these comments help even less.

DRY. Breath it. Live it. Do not repeat yourself! When you realize the new functionality you're working on is similar to something else, then you have to look it up and eliminate any duplication as good as you can. In the long run, this severely limits the number of places in your code that you would have to look for.

The probably most important and easy way to handle this though is to outsource it. Not to some other country, but to your team members! When you come up with that cool new pattern - go tell someone about it! Never ever keep it to yourself, because then you are the one who has to remember it. If you see someone writing an Anti-pattern - tell them, don't just fix the problem! In addition to transfering your knowledge to team members, reviews help you to profit from your previously outsourced knowledge. People also have diverse skillsets. Some have a freaking good memory. Often times more accurate and faster than google, because they have full knowledge of your project. Make use of that! It's a win-win for everyone in the team.

Issue tracking with traceability is particularly helpful in dealing with errors. If you have an issue from the last time you have dealt with this error, then your issue tracking system should be able to find it for you (from a stacktrace, error message, whatever - but it must be in the ticket description in some way of course). Next comes traceability, i.e. given your ticket you should have a way to quickly find the part of your code that dealt with that problem the first time. Not a lot of google or blog-reading left really. This also ties in with version control, since you can rather quickly find the corresponding changeset when you know the part of the code ("blame" it), or when your commits are referencing the issue number.


问:
Smells in exception handling: how to separate between public and internal exceptions?
During the development of a small web API, we decided to separate internal exceptions from public exceptions. Public exceptions are HTTP exceptions, that translate into HTTP responses with proper status code (e.g: BadRequestHttpException, NotFoundHttpException, etc). Internal exceptions are either exceptions thrown from adapters in our system (cache layer, persistence layer, etc.) or the domain (InvalidUserException, BadPasswordException, etc.).

This has been great so far. However, our controllers are starting to smell really bad:

```<code>    try {
        securityService.login(credentials);
    } catch (InvalidOAuthProviderException e) {
        throw new BadRequestHttpException(e.getMessage(), e.getCode());
    } catch (UserNotFoundException e) {
        throw new NotFoundHttpException(e.getMessage(), e.getCode());
    } catch (InactiveUserException e) {
        throw new NotFoundHttpException(e.getMessage(), e.getCode());
    } catch (InvalidOAuthTokenException e) {
        throw new ForbiddenHttpException(e.getMessage(), e.getCode());
    }
</code>```

The HttpException constructor signature is the error message and code. This will result in a JSON body: {"message":"","code":222}. The code is the unique error code for doc reference. The actual response HTTP code is defined by the type of the exception.

This is clearly not a good sign and i'm sure there's something wrong in the design here. Any help?

答:
You can create reusable utility class that will resolve correct HttpException.

```<code>try {
        securityService.login(credentials);
    } catch (InternalException e) {
        throw ExceptionUtil.resolveHttpException(e);
    }

public class ExceptionUtil {
  public static HttpException resolveHttpException(InternalException exc) {
     if (exc instanceOf InvalidOAuthProviderException)
        return new InvalidOAuthProviderException(e.getMessage(), e.getCode()
     else if (exc instanceOf AnotherInternalException)
        return new  AnotherInternalException;
      ...
    }
</code>```

}

Then you can use it across all application without code redundancy.

Body:
You can create reusable utility class that will resolve correct HttpException.

try {
        securityService.login(credentials);
    } catch (InternalException e) {
        throw ExceptionUtil.resolveHttpException(e);
    }

public class ExceptionUtil {
  public static HttpException resolveHttpException(InternalException exc) {
     if (exc instanceOf InvalidOAuthProviderException)
        return new InvalidOAuthProviderException(e.getMessage(), e.getCode()
     else if (exc instanceOf AnotherInternalException)
        return new  AnotherInternalException;
      ...
    }

}

Then you can use it across all application without code redundancy.


答:
You are handling errors across the boundary between two systems, effectively, so its best to think of the http handler as a system and the internal logic that throws these internal exceptions as a library.

Given you want to catch these at the boundary point, and you do not want to map internal to external exceptions, then you're left with a simple catch-all (or a couple of catch-most) handlers. The client doesn't want to know about the internal exception, so catching everything from a login request and returning a forbidden or bad request exception is the way to go, considering you include the error message from the internal exception, it doesn't really matter what the internal exception was as far as the client interface is concerned - something went wrong, it was either a bad user or some server error.

In most cases, you should be catching the internal errors and performing some other form of handler to them - like logging them or raising an admin alarm, and then returning a more generic "it didn't work" exception to the client. The only difference here is for exceptions you know are 'expected' such as login failure due to a bad password.

Title: Smells in exception handling: how to separate between public and internal exceptions?

Body:
During the development of a small web API, we decided to separate internal exceptions from public exceptions. Public exceptions are HTTP exceptions, that translate into HTTP responses with proper status code (e.g: BadRequestHttpException, NotFoundHttpException, etc). Internal exceptions are either exceptions thrown from adapters in our system (cache layer, persistence layer, etc.) or the domain (InvalidUserException, BadPasswordException, etc.).

This has been great so far. However, our controllers are starting to smell really bad:

```<code>    try {
        securityService.login(credentials);
    } catch (InvalidOAuthProviderException e) {
        throw new BadRequestHttpException(e.getMessage(), e.getCode());
    } catch (UserNotFoundException e) {
        throw new NotFoundHttpException(e.getMessage(), e.getCode());
    } catch (InactiveUserException e) {
        throw new NotFoundHttpException(e.getMessage(), e.getCode());
    } catch (InvalidOAuthTokenException e) {
        throw new ForbiddenHttpException(e.getMessage(), e.getCode());
    }
</code>```

The HttpException constructor signature is the error message and code. This will result in a JSON body: {"message":"","code":222}. The code is the unique error code for doc reference. The actual response HTTP code is defined by the type of the exception.

This is clearly not a good sign and i'm sure there's something wrong in the design here. Any help?


问:
Is static going to make any difference in this code snippet
I have been to an interview and was asked this question - is there any difference adding or removing the static keyword in these classes?

I know what static means but my understanding of this point is weak.

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public static class aAsposeNew
{
    public static void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public static void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

and without the static keyword:

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew aAN = new aAsposeNew();
            aAN.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public class aAsposeNew
{
    public void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

答: No, there won't be any difference. The methods do not modify the state of the class, so having static or not having static has no effect. They are the exact same, minus the fact you need an instance of the class if it isn't static.</p>


问:
What is the relationship between scope and namespaces in Python?
In many resources I found "scope" and "namespaces" are used interchangeably, which seems a bit confusing since they mean different things.

Scope defines the region of the code where a name is available.

The LEGB rule defines the way names are looked up.

Namespace is a place where you look up names.

Then I read:

"names are bind to a namespace according to where they are assigned..." (which I believe is the deal with scopes in lexical scoping).

"functions add an extra namespace layer to your programs" [ref.] (don't they add a extra local scope?)

"all the names assigned inside a function definition are put in the local scope (the
namespace associated with the function call)."

"global scope—that is, a namespace in which variables created (assigned) at the top level of the module file live."

*all of the quotes are from learning python 5th edition ch17

Are namespaces in Python the way scopes are implemented? Are they the same thing? Can anyone enlighten me?

答:
A namespace is a dictionary, mapping names (as strings) to values. When you do an assignment, like a = 1, you're mutating a namespace. When you make a reference, like print(a), Python looks through a list of namespaces to try and find one with the name as a key.

A scope defines which namespaces will be looked in and in what order. The scope of any reference always starts in the local namespace, and moves outwards until it reaches the module's global namespace, before moving on to the builtins (the namespace that references Python's predefined functions and constants, like range and getattr), which is the end of the line.

Imagine you have a function named inner, nested within a global function named outer, and inner contains a reference to a name. Python first looks in the inner namespace. If the name's not there, Python then looks in the outer namespace. If that fails, Python tries the module's global namespace, then the builtin namespace, eventually throwing a NameError if the name isn't found.

When we say x is in a function's namespace, we mean it is defined there, locally within the function. When we say x is in the function's scope, we mean x is either in the function's namespace or in any of the outer namespaces that the function's namespace is currently nested within.

Whenever you define a function, you create a new namespace and a new scope. The namespace is the new, local hash of names. The scope is the implied chain of namespaces that starts at the new namespace, then works its way through any outer namespaces (outer scopes), up to the global namespace (the global scope), and on to the builtins.

The terms can be used almost interchangeably, but that's not because they mean the same thing; it's because they overlap a lot in what they imply.

ContentLicense: CC BY-SA 4.0