答:
There's nothing to prevent high cohesion between two classes that are used commonly together (e.g. an Order and LineItem will commonly reference each other). However, in these cases, I tend to adhere to Domain Driven Design rules and model them as an Aggregate with the Parent being the Aggregate Root. This tells us that the AR is responsible for the lifetime of all objects in its aggregate.

So it would be most like your scenario four where the parent exposes a method to create its children accepting any necessary parameters to properly initialize the children and adding it to the collection.

Title: What is the best way to initialize a child's reference to its parent?

Body:
I'm developing an object model that has lots of different parent/child classes.  Each child object has a reference to its parent object.  I can think of (and have tried) several ways to initialize the parent reference, but I find significant drawbacks to each approach.  Given the approaches described below which is best ... or what is even better.

I'm not going to make sure the code below compiles so please try to see my intention if the code is not syntactically correct.

Note that some of my child class constructors do take parameters (other than parent) even though I don't always show any.

Caller is responsible for setting parent and adding to the same parent.

```<code>class Child {
  public Child(Parent parent) {Parent=parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; set;}
  //children
  private List<Child> _children = new List<Child>();
  public List<Child> Children { get {return _children;} }
}
</code>```

Downside: setting parent is a two-step process for the consumer.

```<code>var child = new Child(parent);
parent.Children.Add(child);
</code>```

Downside: error prone.  Caller can add child to a different parent than was used to initialize the child.

```<code>var child = new Child(parent1);
parent2.Children.Add(child);
</code>```

Parent verifies that caller adds child to parent for which was initialized.

```<code>class Child {
  public Child(Parent parent) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      if (value.Parent != this) throw new Exception();
      _child=value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    if (child.Parent != this) throw new Exception();
    _children.Add(child);
  }
}
</code>```

Downside: Caller still has a two-step process for setting parent.

Downside: runtime checking – reduces performance and adds code to every add/setter.

The parent sets the child's parent reference (to itself) when the child is added/assigned to a parent.  Parent setter is internal.

```<code>class Child {
  public Parent Parent {get; internal set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      value.Parent = this;
      _child = value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    child.Parent = this;
    _children.Add(child);
  }
}
</code>```

Downside: The child is created without a parent reference.  Sometimes initialization/validation requires the parent which means some initialization/validation must be performed in the child’s parent setter.  The code can get complicated.  It would be so much easier to implement the child if it always had its parent reference.

Parent exposes factory add methods so that a child always has a parent reference.  Child ctor is internal.  Parent setter is private.

```<code>class Child {
  internal Child(Parent parent, init-params) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; private set;}
  public void CreateChild(init-params) {
      var child = new Child(this, init-params);
      Child = value;
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public Child AddChild(init-params) {
    var child = new Child(this, init-params);
    _children.Add(child);
    return child;
  }
}
</code>```

Downside: Can’t use initialization syntax such as new Child(){prop = value}.
Instead have to do:

```<code>var c = parent.AddChild();
c.prop = value;
</code>```

Downside: Have to duplicate the parameters of the child constructor in the add-factory methods.

Downside: Can’t use a property setter for a singleton child.  It seems lame that I need a method to set the value but provide read access via a property getter.  It’s lopsided.

Child adds itself to the parent referenced in its constructor.  Child ctor is public.  No public add access from parent.

```<code>//singleton
class Child{
  public Child(ParentWithChild parent) {
    Parent = parent;
    Parent.Child = this;
  }
  public ParentWithChild Parent {get; private set;}
}
class ParentWithChild {
  public Child Child {get; internal set;}
}

//children
class Child {
  public Child(ParentWithChildren parent) {
    Parent = parent;
    Parent._children.Add(this);
  }
  public ParentWithChildren Parent {get; private set;}
}
class ParentWithChildren {
  internal List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
}
</code>```

Downside: calling syntax is not great.  Normally one calls an add method on the parent instead of just creating an object like this:

```<code>var parent = new ParentWithChildren();
new Child(parent); //adds child to parent
new Child(parent);
new Child(parent);
</code>```

And sets a property rather than just creating an object like this:

```<code>var parent = new ParentWithChild();
new Child(parent); // sets parent.Child
</code>```

...

I just learned that SE does not allow some subjective questions and clearly this is a subjective question.  But, maybe it is a good subjective question.


问:
How do we isolate dependencies for a .Net app deploy in a way which is safe for a strongly-named assemblies?
To design in such that it is easy to deploy dependencies with your app, and so that development environments are easy to set up, it is advantageous to isolate an app's dependencies from it's environment. That means the app can get its dependencies from a package manager, and it will not be affected by it's deployment environment (such as the GAC). This principle comes from the Dependencies section of the very interesting "Twelve-Factor App" standards.

In .Net, I guess this would mean explicitly specifying to use dependencies from the bin folder of an app? I am concerned that this might cause problems for shared, strongly-named assemblies. In this Microsoft article, Ferrandez says locking conflicts can occur if apps do not share strongly-named assemblies via the GAC, since the assembly is loaded into a shared domain.

The 12-factor app describes the pieces needed to satisfy this principle as a dependency declaration manifest and a dependency isolation tool.

Does anyone have an established setup for isolating dependencies which is working for you, and is safe for strongly-named assemblies? Are we in the .Net world stuck with separating all our apps into VM's to achieve isolation?

Personal context: I maintain a SAAS app where each server instance runs a few services/apps which engage in some inter-process communication. They have some strongly-named dependencies in common. Having the dependencies in the GAC makes deployment complex, setting up dev environments a pain, and restricts freedom to choose deployment environments. Even without the strong naming or shared dependency issue, I am interested to know how people do dependency declaration and/or isolation. Thanks!

答:
Using Nuget for library dependencies goes a long way toward dependency declaration and isolation.

The packages.config associated to each project can be read as a dependency declaration.

If those package references are marked 'private', they are bundled into the bin folder of your build outputs, and are presumably bundled for deployment.  This avoids the requirement that all reference assemblies are GAC'd on the deployment box.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
What is the actual reason that locks (sentinels) in OO are hard to reason about?
In this talk, Rich Hickey introduces Clojure. He gives an Ants demo and talks about his motivations for implementing a Software Transactional Memory (STM) system.

His reasoning for STM is that "locks are hard to reason about".

I took that to mean that the deadlock situation, where two threads are trying to update the same item and they hold resources that the other thread needs.

So to be atomic one thread has to roll back and retry and the other has to roll forward.

To make this work in an Object Oriented Language, you have to either use an STM framework or roll it yourself by hand.

That's my understanding, but I suspect I've only covered one problem case and I would imagine there is a more general principle that I'm missing. Perhaps the issue is that locks don't compose or something.

My question is: What is the actual reason that locks (sentinels) in OO are hard to reason about?

答:
Locks aren't hard to understand, and concurrency isn't particularly difficult to understand, either (almost everything going on around us in life is concurrent). It is scheduling of the locks that is hard to understand. Almost nothing in real life blocks, but in sequential computing with a single thread everything does, and all we do by splitting threads or processes is to pretend there are several when in fact we are really blocking each other constantly. Scheduling that block is really hard to get right. Its hard to schedule the CPU time for one, and hard to schedule shared, stateful resources as well, but doing both can be a real beast.

Enter things like the Erlang runtime. There concurrency is easy and works the way you expect. This is because the runtime handles the scheduling for you, freeing you up to think about the problem you're actually trying to solve. Scheduling is the big win, not the other stuff that gets hyped all the time. The cost for all that easy concurrency is that no state can be shared. It appears this is not something that most programmers feel comfortable with; there are extremely high incidences of folks doing the "read half a book on Erlang and gave up" dance and winding up right back where they started.

Whatever language or environment you choose to solve problems in it is important to recognize that the nature of the problem is not the locks, the state or the language, it is the scheduling of locks whenever state is shared.


问:
Is this extension method any better than just casting to an int?
The following extension method was set up in some code I maintain.

```<code>public static Int32 GetInt32(this System.Data.Common.DbDataReader reader, string name)
{
   return reader.GetInt32(reader.GetOrdinal(name));
}
</code>```

Which is then called like this:

```<code>int field1 = dr.GetInt32("field1");
</code>```

Is this really any better than just casting to an int like this:

```<code>int field1 = (int)dr["DiskGroupNum"];
</code>```

答:
There is a fundamental difference here.  In one case you say, "I'm going to just assume this is an int", and in the former, you ask the reader to give you an int.  If the value is already an int, I would not expect any difficulty.  However, what happens when the value is a Int64?  You're casting it to an int which is only 4 bytes long.  You may get unexpected surprises this way if you're lucky.  If you're not, the program continues like nothing happened, and you wind up with a value missing its upper 4 bytes.

However if you ask the reader to give you an Int32, you will see it complain should there be some problems with doing so.  It might seem contrary writing code to potentially create exceptions, but it works in your favor ultimately, trust me.  Even if something does go wrong when you don't expect it, the error is clear and can be fixed easily.

If you have a value that doesn't reflect what is read, it may cause problems elsewhere in your program and leave you scratching your head as to why.


问:
Defensive copy in the client class or in the service class?
I have one service method that receive parameters as a Map. I will need to add new attributes to this map inside the service. If I pass the original Map object to the parameter instead of a copy, the original parameters object will be changed.

My question here is: which class is responsible for maintain the integrity of the parameter object?

Should the Client class pass a copy in case the Service changes the parameters, or should the 'Servicedo a copy of the parameters to avoid hurting theClient`?

```<code>public class Client{
    public void search(){
         Map<String, Object> parameters = new HashMap<>();

         // defensive parameters copy here?
         new Service().search(parameters);
         // parameters can be changed if I don't use a defensive copy
    }
}

public class Service{
    public ... search(Map<String, Object> parameters){
        // defensive parameters copy here?
        parameters.put("newParam", 1);
    }
}
</code>```

答:
As a general rule, I don't write methods that have side effects when writing an interface to be called by others.  Methods with side effects are bad in general, though it could happen that you perform some minor state change other than the one expected.

Even if the client didn't need to use this data, I don't think assumptions like that should be made when it comes to the interface.  I would go so far as to pass an ImmutableDictionary to the server to make this fact clear.  The server should use these parameters and apply them.  In this case, you'd probably just copy them, though the server can do with that information whatever it likes. It just can't change that data, unless of course that was the intended action, in my humble opinion.


答:
Actually, I would go with a third option.  Retrieve the column ordinal up-front and use the ordinal overloads.  In any case where you have multiple rows, it saves work:</p>

```<code>var ord_field1 = dr.GetOrdinal("field1");

while(dr.Read())
{
    ...
    var field1 = dr.GetInt32(ord_field1);
    ...
}
</code>```

Title: Is this extension method any better than just casting to an int?

Body:
The following extension method was set up in some code I maintain.

```<code>public static Int32 GetInt32(this System.Data.Common.DbDataReader reader, string name)
{
   return reader.GetInt32(reader.GetOrdinal(name));
}
</code>```

Which is then called like this:

```<code>int field1 = dr.GetInt32("field1");
</code>```

Is this really any better than just casting to an int like this:

```<code>int field1 = (int)dr["DiskGroupNum"];
</code>```

Body:
Actually, I would go with a third option.  Retrieve the column ordinal up-front and use the ordinal overloads.  In any case where you have multiple rows, it saves work:

var ord_field1 = dr.GetOrdinal("field1");

while(dr.Read())
{
    ...
    var field1 = dr.GetInt32(ord_field1);
    ...
}


答:
To understand the correctness of a given line of lock-based concurrency code, you have to understand the entire program.

Now, you can save on this a bit.  If you manage to prove to yourself that everything accessed in that bit of lock-based concurrency code is only accessed within a particular lock, you now only have to understand every bit of code in the program that also accesses that lock, its state when it starts the lock access, and everything it does while holding it.

This is because lock-based concurrency only maintains "thread safety" by locking access to data to limited numbers of threads at once (sometimes 1, sometimes only readers, etc).  So you have to understand all of the locking behavior, and behavior while locking, in order to know if you lock system is actually doing what you want it to.

Next, because locks are subject to deadlocks, in order to understand multiple locks you have to understand not only the code in a lock, but every possible sequence you can acquire locks in.

And our languages and type systems do not help all that much with these tasks.

It gets worse.  Like the other hard to track down and common errors, the deadlock and race condition problems usually do not happen reliably.  You can write the code, do some simple tests, even run it in production, and have it work almost always.  Except sometimes it fails spectacularly.

Really rare spectacular failures are hard to debug regardless of how easy they are to reason about.  Here we have rare, spectacular failures that are difficult to reason about.

And it gets worse.  When learning how to program, people typically run into a number of hurdles.  Understanding state/assignment/data flow is a hurdle some don't get over.  Understanding conditionals and function calling is another.  Recursion and iteration throws some people for a loop.  Indirection and pointers cut off an entire set of would-be programmers from becoming useful.  Resource management.  And concurrency and synchronization is another such hurdle.

We can generate more useful programmers by removing some of these hurdles "in the way" of being productive.  There are languages that hide indirection and pointers from the programmer, and handle the big resource management task for you (memory), and you can learn to become a productive programmer in those languages without getting over that hurdle.

In almost every language you can become a "productive programmer" without getting over the concurrency hurdle.  You can produce useful code, be a professional developer, graduate from university -- all of them without ever getting concurrency.

The ones that didn't get flow control, data flow and iteration never became professional programmers.  The ones who don't get concurrency are productive senior developers at many a company.

Body:
In this talk, Rich Hickey introduces Clojure. He gives an Ants demo and talks about his motivations for implementing a Software Transactional Memory (STM) system.

His reasoning for STM is that "locks are hard to reason about".

I took that to mean that the deadlock situation, where two threads are trying to update the same item and they hold resources that the other thread needs.

So to be atomic one thread has to roll back and retry and the other has to roll forward.

To make this work in an Object Oriented Language, you have to either use an STM framework or roll it yourself by hand.

That's my understanding, but I suspect I've only covered one problem case and I would imagine there is a more general principle that I'm missing. Perhaps the issue is that locks don't compose or something.

My question is: What is the actual reason that locks (sentinels) in OO are hard to reason about?


答:
No, it is not better than casting to int (in my opinion).

In your specific example, dr["DiskGroupNum"] returns type object, which means that your second example:

```<code>int field1 = (int)dr["DiskGroupNum"];
</code>```

You are actually unboxing the object to type int, which will give you an InvalidCastException if it's not exactly of type int (Int32 specifically).

Why I think it is not beneficial to have an extension method to do this is:

It's more writing

It's more code to debug

You'll have to write specific code for different types

Body:
No, it is not better than casting to int (in my opinion).

In your specific example, dr["DiskGroupNum"] returns type object, which means that your second example:

int field1 = (int)dr["DiskGroupNum"];

You are actually unboxing the object to type int, which will give you an InvalidCastException if it's not exactly of type int (Int32 specifically).

Why I think it is not beneficial to have an extension method to do this is:

It's more writing

It's more code to debug

You'll have to write specific code for different types


问:
Looking for encryption method
I have a blackbox system whose code is hidden from the end user. That's the intent anyway, I know some may break into it, but generally it's closed.

It's running on PHP, and I need to export a database for backup purposes. This database contains some data I don't want the user to tamper with, so the idea is obvious - encrypt the data file.

I can use RSA, but I'm not sure if it's the best, considering both private and public keys would be embedded in the code. I can also password-protect a zip containing the data file. There's maybe other methods I'm unaware of.

Here's a silly ASCII art diagram of what I want

```<code> /*

+----------black-box system-----------+
|                                     |
|   +----------+      ??????????????  |  +-------------+
|   | SQL DUMP | ===> ? ENCRYPTION ? ==> # BACKUP FILE #
|   +----------+      ??????????????  |  +-------------+
|                                     |         v
|   +----------+      ??????????????  |  +-------------+
|   | SQL DUMP | <=== ? DECRYPTION ? <== # BACKUP FILE #
|   +----------+      ??????????????  |  +-------------+
|                                     |
+-------------------------------------+

*/
</code>```

The file should be readable by the app again, for "restore from backup" functionality.

Please, suggest how to protect the file. Thanks.

答:
Your model is casual security, so you might as well just flip a coin. Not to be sarcastic, but if you store your keys in code and are sharing the key across all users of your app, and your goal is just to obscure the data from casual tampering, then it really doesn't matter. Pick a symmetric cipher (AES-128 block cipher for example) and be done. It is commonly supported and also fast on modern hardware.

Just make sure not to market the feature as "secure". It is casual anti-tampering, but not secure.

Title: Looking for encryption method


问:
How do I cope with a manager who’s always interfering in what I do, but doesn’t really understand it?
We've all had them, managers who have either come from sales or last looked at code 10 or more years ago but think they know how to write code.

What can I do to give the impression that I'm grateful for their intervention, but keep it as short as possible so I can get on with my work?

Or, should I be engaging more with the manager to educate them with modern coding techniques and practices? After all, a manager who understands these will be able to talk sensibly to clients and more senior management when discussing the project and its timescales.

答:
It can be very difficult, especially if the manager thinks they're a l33t h@x0r but hasn't coded anything in the last 10 years.

Start by using active listening.  Make sure you understand exactly what point they're trying to get across.  Rephrase it and shoot it back to them so that they know you understood them.  Sometimes this is all they really care about.

If they insist on some implementation, ask yourself why you're refusing them.  There has to be a reason.  It probably breaks some fundamental software design principle... usually separation of concerns.  Know your principles, and know why they're better than the alternative.  Then quote the principles and explain why they should be followed in this case.  That makes the discussion academic.

If you can't figure out why you don't like what they're saying, it's a good opportunity to question your assumptions.

ContentLicense: CC BY-SA 2.5


问:
Inheritance in imperative programming
My first introduction to programming was Java, which was horrible so I learnt Actionscript3 which was nice...  "The point is" OOP was my introduction to programming where by I went on to gain a career in PHP and while I can confidently write programs/scripts in imperative languages I am no where near as comfortable in doing so.

The primary reason is because I am unable to understand how imperative/procedural languages can be extended in the same way OOP languages use polymorphism and substitution.

I am now looking to learn additional languages and may even have a crack at C, only if I can work out the basic principles for substituting functionality.

Can anyone explain the basic principles used to extend the functionality of a library/function without re-writing that entire function.  Because in OOP you would override one method of a class and possibly call the super method to retain some of the original behavior.

答:
If you want a good example of full-fledged OOP in C, take a look at GTK+.  Mostly, your constructors have a lot of boilerplate to initialize things like vtables and keep track of a type hierarchy.  Creating your own object for GTK+ is a good way to learn what most OO languages do for you behind the scenes.

One thing you'll learn by writing some real code is that virtual methods are not as common or necessary as you would think they'd be.  Programmers have a tendency to overuse inheritance.  Most of the time, you know exactly which static function you need to call, and you're just sharing a simple data structure between several different functions.  You extend it simply by creating a new function that works on the same data structure.  This is how the vast majority of procedural code works.

When you do truly need virtual methods, you just add function pointers to that data structure you pass around.  Then perhaps create a wrapper function to encapsulate the ugly function pointer syntax.  See here for an example of how that's done in GObject, the object library of GTK.

If you need to potentially add fields, that data structure you pass around typically has a void* or something where you can store implementation-specific data.

Again, write a real app in GTK+ as a learning exercise, and I think you'll find the patterns somewhat familiar, once you get past the syntax.

Title: Inheritance in imperative programming


问:
What is the best way to initialize a child's reference to its parent?
I'm developing an object model that has lots of different parent/child classes.  Each child object has a reference to its parent object.  I can think of (and have tried) several ways to initialize the parent reference, but I find significant drawbacks to each approach.  Given the approaches described below which is best ... or what is even better.

I'm not going to make sure the code below compiles so please try to see my intention if the code is not syntactically correct.

Note that some of my child class constructors do take parameters (other than parent) even though I don't always show any.

Caller is responsible for setting parent and adding to the same parent.

```<code>class Child {
  public Child(Parent parent) {Parent=parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; set;}
  //children
  private List<Child> _children = new List<Child>();
  public List<Child> Children { get {return _children;} }
}
</code>```

Downside: setting parent is a two-step process for the consumer.

```<code>var child = new Child(parent);
parent.Children.Add(child);
</code>```

Downside: error prone.  Caller can add child to a different parent than was used to initialize the child.

```<code>var child = new Child(parent1);
parent2.Children.Add(child);
</code>```

Parent verifies that caller adds child to parent for which was initialized.

```<code>class Child {
  public Child(Parent parent) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      if (value.Parent != this) throw new Exception();
      _child=value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    if (child.Parent != this) throw new Exception();
    _children.Add(child);
  }
}
</code>```

Downside: Caller still has a two-step process for setting parent.

Downside: runtime checking – reduces performance and adds code to every add/setter.

The parent sets the child's parent reference (to itself) when the child is added/assigned to a parent.  Parent setter is internal.

```<code>class Child {
  public Parent Parent {get; internal set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      value.Parent = this;
      _child = value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    child.Parent = this;
    _children.Add(child);
  }
}
</code>```

Downside: The child is created without a parent reference.  Sometimes initialization/validation requires the parent which means some initialization/validation must be performed in the child’s parent setter.  The code can get complicated.  It would be so much easier to implement the child if it always had its parent reference.

Parent exposes factory add methods so that a child always has a parent reference.  Child ctor is internal.  Parent setter is private.

```<code>class Child {
  internal Child(Parent parent, init-params) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; private set;}
  public void CreateChild(init-params) {
      var child = new Child(this, init-params);
      Child = value;
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public Child AddChild(init-params) {
    var child = new Child(this, init-params);
    _children.Add(child);
    return child;
  }
}
</code>```

Downside: Can’t use initialization syntax such as new Child(){prop = value}.
Instead have to do:

```<code>var c = parent.AddChild();
c.prop = value;
</code>```

Downside: Have to duplicate the parameters of the child constructor in the add-factory methods.

Downside: Can’t use a property setter for a singleton child.  It seems lame that I need a method to set the value but provide read access via a property getter.  It’s lopsided.

Child adds itself to the parent referenced in its constructor.  Child ctor is public.  No public add access from parent.

```<code>//singleton
class Child{
  public Child(ParentWithChild parent) {
    Parent = parent;
    Parent.Child = this;
  }
  public ParentWithChild Parent {get; private set;}
}
class ParentWithChild {
  public Child Child {get; internal set;}
}

//children
class Child {
  public Child(ParentWithChildren parent) {
    Parent = parent;
    Parent._children.Add(this);
  }
  public ParentWithChildren Parent {get; private set;}
}
class ParentWithChildren {
  internal List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
}
</code>```

Downside: calling syntax is not great.  Normally one calls an add method on the parent instead of just creating an object like this:

```<code>var parent = new ParentWithChildren();
new Child(parent); //adds child to parent
new Child(parent);
new Child(parent);
</code>```

And sets a property rather than just creating an object like this:

```<code>var parent = new ParentWithChild();
new Child(parent); // sets parent.Child
</code>```

...

I just learned that SE does not allow some subjective questions and clearly this is a subjective question.  But, maybe it is a good subjective question.

答:
I think your option 3 might be the cleanest. You wrote.

Downside: The child is created without a parent reference.

I don't see that as a downside. In fact, the design of your program can benefit from child objects which can be created without a parent first. For example, it can make testing childs in isolation a lot easier. If a user of your model forgets to add a child to its parent and calls a methods which expects the parent property initialized in your child class, then he gets a null ref exception - which is exactly what you want: an early crash for a wrong usage.

And if you think a child needs its parent attribute to be initialized in the constructor under all circumstances for technical reasons, use something like a "null parent object" as the default value (though this has the risk of masking errors).


问:
Reverse relationships for smaller/better Aggregates?
Let's take an example: we have two related entities, like Question and Choice. This is a poll: it contains of single question that may have 2 or more choices. Each choice can be voted for by users, each vote is stored.

Obviously, on paper, Question would contain a collection of Choices. And probably we would have something like this:

```<code>public class Question {
    List<Choice> choices;
    public void assignChoice(Choice choice) {}
    public List<Choice> getChoices();
}
</code>```

Question is an Aggregate that contains list of other entity, Choice.

Now, if the Choice is a value object, I would be fine. Repository should store the aggregate starting from root, so it would store a root entity and related value objects.

However, here we have aggregate of entities! In that sense I wonder: why do we need to maintain collection in Question at all? I mean, for view, we will have query read-only model. For commands we might not needed it at all.

So we can move from this:

```<code>Question question = new Question("Favorite color?");
question.assignAnswer(new Choice("red"));
question.assignAnswer(new Choice("blue"));

questionRepository.store(question);
</code>```

to:

```<code>Question question = new Question("Favorite color?");
Choice c1 = new Choice(question, "red"); // or just: questionId instead of question?
Choice c2 = new Choice(question, "blue");// the same

questionRepository.store(question);
choiceRepository.store(c1, c2);
</code>```

Now we do not need to 'assign' anything to the Question and we don't need to maintain the collection. For example, this collection may vary - it may be collection of just approved choices, or voted choices, or top 3 voted choices etc. We are not able to expressed what kind of relationship is that just by having getChoices().

So should we even go further to have a rule like:

Don't compose Aggregates with other Entities. Just have a root Entity and value objects. Use reverse relationship to express the connection between aggregate roots.

Make sense?

答:
In my opinion, one reason to let the Question be the aggregate root of the choices (and maintain a list of choices within the question) might be:

A choice does not exist on its own and is always related to a specific question (even as an entity). That's why I think it would make sense to access a choice only through its parent question.

Another advantage could be that whenever you change the question, you can easily check all related choices for invariants. Or when deleting the question, you can simply remove all child choices within the Delete operation of the question itself.

I agree that all of this could also be achieved via a reverse relation, but would be more complicated in my opinion. For example, if I would have a reverse relation and want to delete a question, I would have to iterate through all choices to pick the ones that are related to this specific question.

Concerning your point with the varying collections of choices inside the question:
This is something were you could add some additional filter logic and in that way implement some domain logic within your question, like:

```<code>public class Question {
List<Choice> choices;
public List<Choice> getHighestVotedChoices();// will query choices and return highest voted choices
public List<Choice> getApprovedVotedChoices(); // will filter choices list "approved property"
</code>```

}

Body:
In my opinion, one reason to let the Question be the aggregate root of the choices (and maintain a list of choices within the question) might be:

A choice does not exist on its own and is always related to a specific question (even as an entity). That's why I think it would make sense to access a choice only through its parent question.

Another advantage could be that whenever you change the question, you can easily check all related choices for invariants. Or when deleting the question, you can simply remove all child choices within the Delete operation of the question itself.

I agree that all of this could also be achieved via a reverse relation, but would be more complicated in my opinion. For example, if I would have a reverse relation and want to delete a question, I would have to iterate through all choices to pick the ones that are related to this specific question.

Concerning your point with the varying collections of choices inside the question:
This is something were you could add some additional filter logic and in that way implement some domain logic within your question, like:

public class Question {
List<Choice> choices;
public List<Choice> getHighestVotedChoices();// will query choices and return highest voted choices
public List<Choice> getApprovedVotedChoices(); // will filter choices list "approved property"

}


问:
What are your decision critera in C++ to make something a data member or virtual method?
(Figured this was too subjective for SO, so posting here...)

I have some behavior that I can implement in various ways.  At least two methods are shows in the code snippet below.  Presume that the m_well data member is correctly set somehow at object construction time.

```<code>struct Behavior
{
    virtual bool behavesWell() { return true; }

private:
    bool m_well;
public:
    bool behavesMemberWell() { return m_well; }
};

struct OtherBehavior : public Behavior
{
    virtual bool behavesWell() { return false; }
};
</code>```

Obviously the one relies upon virtual dispatch, and the other merely the return of a data member.

A third, non-shown method would likely have the non-virtual public member function not return a fixed data member, but instead call a virtual - lets leave that aside for the purpose of this please.

What would lead you to one or other other of these two methods of implementing functionality, such that a user of this class can interrogate an object's behavior?

答:
As far as I can see, you've got a couple of conflicting issues here, which may be clarified if you could tell us for what purpose you're doing this? Is the code going to be used by you/your team, or are you designing an API for consumption by others?

If you're just trying to design a good interface to your functionality, put yourself in the shoes of the clients of your functions - write some unit tests. If when writing the unit tests, anything seems awkward or non-obvious, your design needs improving.

If your class is meant for sub-classing, then you don't want public data members, or protected data members for that matter. Data members that are private can be changed at any time without breaking the sub-classes, whereas changes to protected members (potentially) break sub-classes and changes to public data members (quite likely) break client code. It may seem tedious to have a getter/setter pair of methods to manipulate a data member, but it's worth it if you want to keep the implementation flexible and not design yourself into a corner.

The virtual methods would indicate that you're considering handing the client of your class an interface which would be pure virtual. If this is the case, then you can't have data members in an abstract (pure virtual) class, so that leads you to virtual methods with virtual method calls to get/set data items.


答:
In short: If Client cares about the parameters after the fact, then it should create a defensive deep copy of the map (not only the map, but also of the values). If Service needs to modify the collection, then it should create a defensive copy. But we can do better...

To safely pass the Map (though not to safely pass its contents), Client does not need to copy the map, it can use Collections.unmodifiableMap() to create an unmodifiable view.

If Client cares about the map after the fact, then it probably also cares about the contents of the map. Does Client know how to make a defensive copy of all subclasses of Object that will be included in the map? If the actual Objects being used are immutable types, then Client doesn't need to know how to make a defensive copy of them, and passing the unmodifiable collection is sufficient.

If the actual Objects being used are mutable types, then Client needs to make a deep copy of them, or needs to send copies (or immutables) of whatever Service is going to do with the map. For example, if Service actually intends to call .toString() on all Objects in the map, then maybe the contract can be changed such that Service accepts a Map<String, String>. Maybe Service is a bit more clever, and can also handle Objects that might implement Collection, and uses the .toString() method for non-collections, but iterates over collections and calls the .toString() on each of those. If that is the case, perhaps Client can contain the logic for getting to that step, and the contract changed to Map<String, List<String>>; remember to pass unmodifiable views of the collections, and not the collections themselves.

Wherever possible, I prefer to pass unmodifiable views or immutable collections (for example, from the Guava library), containing immutable objects. If Service actually needs to modify the collection it should be making a copy (because it should know that side effects are generally undesirable), deep if necessary. You will find out in testing if Service actually does produce side effects, because it will throw an exception when trying to modify the unmodifiable/immutable collection, in which case Client needs to create a mutable copy of the collection, pass that, and then never use it again.

Title: Defensive copy in the client class or in the service class?

Body:
I have one service method that receive parameters as a Map. I will need to add new attributes to this map inside the service. If I pass the original Map object to the parameter instead of a copy, the original parameters object will be changed.

My question here is: which class is responsible for maintain the integrity of the parameter object?

Should the Client class pass a copy in case the Service changes the parameters, or should the 'Servicedo a copy of the parameters to avoid hurting theClient`?

```<code>public class Client{
    public void search(){
         Map<String, Object> parameters = new HashMap<>();

         // defensive parameters copy here?
         new Service().search(parameters);
         // parameters can be changed if I don't use a defensive copy
    }
}

public class Service{
    public ... search(Map<String, Object> parameters){
        // defensive parameters copy here?
        parameters.put("newParam", 1);
    }
}
</code>```


问:
Does scrum involve writing tests before code?
I just read that in XP, tests are written before code. Scrum is a different Agile Methodology but does scrum also involve writing tests before code?</p>

答:
Scrum is a different Agile Methodology but does scrum also involve writing tests before code?

Not necessarily. Depending on your locale, writing (unit) tests first is "Test Driven Development" (TDD) or simply "Test First Development". Either way, it is an implementation detail of your development process (how you write the code), not an immutable part of your project management process (Scrum; How do you get people organized to make something useful).

I am not particularly familiar with XP, so cannot speak to it.


答:
I just read that in XP, tests are written before code.

That's not what that's about. Yes, you write tests before the code, but that's a consequence, not the essence. The essence is that failing tests drive the development process, the design and the code. And in order to drive those, they obviously need to exist first.

Scrum is a different Agile Methodology but does scrum also involve writing tests before code?

No, it doesn't. In fact, Scrum doesn't involve code at all. eXtreme Programming, as the name suggests, is a Methodology for Software Projects. Scrum is a Methodology for Projects. (More precisely: it is a Framework for creating Methodologies for Projects.) It could be a design project, a research project, an architecture project (as in "house", not "software architecture"), anything. Scrum doesn't concern itself with software at all.

When using Scrum for Software Development, it is very common to combine it with XP in such a way that the Project Management Practices from XP are ignored and the Software Development Practices from XP are integrated with the Project Management Practices from Scrum. IOW: whenever Scrum doesn't say anything in particular about a certain issue, you look to XP for answers.

The other way around, some teams augment XP with ideas from Scrum.

Title: Does scrum involve writing tests before code?

Body: I just read that in XP, tests are written before code. Scrum is a different Agile Methodology but does scrum also involve writing tests before code?</p>


答:
The problem here is that your manager obviously feels COMPETENT, when he IS NOT.

I've had such experience before and for me it worked if I subtly showed the guy that programming wasn't his domain.

For example, I might go at great lengths to explain a specific piece of code, descending all the way into talking about hash tables and linked lists, big O notation etc., until his face shows that he really feels unable to follow any more of your discussion.

So if you can pull this off you will most likely get rid of the silly questions and micromanagement.

Title: How do I cope with a manager who’s always interfering in what I do, but doesn’t really understand it?

Body:
We've all had them, managers who have either come from sales or last looked at code 10 or more years ago but think they know how to write code.

What can I do to give the impression that I'm grateful for their intervention, but keep it as short as possible so I can get on with my work?

Or, should I be engaging more with the manager to educate them with modern coding techniques and practices? After all, a manager who understands these will be able to talk sensibly to clients and more senior management when discussing the project and its timescales.


答:
I think the easiest way to understand this is by looking at a simple example in C: the qsort function of the standard C library. As a user of that lib, you can provide an arbitrary comparison function to qsort here without touching or recompiling the library.

Another good example was shown in this former SO post. It exaplains how to build the equivalent of a String class in C, and how to emulate inheritance.

Title: Inheritance in imperative programming

Body:
My first introduction to programming was Java, which was horrible so I learnt Actionscript3 which was nice...  "The point is" OOP was my introduction to programming where by I went on to gain a career in PHP and while I can confidently write programs/scripts in imperative languages I am no where near as comfortable in doing so.

The primary reason is because I am unable to understand how imperative/procedural languages can be extended in the same way OOP languages use polymorphism and substitution.

I am now looking to learn additional languages and may even have a crack at C, only if I can work out the basic principles for substituting functionality.

Can anyone explain the basic principles used to extend the functionality of a library/function without re-writing that entire function.  Because in OOP you would override one method of a class and possibly call the super method to retain some of the original behavior.


问:
DDD: storing additional data with the model
Our domain is operated within certain context. This context is described by some additional values, like a fooId - id that does not have a meaning in domain business, but it's more a flavor for the whole application and modules.

I need to store this fooId with entities, like Book. But I do not want Book to have this id in the class, since number of flags depends on the context. This flags are available in the repo, so I am able to store them to the db.

How to model this?

I can have a factory for Book that actually creates a Book implementation that has all the additional fields. Repository would work only with these implementations. User is unaware of the additional fields. But he always need to call the Factory if he wants to create the object.

How does this feel? I do not see any other way to make this, and yet to have Book not aware of additional flag(s).

The additional flags fooId I am talking about may be e.g. groupId. We can say that our software is dividied into modules, and each module may create it's artifacts (like Books) in it's own group. However, group is 'flavor' of the repository - services and model should not be aware of the groups, as we can have mono-group repo, where everything is stored in single group.

答:
Problems of this kind can be solved by providing a graphical version of the model (for example, in an UML CASE tool), which shows just the domain attributes, together with a code generator which generates the implementation of class interfaces, database scripts etc.

The code generator will provide you silently with any of your "technical attributes", so at the implementation level, they are visible and available, and on the "domain experts level", the attributes are invisible. Moreover, your code generator can provide different code and different attributes for different contexts.


问:
Permutation tests for large sequences
I would like to perform a permutation test on a particularly large data set, i.e. around 4 million entries. Basically, I need to get some number of random permutations of this data set. Usual way to do this, is a Fisher-Yates shuffle, but it's pretty much limited by period of a PRNG. That is, to a sequence no longer than around 2080.

Is there a solution to randomly permuting much larger sequences?

EDIT:
Here is an interesting related discussion on random shuffle algorithms and how much are they limited by RNG.

答:
I think that something is unclear in the question.  Are you asking:

1) Can I generate a large number of random permutations of 4000000 elements using a PRNG, where a large number is something like 100000000000 random permutations?

Or

2) Can I generate EVERY random permutation of 4000000 elements using a PRNG?

The answer to the first question is yes, and to the second question is no.  Take Mersenne Twister as an example.  To generate one random permutation, you need to generate 8.1e+7 random bits, or around 2^21 random 32-bit numbers.  Since the period of Mersenne Twister is 2^19997, you can continue and generate a whopping 2^19976 random permutations, many more than you will ever need.

However, if you wanted generate EVERY possible random permutation, you would need to generate at least 2^8100000 random permutations, which is more than 2^19976.  But there isn't any practical reason for generating every possible permutation.

Regarding the other question in the comments about whether a random shuffle would sample uniformly from all possible permutations: the answer is yes.  As long as your RNG can generate 80000000 consecutive uniformly random bits, which Mersenne Twister can, then your sampling will be uniform.

Title: Permutation tests for large sequences


问:
Safe serial numbers generation
I want to generate a 6 digits serial number, ranged from A-Z (only uppercase allow), e.g.

```<code>serial = "ABCDEF"
</code>```

the problem is, some letters are considered confusing to others letters/numbers, e.g.

```<code>U <-> V
O <-> 0 (number)
I <-> 1 (number)
</code>```

So, are there any existing set of safe letters can be used as seed to generate a safe serial number?

答:
Depending on the font you use:

B (not visually very different from the digit 8)

C (with some fonts, the difference with O may be barely noticeable),

D (for the same reason as C),

I (is it the digit 1?),

O (is it the digit 0?),

Q (with some fonts, the difference with O may be barely noticeable),

Note that you shouldn't exclude just one character (say O in 0/O) in a pair, but both (O and 0). Users won't know you excluded them, unless you make it obvious by triggering some visual response when such character is entered in the text-box. As an illustration, a few years ago, I've written a custom CAPTCHA where, indeed, characters like "B" were excluded. Below the CAPTCHA, there was a piece of text:

The image doesn't contain the following characters: B, D, I and O.

According to the logs, there were still many users who tried those four characters. Modifying the CAPTCHA to:

The image doesn't contain the following characters B, D, I, O, 0, 1 and 8.

helped, since there was no longer any ambiguity. Later, removing the piece of text haven't decreased the success ratio.

Instead of excluding letters, you may also try those alternatives:

Chose a good font which is particularly clear. For example, Slashed zero page on Wikipedia discusses the particular aspect of "0/O". Another example is that when written like this: 0/O, it becomes obvious which one is the digit and which one is the capital letter.

If the serial is not printed on the software package, but rather available in digital form, make it easy to copy-paste. For example, many products which have 25-characters serials separated in 5 groups by dashes use 5 text-boxes, but let you to copy-paste the entire serial number, handling dashes automatically.

Use digits only. In this case, either start all serial numbers by a digit from 1 to 9, or handle the case where the user doesn't enter the leading zeroes: when having to enter the serial such as 003197, some users will enter it as-is, while others will enter only the last four digits.

Also, put spaces or dashes in your serials. Compare the ones on the left with the ones on the right:

```<code>5F91PS           5F-91-PS
CY4BIW           CY-4B-IW
ZHL0A2           ZH-L0-A2
</code>```

The ones on the right are easier to type and to spell on a phone (this is also the reason why Microsoft's serials contain dashes, although their length (25 characters) makes them very difficult to type anyway).

Title: Safe serial numbers generation

Body:
Depending on the font you use:

B (not visually very different from the digit 8)

C (with some fonts, the difference with O may be barely noticeable),

D (for the same reason as C),

I (is it the digit 1?),

O (is it the digit 0?),

Q (with some fonts, the difference with O may be barely noticeable),

Note that you shouldn't exclude just one character (say O in 0/O) in a pair, but both (O and 0). Users won't know you excluded them, unless you make it obvious by triggering some visual response when such character is entered in the text-box. As an illustration, a few years ago, I've written a custom CAPTCHA where, indeed, characters like "B" were excluded. Below the CAPTCHA, there was a piece of text:

The image doesn't contain the following characters: B, D, I and O.

According to the logs, there were still many users who tried those four characters. Modifying the CAPTCHA to:

The image doesn't contain the following characters B, D, I, O, 0, 1 and 8.

helped, since there was no longer any ambiguity. Later, removing the piece of text haven't decreased the success ratio.

Instead of excluding letters, you may also try those alternatives:

Chose a good font which is particularly clear. For example, Slashed zero page on Wikipedia discusses the particular aspect of "0/O". Another example is that when written like this: 0/O, it becomes obvious which one is the digit and which one is the capital letter.

If the serial is not printed on the software package, but rather available in digital form, make it easy to copy-paste. For example, many products which have 25-characters serials separated in 5 groups by dashes use 5 text-boxes, but let you to copy-paste the entire serial number, handling dashes automatically.

Use digits only. In this case, either start all serial numbers by a digit from 1 to 9, or handle the case where the user doesn't enter the leading zeroes: when having to enter the serial such as 003197, some users will enter it as-is, while others will enter only the last four digits.

Also, put spaces or dashes in your serials. Compare the ones on the left with the ones on the right:

5F91PS           5F-91-PS
CY4BIW           CY-4B-IW
ZHL0A2           ZH-L0-A2

The ones on the right are easier to type and to spell on a phone (this is also the reason why Microsoft's serials contain dashes, although their length (25 characters) makes them very difficult to type anyway).


问:
How should I connect to my php framework to use methods written in the framework, in a framework agnostic environment?
My company runs 2 websites, a public facing website for clients, and an employee intranet. The intranet is used as a backend for employees to edit and maintain various parts of the public website. Both are written in PHP. The intranet is years older, and was designed using an inhouse framework. We have recently created a new public website, and because of the opportunity to "start from scratch" with it, we designed it using a PHP framework (Kohana). We knew from the beginning that there would be implementation issues with getting the intranet to interact with the public site, and vice-versa. We are now at that point.

There are a few different ways we have been able to make things work: For direct data manipulation, both use mysql, so the query builder in Kohana can manipulate the same data as the straight mysqli queries of the intranet. But beyond that, when the public site needs to use certain auditing methods written on the intranet framework, or when the intranet needs to send an automatic email written in Kohana, or use any number of other methods and functions, we have

1- Included one framework within the other, to have access to both. Problems with this are:

a. Both rely on object buffering to prepare output, and are constantly starting and ending buffers at odd times.

b. Conflicting class names being autoloaded

c. autoloaders overwriting each other

d. errors designed to be handled in one way are being handled improperly by the other framework's error handler.

e. any number of other incompatibility issues

We have gotten around these on a case by case basis, but it has been a nightmare

2- Using a remote API. We have written webservice methods on each server, and the other framework makes a cURL request of the other server. Problems with this are:

a. The added work of protecting the API and authenticating requests

b. the need to write service methods

c. The overhead of having to make http requests instead of loading files locally

3- Using a local api. Similar to the above, except the framework is included on the same server, and the api methods are written in shell scripts which output data to be read by the calling script via shell_exec.
This alleviates the need for authentication, but it seems like an ugly, hacky way of doing things

We don't want to rewrite the intranet using a proper framework. It would take an incredible amount of time that we do not have. Is there a better way to do this, or at least a more "standard" or "conventional" way of dealing with this problem? Or are we stuck hacking away at it like we currently have been?

答:
firstly for multiple classes with the same name, I would suggest that you use namespaces to clear out what class in which namespace is supposed to handle it.

most frameworks error handlers can be overwritten to achieve custom error handling , I'm using Yii and at least that is supporting it.

and also you can use the old frameworks working parts and include them in your new framework and reuse your code.


问:
Can a table be both Fact and Dimension
Ok, I am a newbie and don't really think "dimensionally" yet, I have most of my initial schema roughed out but I keep flipping back and forth on one table.

I have a Contract table and it has a quantity column (tonnes), and a net price column,  which need to be summed up a bunch of different ways, and the contract has lots of foreign keys (producer, commodity, futures month etc.) and dates so it appears to be a fact table. Also the contract is never updated, if that makes a difference.

However, we create cash tickets which we use to pay out part or all of the contract and they have a contract ID on them so then the contract looks like a dimension in the cash ticket's star schema.

Is this a problem? Any ideas on the process to resolve this, because people don't seem to like the idea of joining two fact tables.

Should I put producerId and commodityId on the cash ticket? It would seem really weird not to have a contractID on it.

答:
I have a Contract ... it appears to be a fact table.

I think this is what is causing the confusion. As James K. Lowden pointed out, forget relational theory.

Try this:

Create a ContractDim table with a contract_PK, the original contractID and anything else that relates to the contract EXCEPT the columns that will be summed up

Create a SalesFact table (or revenue) with all the foreign keys and columns to be summed up like: tonnes and net price. I would pre-calculate some sort of total as well.

This way your cash ticket can link to contractdim (start of a snow-flake schema) or you can have a cash ticket foreign key in your fact table to link directly to the sales values.

You can do the same with CashTicketDim and PayoutFact. This way you would never link the SalesFact to the PayoutFact.

Title: Can a table be both Fact and Dimension


问:
Separation of retrieving data and business objects between DAL and BLL Layers
I did some research before posting this question. Among other questions or post, one of those is provided below. I could not get a clear mind how to determine..

Business Objects within a Data Access Layer

I have a Repository and the Business Layers call the repository to retrieve the data. For example, say I have the following classes for BLL and DAL:

```<code>class BllCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public BllAddress Address {get; set;}
}

class BllAddress
{
     public int AddressId {get; set;}
     public String Street {get; set;}
     public String City {get; set;}
     public String ZipCode {get; set; }
}

class DalCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public int AddressID {get; set;}
}

class DalAddress
{
     public int AddressId {get; set;}
     public String Street {get; set;}
     public String City {get; set;}
     public String ZipCode {get; set; }
}
</code>```

If the BLL wants to retrieve a Customer object, it would call GetCustomerById(customerId) in DAL.

The following are my concerns I could not get a clear mind:

I cannot see how to determine what object the GetCustomerById in DAL should return? Should it return BllCustomer or DalCustomer?

Where should be the retrieving (and/or converting to Business object) of the address associated with the customer?

If the DAL returns Dal objects then, the logic to retrieve and fill in the Address can only be in the BLL. If the DAL returns BLL objects, then the logic to retrieve and fill in the Address can be either in the BLL or DAL. Currently the DAL is returning the Business Objects and the logic to fill it in is in the DAL.

From what I read, I guess there is no right or wrong. From the link included above, there are people saying one way and the others are saying the other way. But how do I determine which would works best for my case?

Any help would be appreciated.

答:
Typically, the DAL has no knowledge of the BLL. Think of it this way, a different application with a different BLL could use the same DAL. A Payables application/module and a Receivables app for the same company would share data (clients, charges, payments, etc.). Trying to have one DLL have knowledge of more than one BLL would be very difficult and unnecessary. This would also allow you to change your data storage with no impact on the BLL (as long as you don't break the interfaces).

You now can pass a DAL object to the BLL or you could create a third set of objects: Entity. These would contain just the values to be passed around together. The DAL would reference the entity and interact with your storage/database and the BLL would handle all the logic and reference the DAL.

```<code>class EntCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public BllAddress Address {get; set;}
}
class BllCustomer
{
   //reference EntCustomer, DalCustomer and handle business rules/logic
}

class DalCustomer
{
   //reference EntCustomer and interact with data storage
}
</code>```

Body:
Typically, the DAL has no knowledge of the BLL. Think of it this way, a different application with a different BLL could use the same DAL. A Payables application/module and a Receivables app for the same company would share data (clients, charges, payments, etc.). Trying to have one DLL have knowledge of more than one BLL would be very difficult and unnecessary. This would also allow you to change your data storage with no impact on the BLL (as long as you don't break the interfaces).

You now can pass a DAL object to the BLL or you could create a third set of objects: Entity. These would contain just the values to be passed around together. The DAL would reference the entity and interact with your storage/database and the BLL would handle all the logic and reference the DAL.

class EntCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public BllAddress Address {get; set;}
}
class BllCustomer
{
   //reference EntCustomer, DalCustomer and handle business rules/logic
}

class DalCustomer
{
   //reference EntCustomer and interact with data storage
}


问:
Why REST Api do not follow the Facade design pattern
In comparing REST [api] structure with a OO model, I see these similarities:

Both:

Are data oriented

REST = Resources

OO = Objects

Surround operation around data

REST = surround VERBS (Get, Post, ...) around resources

OO = promote operation around objects by encapsulation

However, good OO practices do not always stand on REST apis when trying to apply the facade pattern for instance:
   in REST, you do not have 1 controller to handle all requests AND you do not hide internal object complexity.

On the contrary, REST promotes resources publishing of all relations with a resource and other on at least two forms:

via resource hierarchy relations (A contact of id 43 is composed of an address 453) : /api/contacts/43/addresses/453

via links in a REST json response:

```<code>>> GET /api/contacts/43
<< HTTP Response {
   id: 43, ...
   addresses: [{
      id: 453, ...
   }],
   links: [{
      favoriteAddress: {
          id: 453
      }
   }]
}
</code>```

Coming back to OO, the facade design pattern respect a Low Coupling between an objectA and its 'objectB client' and High Cohesion for this objectA and its internal object composition (objectC, objectD).  With the objectA interface, this allow a developer to limit impact on objectB of the objectA internal changes (in objectC and objectD), as long as the objectA api (operations) are still respected.

In REST, the data (resource), the relations (links), and the behavior (verbs) are exploded in different elements and available to the web.

Playing with REST, I always have an impact on code changes between my client and server:   Because I have High Coupling between my Backbone.js requests and Low Cohesion between resources.

I never figured out how to let my Backbone.js javascript application deal with "REST resources and features" discovery promoted by REST links.  I understand that the WWW is meant to be served by multi servers, and that the OO elements had to be exploded to be serviced by many hosts in there, but for a simple scenario like "saving" a page showing a contact with its addresses, I end up with:

```<code>GET /api/contacts/43?embed=(addresses)
[save button pressed]
PUT /api/contacts/43
PUT /api/contacts/43/addresses/453
</code>```

which lead me to move the saving action atomic transactional responsibility on the browsers applications (since two resources can be addressed separately).

With this in mind, if I cannot simplify my development (Facade design patterns not applicable), and if I bring more complexity to my client (handling transactional atomic save), where is the benefit of being RESTful ?

答:
Thats because facades are a 'kludge'; you should take a look at 'api abstraction' and 'api chaining'. The api is a combination of two sets of functionality : I/O and resource management. Locally, the I/O is fine but within a distributed architecture (ie proxy, api gate, message queue, etc) the I/O is shared and thus the data and functionality becomes duplicated and entangled. This leades to an architectural cross-cutting concerns. This plagues ALL existing apis.

The only way to resolve this is to abstract I/O functionality for the API to a pre/post handler (like a handlerIntercepter in Spring/Grails or a filter in Rails) so functionality can be used as a monad and shared across instances and external tooling. Data for request/response also needs to be externalized in an object so it can be shared and reloaded as well.

http://www.slideshare.net/bobdobbes/api-abstraction-api-chaining

OwnerDisplayName: Alain


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

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

答:
No, you shouldn't

With two exceptions:

Content you want to be search engine indexable. (That doesn't mean it has to look good - as long as the links work and the content is discoverable.)

Simple mobile sites that must work on all devices. (Some BlackBerries have JS disabled by default, and many non-smart phones often don't have it at all.)

For desktop and touch phone websites, Javascript provides an amazingly rich user experience. There is a reason all top websites make extensive use of AJAX and Javascript. All current browsers support it. Embrace it!

As someone who has sweated in the past to make an entire website work with Javascript disabled, I can assure anyone that they'll end up degrading the experience for the 99% in order to please the 1%.

Rather just stick in a NOSCRIPT tag that tells those users to enable Javascript. They'll be used to it.


问:
What is the term ("metric") for the degree of unstructuredness due to many changes?
Is there a specific term (name of a "metric") that represents the growing level of unstructuredness (or just plain badness) of a s/w component that is caused by too many changes, by too many people, over too long a time interval?</p>

答:
Technical debt ?

Technical debt is a recent metaphor referring to the eventual consequences of poor system design, software architecture or software development within a codebase. The debt can be thought of as work that needs to be done before a particular job can be considered complete or proper. If the debt is not repaid, then it will keep on accumulating interest, making it hard to implement changes later on.

But it seems to refer more to bad changes instead of many changes.


问:
Does code formatting have to matter?
UPDATE: an issue would arise from stuff that is not strictly defined by a formatter, like consecutive empty lines etc., that would get lost in the process (local to server to local reformatting) which would annoy people (me as well :)

I'm used to adopting some shared code formatter so my question is not about "should I submit to that?"

I wonder does this (code formatting) have to matter at all? Isn't it possible to have your repository store your commmits in some "default" formatting? You would never get to see what that style looks like, because every time you checkout all the sources get saved to your HDD after getting reformatted using YOUR formatter. Also every time you would browse the repository your client would show you the source reformatted using YOUR formatter. Also all diffs would be done after reformatting using YOUR formatter.

Is this possible to do? (E.g. client plugins, repository configuration, etc.)

答:
There's an excellent tool uncrustify that takes a description of the source code formatting from a config file and outputs a formatted file as per specification in config file. However, there's a few problems with this approach, most obvious and important are:

File stored in the repository will be different than view of your file making looking into diffs much harder.

It will be much harder for you to keep whitespace changes separated from the important commits.

I'm sure there's more.

Title: Does code formatting have to matter?


答:
Having no rules is not freedom, it's just chaos. How would one write a book on programming language without any coding standards? Can you imagine each book having completely different formatting?

I have personal preferences about how the code should look like, but my personality is not really important when I work in a team. Collaboration is important, and coding standards make it possible, not just easier.

Is this possible to do? (E.g. client plugins, repository configuration, etc.)

Yes, but with worse performance, bugs, and additional setup phase. I have enough of configuration and plugins thanks to Maven, so I better stick with good old discipline.

However, there is an idea about storing a program not as it's source code, but as it's syntax tree. Like language-agnostic ASTs and stuff.

Update: On comments.

I see and understand your point, but I still believe my concerns are true.

Imagine you have those magic plugins which abstract away the formatting. You team up and code with other people without knowing about their preferences, and it's all double rainbow all across the sky =)

Then, one of your colleagues tells you something like: "I'm writing a book about programming, need your help." Then she sends you a manuscript and you see she's gone completely opposite direction with not only formatting, but even with concrete syntax. Imagine she invented something like CoffeeScript on top of the language you both use: keywords are different, shorter syntax constructs, etc. It's totally possible when you have such a magic plugin and people will do it (because of Murthy's law, and it ain't no joke).

So, you can't help her, unless you both reject your personal preferences and use "standard", "default" formatting and concrete syntax. Ta-a-da-a!

So I claim:

If there are N people and each one is allowed to have his/her own concrete syntax and formatting styles, there eventually be N different styles.

If there are people using those different styles, they would either write books using those different styles, or agree on using "default".

If you end up using "default" anyway to be able to collaborate, why bother with customization?

I'm not insisting on "purity" or something. I work with code which often has a mix of different formatting styles. But that's mostly just slight differences which don't affect the language. I'm totally fine with that.

But I don't want to learn a new language just to feed someone's ego (my own too, for that matter). I sometimes just copy-paste code in my instant messenger and I don't want to have any plugin in it (on both mine and recipient sides, I'll have you know) to send a snippet.

If you have such a magic plugin in your IDE, you have to have such plugins everywhere you want to stick you code to. That's nothing more than additional problems.

Summary: you can do so, but you shouldn't. Standards are better when customization. Conventions are better than plugins.

Update 2:

Image person A prefers to put an opening brace on a separate line:

```<code>while (true) // endless loop
{
</code>```

Then this code can be stores in some kind of syntax tree and then shown to person B, who uses Egyptian style. That can be done either like so:

```<code>while (true) /* endless loop */ {
</code>```

or so:

```<code>// endless loop
while (true) {
</code>```

And this second one has different order of tokens.

This shows that not all syntax constructs would fit in this model. So the language should be probably restricted in many ways to provide ability to customize formatting. Still I think it is possible, since there are programming languages like Google's Blockly which have completely different concrete and "stored" syntaxes.

By the way, Blockly is a proof of concept, since you totally can customize the frontend to fit your artistic taste.

Title: Does code formatting have to matter?

Body:
UPDATE: an issue would arise from stuff that is not strictly defined by a formatter, like consecutive empty lines etc., that would get lost in the process (local to server to local reformatting) which would annoy people (me as well :)

I'm used to adopting some shared code formatter so my question is not about "should I submit to that?"

I wonder does this (code formatting) have to matter at all? Isn't it possible to have your repository store your commmits in some "default" formatting? You would never get to see what that style looks like, because every time you checkout all the sources get saved to your HDD after getting reformatted using YOUR formatter. Also every time you would browse the repository your client would show you the source reformatted using YOUR formatter. Also all diffs would be done after reformatting using YOUR formatter.

Is this possible to do? (E.g. client plugins, repository configuration, etc.)

Body:
Having no rules is not freedom, it's just chaos. How would one write a book on programming language without any coding standards? Can you imagine each book having completely different formatting?

I have personal preferences about how the code should look like, but my personality is not really important when I work in a team. Collaboration is important, and coding standards make it possible, not just easier.

Is this possible to do? (E.g. client plugins, repository configuration, etc.)

Yes, but with worse performance, bugs, and additional setup phase. I have enough of configuration and plugins thanks to Maven, so I better stick with good old discipline.

However, there is an idea about storing a program not as it's source code, but as it's syntax tree. Like language-agnostic ASTs and stuff.

Update: On comments.

I see and understand your point, but I still believe my concerns are true.

Imagine you have those magic plugins which abstract away the formatting. You team up and code with other people without knowing about their preferences, and it's all double rainbow all across the sky =)

Then, one of your colleagues tells you something like: "I'm writing a book about programming, need your help." Then she sends you a manuscript and you see she's gone completely opposite direction with not only formatting, but even with concrete syntax. Imagine she invented something like CoffeeScript on top of the language you both use: keywords are different, shorter syntax constructs, etc. It's totally possible when you have such a magic plugin and people will do it (because of Murthy's law, and it ain't no joke).

So, you can't help her, unless you both reject your personal preferences and use "standard", "default" formatting and concrete syntax. Ta-a-da-a!

So I claim:

If there are N people and each one is allowed to have his/her own concrete syntax and formatting styles, there eventually be N different styles.

If there are people using those different styles, they would either write books using those different styles, or agree on using "default".

If you end up using "default" anyway to be able to collaborate, why bother with customization?

I'm not insisting on "purity" or something. I work with code which often has a mix of different formatting styles. But that's mostly just slight differences which don't affect the language. I'm totally fine with that.

But I don't want to learn a new language just to feed someone's ego (my own too, for that matter). I sometimes just copy-paste code in my instant messenger and I don't want to have any plugin in it (on both mine and recipient sides, I'll have you know) to send a snippet.

If you have such a magic plugin in your IDE, you have to have such plugins everywhere you want to stick you code to. That's nothing more than additional problems.

Summary: you can do so, but you shouldn't. Standards are better when customization. Conventions are better than plugins.

Update 2:

Image person A prefers to put an opening brace on a separate line:

while (true) // endless loop
{

Then this code can be stores in some kind of syntax tree and then shown to person B, who uses Egyptian style. That can be done either like so:

while (true) /* endless loop */ {

or so:

// endless loop
while (true) {

And this second one has different order of tokens.

This shows that not all syntax constructs would fit in this model. So the language should be probably restricted in many ways to provide ability to customize formatting. Still I think it is possible, since there are programming languages like Google's Blockly which have completely different concrete and "stored" syntaxes.

By the way, Blockly is a proof of concept, since you totally can customize the frontend to fit your artistic taste.


问:
Software engineering - "Precious project" syndrome?
I recently failed three projects with a similar pattern:

I had to work on each of them alone

With time I started to take the project too personally, like it is my spiritual child, and I tried to make it perfect

Soon my progress slowed to a halt, and effected everyone, which in turn made me feel more guilty and desired to make things even more perfect!

Eventually I had to drop it in shame.

I want to ask if there's anyone who have suffered the same:

How do you overcome it?

If you absolutely cannot work on a solo project then how do you explain it to your boss so that it doesn't seem like you're incompetent?

答:
How do you overcome it?

I see (intentionally seeking) other people making mistakes and being fine with that. That tones down my fear of mistakes.

If you absolutely cannot work on a solo project then how do you explain it to your boss so that it doesn't seem like you're incompetent?

I don't know how it looks from the eyes of my boss. I can't read others' minds. If I think I look incompetent, that's just my fear of looking incompetent comes into play. And if I'm really incompetent and try to pretend I'm not, I screw up in the end anyway, so I better confess.


问:
Autoreleasing objects in Reference Counting Systems
I'm experimenting a bit in C and I'm trying to implement my own Reference Counting System. I've mainly worked with Objective-C in the past but AFAIK autoreleasing objects is something that is unique to Objective-C.

The problem with reference counting is that, when returning objects from methods, there is no correct way to release the object and return it at the same time. If the reference count is 1 releasing it will deallocate the object before it can be returned.

```<code>void *testMethod() {
   return release(object); // Object is already deallocated :'(
}
</code>```

Therefore, by autoreleasing an object, it is not deallocated instantly. Instead, when the autorelease pool is drained, all the objects that were autorelease in the scope of the autorelease pool get released.

```<code>void *testMethod() {
   return autorelease(object);
}

@autorelease {
    object = retain(testMethod());
}
</code>```

As you can see above, the object gets released when the @autorelease {} block ends, which is after the object has been retained again. This solves the problem.

This solution however can become quite a bottleneck. You have to store every object that gets autoreleased in an array with no predeterminable size, requiring you to realloc a lot of times. Loops that require an autorelease pool have become much slower because of this.

Is there a better solution to this problem?

Or rather, are there any other solutions to this problem at all?

答:
The usual way is to retain for the calling code, To make it consistent you should do it for all objects that you return.

```<code>//popFromQueue will remove from the queue and pass the buck to the calling code
Foo* pop(FooQueue* q){
    Node* foo = q.head;
    q->head = foo->next;
    foo->next=null;//make sure new head isn't released; could have also retain the new head instead
    Foo retValue = retain(foo->value);
    release(foo);//will release next and value
    return retValue; //passes our ownership to calling code
}
// peekQueue will return the head value and give ownership to calling code
Foo* peek(FooQueue q){
    return retain(q->head->value);//add a retain and pass to calling code
}
</code>```

For example when you create an object: Foo* foo = createFoo(); it already has been retained once to let the calling code get ownership.

This has the downside that all returned values need to be released and you need to ensure they have been retianed before returning them.

Body:
The usual way is to retain for the calling code, To make it consistent you should do it for all objects that you return.

//popFromQueue will remove from the queue and pass the buck to the calling code
Foo* pop(FooQueue* q){
    Node* foo = q.head;
    q->head = foo->next;
    foo->next=null;//make sure new head isn't released; could have also retain the new head instead
    Foo retValue = retain(foo->value);
    release(foo);//will release next and value
    return retValue; //passes our ownership to calling code
}
// peekQueue will return the head value and give ownership to calling code
Foo* peek(FooQueue q){
    return retain(q->head->value);//add a retain and pass to calling code
}

For example when you create an object: Foo* foo = createFoo(); it already has been retained once to let the calling code get ownership.

This has the downside that all returned values need to be released and you need to ensure they have been retianed before returning them.


问:
Does code format affect performance?
I think I have came across a few times when I reformat some segment of code, it performed the way I wanted it to other than the other poorly formatted segment of code? Does code format affect performance? Or is that a myth?</p>

答:
In a compiled language, any superfluous whitespaces, comments or other elements without syntactical meaning do not survive the tokenization step of the compilation, so it doesn't make a difference at all for the resulting binary (at least for the executable parts - some compilers might embed original sourcecode in the generated binary for debugging purposes, but those parts of the binary aren't executed).

In purely interpreted languages, the interpreter needs to parse all whitespaces. So formating can actually slow down the interpreter a tiny bit. But more advanced* interpreters usually compile the code in-memory to an optimized representation ("bytecode") before they execute it . In this step, whitespaces are usually also stripped, so it shouldn't matter for runtime either.

*in this case "more advanced" means "anything you would use in a 2014 production environment".

Title: Does code format affect performance?


答:
I have three suggestions:

Entropy (but in its physical meaning and not in its information science meaning)
As wikipedia says, the term entropy is often used to describe the  "measure of disorder  of a system". I think the situation you described could also be interpreted as the growing disorder of a software system.

Architectural drift which describes that your software architecture is slowly drifting away from the original idea and gets more and more chaotic since new architecture decision are not adjusted to existing ones.

Software Erosion Like the geological term this describes that the structure of the whole software systems breaks more and more apart because new features or bug fixes are not integrated well to the system. And beginning from the edges, the whole architecture looses its shape.

Title: What is the term ("metric") for the degree of unstructuredness due to many changes?

Body: Is there a specific term (name of a "metric") that represents the growing level of unstructuredness (or just plain badness) of a s/w component that is caused by too many changes, by too many people, over too long a time interval?</p>


问:
Cross-platform CI builds
Does any Continuous Integration system out there offer building a project on several operating systems at the same time? Like, building the code on Windows, Linux, *BSD and OSX per commit? I understand that most CI systems are "cross-platform" but that could either mean the above or it could also mean that you need a different setup for each OS. Ideally I'd want CI to run on a central server and spin up virtual machines in the backend for all platforms.

Only need for C/C++, interpreted languages are obviously not the target.

答:
In Jenkins you can setup different build slaves (which could run on different physical or virtual machines).

Your Jenkins master could then delegate different build jobs to the corresponding slave (also in parallel).

So in your case you could setup some Jenkins slaves where every slave runs on a virtual machine with a different operating system.
Your Jenkins master could then define different build jobs like "Build application for OS X", "Build application for Win7" etc... and assign every build job to its machine.

A more complete description can be found here: Jenkins distributed builds.

Title: Cross-platform CI builds


答:
Arrays aren't the only option for implementing autorelease pools. Anything suitable for a set implementation should be suitable for an autorelease pool, including (single- or double-linked) lists, trees, and hash tables. When picking which data structure to use, consider the timing of the various operations and match that to usage.

For an autorelease pool, insertion is a commonly used operation, as is removing recently added items (which is the scenario in question: retaining autoreleased objects). Draining the pool will at a minimum be O(n) for iteration, which should be supportable by any data type (though possibly at an O(n) space cost overall for an extra pointer per record to the next item in the sequence).

Linked lists support insertion & head removal in O(1) time, though removing arbitrary items from a pool also happens relatively frequently, and is O(n) for linked list.

Trees can support insertion & removal in O(log n) time, but iteration is O(n log n) without "next item" pointers.

Operations on hash tables vary from O(1) to O(n), depending on the hash function and the specific data stored in it.

For arrays, best case for insertion is O(1); you only hit the O(n + f(m)) worst-case when the array would overflow, where n is the old array size, m the new array size and f(m) the complexity of allocation. You can reduce the overall timing for insertion by using a dynamic array (doubling the array size on overflow) for an O(1) amortized cost (assuming f(m) ≤ m). However, there's a time-space tradeoff: a portion of the array is allocated but unused. Removing recent items is O(1), though removal is O(n) in general.

You can potentially get further performance gains (at a space cost) by defining a top-level class that all other classes descend from (your own analog to NSObject), and include a pointer to the object's record in the autorelease pool. Using this pointer, searching takes O(1) time, which can reduce removal complexity if searching is the dominant operation during removal (such as for linked lists).

If you declare the object's record pointer as the same type as the autorelease pool's record type, you'll create a tight coupling between objects and memory management, which is undesirable. Instead, you can apply the bridge pattern (aka the Handle-Body idiom in C++ circles): have a abstract memory management strategy class that ties together a family of abstract memory management types (including a type for memory management records and for memory pools), with the object's record pointer of the abstract record type. The strategy would include a stack of AR pools. You could then define concrete autorelease pool and record types for whichever strategies you want. You'd have a static pointer to a memory management strategy, which the basic memory management functions (retain(), release(), autorelease() and pool() (to push a new AR pool)) would reference.

Title: Autoreleasing objects in Reference Counting Systems

Body:
I'm experimenting a bit in C and I'm trying to implement my own Reference Counting System. I've mainly worked with Objective-C in the past but AFAIK autoreleasing objects is something that is unique to Objective-C.

The problem with reference counting is that, when returning objects from methods, there is no correct way to release the object and return it at the same time. If the reference count is 1 releasing it will deallocate the object before it can be returned.

```<code>void *testMethod() {
   return release(object); // Object is already deallocated :'(
}
</code>```

Therefore, by autoreleasing an object, it is not deallocated instantly. Instead, when the autorelease pool is drained, all the objects that were autorelease in the scope of the autorelease pool get released.

```<code>void *testMethod() {
   return autorelease(object);
}

@autorelease {
    object = retain(testMethod());
}
</code>```

As you can see above, the object gets released when the @autorelease {} block ends, which is after the object has been retained again. This solves the problem.

This solution however can become quite a bottleneck. You have to store every object that gets autoreleased in an array with no predeterminable size, requiring you to realloc a lot of times. Loops that require an autorelease pool have become much slower because of this.

Is there a better solution to this problem?

Or rather, are there any other solutions to this problem at all?


问:
Which HTTP verb should I use to trigger an action in a REST web service?
I am implementing a RESTful web service and one of the available actions will be reload. It will be used to reload configurations, cache, etc.

We started with a simple GET to an URI like this: ${path}/cache/reload (no parameters are passed, only the URI is called). I am aware that data should not be modified with a GET request.

Which is the correct verb to use to invoke an action/command in a RESTful web service?

The reload is a command of the REST web service that reload its own cache/configuration/etc. It is not a method that returns information to the client.

Probably what I am trying to do isn't REST, but it is still something that need to be done this way. The reload method was only a real example that makes sense in the scope of the application and most answers focused on it, but in fact, I just needed to know which verb to trigger an action that doesn't do CRUD, but still changes data/state.

I found this detailed asnwer on Stack Overflow abot the subject: https://stackoverflow.com/questions/16877968/

答:
I would argue why a client request would explicitly need to make a call to refresh something like that. It sounds like that should either be hidden logic on a more typical implementation of GET (I.e. Pull data, but the service makes a refresh on the data before it is pulled), or by another trigger in the backend away from the client.

After all, the data/config would only need to be current on subsequent calls, so I would lean more towards a lazy vs eager call for a data refresh. Obviously I am assuming a lot here, but I would take a step back to reevaluate the necessity of such an explicit and standalone call.


答:
POST and PUT are the HTTP verbs used to submit an entity to a web server. With PUT, the submitted entity is the (new) representation for the resource at the given URI, which doesn't fit what you want. POST is for the traditional form-handler, where the entity is ancillary data for the resource, so that's the winner. The entity would include the command or action (e.g. "action=reload").

That said, the command in question probably shouldn't be exposed via a REST interface. It sounds like the necessity for "reload" arises because data can be changed via some other channel (e.g. filesystem, DB client). Caches should be transparent. Moreover, HTTP requests should be atomic, even taking messages sent over other channels into consideration. Offering a "reload" command for configuration settings seems an unnecessary complexity; requiring it is a brittle design. Exposing "reload" to clean-up after an update via another channel is dirty because one channel doesn't contain the entire conversation. Instead, consider one of:

making updates entirely via REST

exposing the command(s) to the other channel

automating the actions

Some of those options might not be viable, depending on what other restrictions exist.

See also "PUT vs POST in REST".

Title: Which HTTP verb should I use to trigger an action in a REST web service?

Body:
I am implementing a RESTful web service and one of the available actions will be reload. It will be used to reload configurations, cache, etc.

We started with a simple GET to an URI like this: ${path}/cache/reload (no parameters are passed, only the URI is called). I am aware that data should not be modified with a GET request.

Which is the correct verb to use to invoke an action/command in a RESTful web service?

The reload is a command of the REST web service that reload its own cache/configuration/etc. It is not a method that returns information to the client.

Probably what I am trying to do isn't REST, but it is still something that need to be done this way. The reload method was only a real example that makes sense in the scope of the application and most answers focused on it, but in fact, I just needed to know which verb to trigger an action that doesn't do CRUD, but still changes data/state.

I found this detailed asnwer on Stack Overflow abot the subject: https://stackoverflow.com/questions/16877968/


答:
I don't think there is a proper verb for this action because this transaction isn't really "RESTful." The "s" and "t" stand for "state transfer" and nothing is being transferred here. Or, put another way, by the strictest definition, the verbs like PUT and POST are always used with a noun and "reload" just has the verb.

This reload may not be RESTful, but it may still be useful and you'll just have pick a way to do it and live with or explain that it's unusual. GET is probably the simplest. There's a fair amount of skepticism in the comments, though, so you should think about whether or not this reload action is required because something else isn't quite doing what it should be doing.