答:
If you want to modell your classes by the single responsibility principle (SRP), you have to make up your mind what these responsibilities are.

When you want to use your Employee class in a salary payment application, then the CalculatePayment method is perfectly right in that place.

The Employee represents an employed person which for sure has a name. Also the Employee class has the responsibility to do (trigger) the calculation of its payment, but it's not neccesary that it knows how. In fact you are limiting your design when you give Employee details on how to calculate the payment.

A better approach could be the following:

```<code>public class Employee
{
    private readonly string name;
    private readonly AbstractPayment payment;

    public Employee(string name, AbstractPayment payment)
    {
        this.name = name;
        this.payment = payment;
    }

    public decimal CalculatePayment()
    {
        return payment.Calculate();
    }
}
</code>```

With this approach every Employee can have a very special payment strategy and you also get rid of the ugly if statement in your calculatePay method.

The base for AbstractPayment could look as following:

```<code>public abstract AbstractPayment
{
    public abstract decimal Calculate();
}
</code>```

Now you have to implement a class for any concrete payment, eg.:

```<code>public class FixedPayment : AbstractPayment
{
    private readonly decimal salary;

    public FixedPayment(decimal salary)
    {
        this.salary = salary;
    }

    public override decimal Calculate()
    {
        return salary;
    }
}

public class TopPerformerPayment : AbstractPayment
{
    private readonly AbstractPayment basePayment;
    private readonly decimal bonus;

    public TopPerformerPayment(AbstractPayment basePayment, decimal bonus)
    {
        this.basePayment= basePayment;
        this.bonus = bonus;
    }

    public override decimal Calculate()
    {
        return basePayment.Calculate() + bonus;
    }
}
</code>```

Instantiate your Employees something like:

```<code>var fixedPayment = new FixedPayment(100m);

var regularEmployee = new Employee("Peter", fixedPayment);
var topEmployee = new Employee("Paul", new TopPerformerPayment(fixedPayment, 500m));
</code>```

For the volunteer you have two posibilities of implementation, depending on the aggreed behaviour of CalculatePayment for an volunteer is an error or not.

```<code>public class VolunteerPaymentIsError : AbstractPayment
{
    public override decimal Calculate()
    {
        throw new PaymentNotAllowedException("A volunteer can not be paid!");
    }
}

public class VolunteerPaymentIsZero : AbstractPayment
{
    public override decimal Calculate()
    {
        return 0m;
    }
}
</code>```

Now you can instantiate your volunteers like so:

```<code>var forbiddenPaymentVolunteer = new Employee("Bob", new VolunteerPaymentIsError());
var zerroSalaryVolunteer = new Employee("Bill", new VolunteerPaymentIsZero());
</code>```

Body:
If you want to modell your classes by the single responsibility principle (SRP), you have to make up your mind what these responsibilities are.

When you want to use your Employee class in a salary payment application, then the CalculatePayment method is perfectly right in that place.

The Employee represents an employed person which for sure has a name. Also the Employee class has the responsibility to do (trigger) the calculation of its payment, but it's not neccesary that it knows how. In fact you are limiting your design when you give Employee details on how to calculate the payment.

A better approach could be the following:

public class Employee
{
    private readonly string name;
    private readonly AbstractPayment payment;

    public Employee(string name, AbstractPayment payment)
    {
        this.name = name;
        this.payment = payment;
    }

    public decimal CalculatePayment()
    {
        return payment.Calculate();
    }
}

With this approach every Employee can have a very special payment strategy and you also get rid of the ugly if statement in your calculatePay method.

The base for AbstractPayment could look as following:

public abstract AbstractPayment
{
    public abstract decimal Calculate();
}

Now you have to implement a class for any concrete payment, eg.:

public class FixedPayment : AbstractPayment
{
    private readonly decimal salary;

    public FixedPayment(decimal salary)
    {
        this.salary = salary;
    }

    public override decimal Calculate()
    {
        return salary;
    }
}

public class TopPerformerPayment : AbstractPayment
{
    private readonly AbstractPayment basePayment;
    private readonly decimal bonus;

    public TopPerformerPayment(AbstractPayment basePayment, decimal bonus)
    {
        this.basePayment= basePayment;
        this.bonus = bonus;
    }

    public override decimal Calculate()
    {
        return basePayment.Calculate() + bonus;
    }
}

Instantiate your Employees something like:

var fixedPayment = new FixedPayment(100m);

var regularEmployee = new Employee("Peter", fixedPayment);
var topEmployee = new Employee("Paul", new TopPerformerPayment(fixedPayment, 500m));

For the volunteer you have two posibilities of implementation, depending on the aggreed behaviour of CalculatePayment for an volunteer is an error or not.

public class VolunteerPaymentIsError : AbstractPayment
{
    public override decimal Calculate()
    {
        throw new PaymentNotAllowedException("A volunteer can not be paid!");
    }
}

public class VolunteerPaymentIsZero : AbstractPayment
{
    public override decimal Calculate()
    {
        return 0m;
    }
}

Now you can instantiate your volunteers like so:

var forbiddenPaymentVolunteer = new Employee("Bob", new VolunteerPaymentIsError());
var zerroSalaryVolunteer = new Employee("Bill", new VolunteerPaymentIsZero());


问:
How do you manage your knowledge base?
As programmers we have a lot of inputs:

Ebooks

Code snippets

Interesting emails

Documents

Web articles

Blog posts

StackOverflow questions

Podcasts
...

Which tools do you use to store, organize, search and consult all of this stuff?

Is there a silver bullet solution to handle this huge amount of data?

答:
Here are the basics for me.

Evernote for web links, blog posts and email.

Snippely for code snippets

Dropbox for syncing Snippely db, PDFs, backup files, and git repos for configs, etc.

ContentLicense: CC BY-SA 2.5

Title: How do you manage your knowledge base?


问:
What layers reference each other in a multi layer design?
I'm creating a project and I'm having difficulty and contrasting opinions on how to do things when it comes down to separating layers. I'm not fully sure what layers should reference each other.

I have read in certain blogs/posts that the flow should be

the view references the business layer

the business layer references the data layer

the data layer only knows about it self

On the other hand I have also seen the following

the view references the business layer

the business layer knows only about itself

the data layer references the business layer

Using the second method I have been using the business layer using IOC but im reluctant to progress without more knowledge.

I have read a number of posts but the answers seem many and varied. Any clarification would be great.

Thanks

答:
In general, it doesn't matter. I wouldn't call the second version a "layered" architecture since the layers don't stack in the right order. It is also unclear in that approach who "glues" the view and the data layer so they work together.

The key thing though is that the relationships are non-cyclic, and unidirectional. This loose coupling allows you to replace those dependencies (IOC or not) should the need arise.

ContentLicense: CC BY-SA 3.0


问:
Custom Video Player
I have a custom file type .mft which is basically a zip that has video inside (mpg,mp4,etc) that is encrypted/protected.

My ideia is to create a custom video player which will read those .mft files, for a private group of users (users provide user and password), and the custom player will not allow to save the video, so that no one can re-share it, and can only view it.

I saw that VLC has this library http://vlcdotnet.codeplex.com/releases/view/121099, so my player would use it.

My question is : Is it really possible to block users from not saving the video? I don't think so, because there are several software to record desktop activity.

What do you think?

答:
Your DRM scheme is based on security by obscurity. It won't take long until people figure out that your custom video format is just a zip-archive and will extract it with 7zip to get the actual file.

You could make it a bit harder by encrypting it, but people will also be able to figure these out and obtain your decryption key by reverse-engineering your application.

Title: Custom Video Player


问:
What is a "lifted representation"?
Just ran across this term here:

http://www.codemesh.io/codemesh2014/viktor-klang

"We'll demonstrate the Flow API—a lifted representation—as well as a
  pluggable way of transforming the lifted representation into the
  execution representation—Flow Materialization."

Googling did not help much.

答:
The term to lift can of course have different meanings depending on the context.

In generic programming it describes the process of abstracting to the next higher level. For example, you could have two pieces of code, one type with int, and the other with float. Lifting this code would mean something like templating the method with a generic type T that works for both, int and float.

I found this usage of the term to be a good intuitive guideline for what lifting means. The only difference that seems to exist between the different contexts is what this higher abstraction really is.

In particular, Viktor is known in the context of functional programming, and in this context, you can find sightly different interpretations of lifting there. One example, is to lift values into a functor, or to lift functions to work on monadic values (i.e. Haskell's liftM2).

A very concrete example of a "lifted representation" could then f.ex. be a List(1), or a Some(1).

Title: What is a "lifted representation"?


答:
I am not familiar with the Flow API.

The term “lifting” comes from category theory. In programming languages such as Haskell or Scala, a lift function takes a function A => B, and somehow performs magic so that the lifted function F[A] => F[B] can be applied to a functor or monad F[A].

A concrete example using Scala's Seq container: Assume we have a function def double(x: Int): Int = 2 * x, and a sequence val xs = Seq(1, 2, 3). We cannot double(xs) due to incompatible types. But if we obtain a val doubleSeq = liftToSeq(double), we can do doubleSeq(xs), which evaluates to Seq(2, 4, 6). Here, liftToSeq can be implemented as

def liftToSeq[A, B](f: A => B): (Seq[A] => Seq[B]) =
  (seq: Seq[A]) => seq.map(f)
```

The Seq(…) constructor can also be seen as a lifting operation, which lifts the values 1, 2, 3 into a Seq instance, thus allowing us to use list abstractions for these values.

Monads allow us to encapsulate the inner workings of some type by offering a watertight but composable interface. Using a lifted representation can make it easier to reason about a computation. Using such abstractions also means that we lose knowledge of the abstracted-away specifics, but those are needed for providing an efficient implementation under the hood (finding a suitable execution representation).

Title: What is a "lifted representation"?

Body:
Just ran across this term here:

http://www.codemesh.io/codemesh2014/viktor-klang

"We'll demonstrate the Flow API—a lifted representation—as well as a
  pluggable way of transforming the lifted representation into the
  execution representation—Flow Materialization."

Googling did not help much.

Body:
I am not familiar with the Flow API.

The term “lifting” comes from category theory. In programming languages such as Haskell or Scala, a lift function takes a function A => B, and somehow performs magic so that the lifted function F[A] => F[B] can be applied to a functor or monad F[A].

A concrete example using Scala's Seq container: Assume we have a function def double(x: Int): Int = 2 * x, and a sequence val xs = Seq(1, 2, 3). We cannot double(xs) due to incompatible types. But if we obtain a val doubleSeq = liftToSeq(double), we can do doubleSeq(xs), which evaluates to Seq(2, 4, 6). Here, liftToSeq can be implemented as

def liftToSeq[A, B](f: A => B): (Seq[A] => Seq[B]) =
  (seq: Seq[A]) => seq.map(f)

The Seq(…) constructor can also be seen as a lifting operation, which lifts the values 1, 2, 3 into a Seq instance, thus allowing us to use list abstractions for these values.

Monads allow us to encapsulate the inner workings of some type by offering a watertight but composable interface. Using a lifted representation can make it easier to reason about a computation. Using such abstractions also means that we lose knowledge of the abstracted-away specifics, but those are needed for providing an efficient implementation under the hood (finding a suitable execution representation).


问:
Why is the use of conjunctions in method names a bad naming convention?
In my team, we work closely with a few software architects. They approve all design decisions of our projects, do some code reviews etc.

Our projects consist mainly of backend functionality implemented in PHP using the Symfony 2 framework. So syntactically, the code, naming conventions and project structure look almost identical to what Java would look like (Symfony 2 encourages such structure). I'm mentioning this because Java-specific conventions also apply in our case (if possible).

Recently, they suggested something that I find very strange: all methods should have conjunctions in their name e.g. getEntityOrNull, setValueOrException etc.

Such a naming convention feels very wrong to me, but I can't come up with any concrete arguments or online articles/pages that specifically challenge this.

The only things I came up with is:

such information should be present in the method's annotations, like @return or @throws

the use of conjunctions ("and", "or" etc.) in method names usually suggest that the Single Responsibility Principle is not properly respected

What are some other concrete arguments against this naming convention?

答:
In my code I sometime create method pairs with names like getEntity() and getEntityOrNull().  The name makes the expected behavior clear.  If getEntity() finds no entity then an exception is thrown.  getEntityOrNull() will return a null.

By doing this, the calling code becomes a bit clearer.  If the calling code has to have an entity then getEntity will do the trick.  If entity is some sort of optional thingee then getEntityOrNull is the method of choice.

The same thing could be accomplished with a single method but that then shifts some of the burden to the calling program.  You always need to test for a null or you need a try/catch block.  Either way it's extra code that needs to be duplicated each time the method is called.

If your architects are not using these sorts of method pairs then yes, I would question the need for the suffix.

Never really saw a setValueOrException method.  Can't think of a good common use case for that.

You might consider asking the architects why.  The ones I know are always glad to explain their decisions.  Often in great (and sometimes excruciating) detail.


问:
When should you call yourself a senior developer?

Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?

答: "When should you call yourself a senior developer?" - When I started to mentor junior developers.


问:
Is there any logical reason to auto-generate code documentation?
Automatic documentation generation can be done with a variety of tools, GhostDoc being one of the more prominent.  However, by definition, everything it generates is redundant.  It takes a look at names of methods, classes, etc. and outputs English that might explain them more verbosely.  In the best case, it does what the reader could already do in their head (examples taken from here):

```<code>/// <summary>
/// Initializes a new instance of the <see cref="Person"/> class.
/// </summary>
public Person() ...
</code>```

In the worst, it can actually end up generating bizarre documentation that is actually misleading in its attempt to heuristically figure out the meaning of names:

```<code>/// <summary>
/// Riches the text selection changed.
/// </summary>
/// <param name="richTextBox">The rich text box.</param>
private void RichTextSelection_Changed(System.Windows.Controls.RichTextBox richTextBox) ...
</code>```

It seems that the attitude with GhostDoc is, "it's intrinsically better to have some kind of formal XML documentation", but when that documentation is 100% redundant, why?  Isn't it just wasting a ton of space at best?

At my workplace, we have to document everything, and almost always with GhostDoc's auto-generated docs.  Do you do this, and are there any rational reasons not to simply leave code undocumented if you aren't going to actually write the documentation yourself?

答:
Certainly, automated documentation is particularly helpful when it can reproduce insightful, appropriate descriptions written by the code authors. Otherwise, it's just a glorified automatic formatter.

But formatting isn't useless. There is value in being able to find the public methods of a largish component at one gaze, sorted, and guaranteed to be complete. If you need a frobnick mutator, and it isn't there, you know it isn't there without wading through source code. (Negative results also have value: you know you have to do something, and you have more time to do it because you didn't have to wade.)

So, yes, automatic doc generation adds some value. Certainly not as much as managers probably assume, and usually not even as much as a really good copy editor would, but not nothing.


问:
Efficient "Object with weights" structure
I need to find an "efficient" data structure / set of algorithms to do the following things:

I have a list of objects. I need to assign them weights and later on increase or decrease these weights.

For instance:
We have the hashmaps {o1}, {o2}, {o3}. The {o}'s don't have any particullar structure, just random json.

I am looking for a way of saying: Increase the weight of o1 by 1. Increase the weight of o2 by 1. Increase the weight of o1 by 1. Now give me the results sorted by their weight.

I am using Python. So far I have tried using a normal hashmap to store them, but the problem is that I can't just hash the {o}'s. I thought of hashing the pointer of the {o}'s in memory, but it seems I don't have access to it in Python.

答:
Use a class

```<code>class Thing(object):
    def __init__(self, o):
        self.o = o
        self.weight = weight
</code>```

You can make a list of Things, or a dict, or whatever works for you.

Body:
Use a class

class Thing(object):
    def __init__(self, o):
        self.o = o
        self.weight = weight

You can make a list of Things, or a dict, or whatever works for you.


答:
These sorts of concepts are usually easiest to understand with a concrete example.  Consider the following excerpt from this Flow API example:

```<code>Flow(text.split("\\s").toVector).
      // transform
      map(line => line.toUpperCase).
      // print to console (can also use ``foreach(println)``)
      foreach(transformedLine => println(transformedLine)).
      onComplete(FlowMaterializer(MaterializerSettings())) {
        case Success(_) => system.shutdown()
        case Failure(e) =>
          println("Failure: " + e.getMessage)
          system.shutdown()
      }
</code>```

This takes the following code:

```<code>text.split("\\s").toVector.
      map(line => line.toUpperCase).
      foreach(println)
</code>```

and "lifts" it into a Flow context.  That allows you to use the same syntax you are familiar with for specifying your algorithm, but behind the scenes the map is done in parallel on several processors or even machines, then the foreach(println) seamlessly collects that output back to one processor for printing.

This is a generic term that can refer to wrapping any context around any type.  Another more familiar example is map takes a function that works on a single element and "lifts" it into the new context of working on a collection of those elements.  Lifting is ubiquitous in functional programming and one of the main reasons it is so much easier to reuse functional code.

Title: What is a "lifted representation"?

Body:
These sorts of concepts are usually easiest to understand with a concrete example.  Consider the following excerpt from this Flow API example:

Flow(text.split("\\s").toVector).
      // transform
      map(line => line.toUpperCase).
      // print to console (can also use ``foreach(println)``)
      foreach(transformedLine => println(transformedLine)).
      onComplete(FlowMaterializer(MaterializerSettings())) {
        case Success(_) => system.shutdown()
        case Failure(e) =>
          println("Failure: " + e.getMessage)
          system.shutdown()
      }

This takes the following code:

text.split("\\s").toVector.
      map(line => line.toUpperCase).
      foreach(println)

and "lifts" it into a Flow context.  That allows you to use the same syntax you are familiar with for specifying your algorithm, but behind the scenes the map is done in parallel on several processors or even machines, then the foreach(println) seamlessly collects that output back to one processor for printing.

This is a generic term that can refer to wrapping any context around any type.  Another more familiar example is map takes a function that works on a single element and "lifts" it into the new context of working on a collection of those elements.  Lifting is ubiquitous in functional programming and one of the main reasons it is so much easier to reuse functional code.


答:
Is there any logical reason to auto-generate code documentation?

From whose perspective?

If I were running the company or the dev group, then there's no good reason. I am staunchly in the "comments should explain why" camp. Forcing people to comment classes/functions/properties is worse than worthless, since they get out of date, they mislead the reader, they're used as an excuse to not make readable code, and so on. These comments waste time both writing them, reading the code, and bugs caused by them. Some will argue that JavaDoc style API docs are a reason to do the commenting, but even under that argument a small portion of your code should be part of the public API, and JavaDoc is not a replacement for actual API docs.

As a developer, I've worked a few places that require comments in these places, despite my opinion. Since I don't have the time or patience to write a bunch of crap that nobody is going to use, I GhostDoc it instead. This allows me to spend that time actually doing stuff that matters. Far more efficient than changing corporate policy.

One other good thing I've found using GhostDoc is that it serves as a check that my names are good. If GhostDoc can't generate decent documentation for a function, it's a smell that my function or parameter names may be poor. While I wouldn't use the tool for just this, it's a nice little side effect if I'm being made to waste my time anyways.

Body:
Automatic documentation generation can be done with a variety of tools, GhostDoc being one of the more prominent.  However, by definition, everything it generates is redundant.  It takes a look at names of methods, classes, etc. and outputs English that might explain them more verbosely.  In the best case, it does what the reader could already do in their head (examples taken from here):

```<code>/// <summary>
/// Initializes a new instance of the <see cref="Person"/> class.
/// </summary>
public Person() ...
</code>```

In the worst, it can actually end up generating bizarre documentation that is actually misleading in its attempt to heuristically figure out the meaning of names:

```<code>/// <summary>
/// Riches the text selection changed.
/// </summary>
/// <param name="richTextBox">The rich text box.</param>
private void RichTextSelection_Changed(System.Windows.Controls.RichTextBox richTextBox) ...
</code>```

It seems that the attitude with GhostDoc is, "it's intrinsically better to have some kind of formal XML documentation", but when that documentation is 100% redundant, why?  Isn't it just wasting a ton of space at best?

At my workplace, we have to document everything, and almost always with GhostDoc's auto-generated docs.  Do you do this, and are there any rational reasons not to simply leave code undocumented if you aren't going to actually write the documentation yourself?


答:
I've noticed the same trend. One of the questions the other day was about a senior developer with 2-3 years' experience moving up to architect.

You can call an acorn a tree, but that don't change what it be.

The only logical conclusion is that "senior" means something else:

relative rank, as in "senior to the guy just out of college"

poor Spanish spellers, i.e. they meant to put señor

southern spelling, as in "senior butt-crack, pull up them pants"

These days, it's just a job title, and may or not say anything about relative industry experience.

Title: When should you call yourself a senior developer?

Body:
Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?


答:
In a statically typed language, Javadoc-style documentation is not for the authors, it's for the consumers.  Autogeneration simply makes it easier for the authors to maintain the documentation for other people to consume.

If you're using a statically typed language and are not writing a library for third party consumption, autogeneration doesn't buy you much, and in my experience is rarely used.  If you're using a dynamically typed language, javadoc-style documentation is often used to document the types, even for internal use only, but autogeneration doesn't know the types, so all it saves you is avoiding manual copying of the boilerplate.

Either way, don't think of autogeneration as producing a finished product.  Think of it as producing the boilerplate for you, so any changes you make manually are significant.

Title: Is there any logical reason to auto-generate code documentation?


答:
Although the use of conjunctions often indicates a violation of the SRP, in this case it is just indicating the return value of a poor man's algebraic data type that can be one of two values, either null or a "success" value.

They are using a kind of Hungarian Notation to compensate for weaknesses in the type system, namely a lack of non-nullable types.  In other words, there is no way to specify in your @return annotation that the function will never return null, and conversely, there's no way to specify in your @return annotation that the function may possibly return null.

Also, I believe that @throws annotations are not mandatory in php, so the absence of the annotation doesn't indicate the absence of an exception, although that's better solved by making the annotation mandatory in your style guide.

Given those limitations of the language you're using, it's not an entirely unreasonable style.

Title: Why is the use of conjunctions in method names a bad naming convention?

Body:
In my team, we work closely with a few software architects. They approve all design decisions of our projects, do some code reviews etc.

Our projects consist mainly of backend functionality implemented in PHP using the Symfony 2 framework. So syntactically, the code, naming conventions and project structure look almost identical to what Java would look like (Symfony 2 encourages such structure). I'm mentioning this because Java-specific conventions also apply in our case (if possible).

Recently, they suggested something that I find very strange: all methods should have conjunctions in their name e.g. getEntityOrNull, setValueOrException etc.

Such a naming convention feels very wrong to me, but I can't come up with any concrete arguments or online articles/pages that specifically challenge this.

The only things I came up with is:

such information should be present in the method's annotations, like @return or @throws

the use of conjunctions ("and", "or" etc.) in method names usually suggest that the Single Responsibility Principle is not properly respected

What are some other concrete arguments against this naming convention?


问:
Allow entities owned by one user to be referenced by other users' entities
I am working on an Asp.NET MVC web application.

I have the following (simplified) entities:

```<code>public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public User CreatedBy { get; set; }
    public EventArea EventArea { get; set; }
}

public class EventArea
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public User CreatedBy { get; set; }
    public CoOrdinate CoOrdinate { get; set; }
}

public class CoOrdinate
{
    public int Id { get; set; }
    public int Latitude { get; set; }
    public int Longitude { get; set; }
}
</code>```

Users can register and create their own Course entities. Each Course has a geographical location, represented by an EventArea which can also be created by a user.

As an EventArea represents a geographical location it should be available for use by other users who want to create a course in the same location.

However making EventArea entities available to users other than the creator raises the following questions:

What happens if the EventArea is modified or deleted by the creating user?

Who should be able to view/edit/modify an EventArea entity?

Any alternative suggestions for how to approach a scenario where an entity created by one user can be referenced by a different user?

答:
how to approach a scenario where an entity created by one user can be referenced by a different user?

You're capturing CreatedBy. So you can tell who is logged on, so you can enable editability on the web page for those things created by that user.

Who should be able to view/edit/modify an EventArea entity?

What happens if the EventArea is modified or deleted by the creating user?

This is entirely dependent on your system requirements. Only you can answer these questions.

It seems to me that if any user can create an EventArea then it is possible to create 2 or more EventAreas that are actually the same place down to the precision of your coordinate system and with exactly the same name.

Do more Requirements Analysis

an EventArea represents a geographical location

If an "event area" can be any  10' x 10' spot in any public space anywhere in the country, then maybe users should be able to create them. But if we're talking about existing auditoriums, stadiums, campus, building, classroom, etc. then maybe they should be created by you and users can only select one.

And so maybe an EventArea represents a place (classroom?), that has a geographical location

Do not allow user-editable keys

If Id is a primary or foreign key into your database then public ... set is a bad idea. Never allow users to edit keys. Maybe they could create them as they created an object - I've had a case where this made sense - but never let an existing key be edited.

Encapsulate Object Creation

Use constructor parameters to control object creation, instead of publicly exposing all the properties. Otherwise you force client code to know everything about creating something. Required entry? Ranges? Valid property combinations? etc., etc.

In this case I'd expect to see something like this:

```<code>public class Course
{
    public int Id { get; protected set; }
    public string Name { get; protected set; }
    public string Description { get; protected set; }
    public User CreatedBy { get; protected set; }
    public EventArea EventArea { get; protected set; }

    public Course (string name, string description, EventArea area) {
        this.Name = name;
        this.Description = description;
        this.EventArea = area;
        this.Id = GenerateID();
        this.CreatedBy = FetchLoggedOnUser();
    }
}
</code>```

Body:
how to approach a scenario where an entity created by one user can be referenced by a different user?

You're capturing CreatedBy. So you can tell who is logged on, so you can enable editability on the web page for those things created by that user.

Who should be able to view/edit/modify an EventArea entity?

What happens if the EventArea is modified or deleted by the creating user?

This is entirely dependent on your system requirements. Only you can answer these questions.

It seems to me that if any user can create an EventArea then it is possible to create 2 or more EventAreas that are actually the same place down to the precision of your coordinate system and with exactly the same name.

Do more Requirements Analysis

an EventArea represents a geographical location

If an "event area" can be any  10' x 10' spot in any public space anywhere in the country, then maybe users should be able to create them. But if we're talking about existing auditoriums, stadiums, campus, building, classroom, etc. then maybe they should be created by you and users can only select one.

And so maybe an EventArea represents a place (classroom?), that has a geographical location

Do not allow user-editable keys

If Id is a primary or foreign key into your database then public ... set is a bad idea. Never allow users to edit keys. Maybe they could create them as they created an object - I've had a case where this made sense - but never let an existing key be edited.

Encapsulate Object Creation

Use constructor parameters to control object creation, instead of publicly exposing all the properties. Otherwise you force client code to know everything about creating something. Required entry? Ranges? Valid property combinations? etc., etc.

In this case I'd expect to see something like this:

public class Course
{
    public int Id { get; protected set; }
    public string Name { get; protected set; }
    public string Description { get; protected set; }
    public User CreatedBy { get; protected set; }
    public EventArea EventArea { get; protected set; }

    public Course (string name, string description, EventArea area) {
        this.Name = name;
        this.Description = description;
        this.EventArea = area;
        this.Id = GenerateID();
        this.CreatedBy = FetchLoggedOnUser();
    }
}


答:
10 Years ?? You must be Kidding. Ok, how do you define 10 years ? Let us say someone started programming at the age of 15 but became proffesional at 25 ?

The industry doesn't work that way. I think different companies let people call them Senior Dev X or Y anytime between 5-8 years. A lot of seniority in the Organization doesn't come with ability alone, it has a lot to do with the initiative an individual is taking and the kind of responsibilites he is willing to share. Most of the time people with reasonable skill and strong motivation do become senior Pros.

BTW 22 years is not teen ;-)


问:
Testing strategy for games
I've inherited a web-based educational game. Over the past year I've worked towards stabilizing the code and adding new features. Most of the logic is in the front-end, so back-end unit tests, while helpful, cover a small percent of the code.

The game has gotten to the point where it's starting to get complex. There are two different modes for each game and the game behaves differently depending on the mode. There are also various flags that affect game play.

I've been an application developer for 10+ years now and this perplexes me. In the enterprise world, an algorithm always functions the same way. I'll write a unit test for an algorithm, I'll expect the value 42 and it'll error if I don't get that value.

When it comes to games, I'm lost. How do I test them? I have testers available to me. I can spend time writing unit tests.

Testers are ... unreliable. They aren't the best at rooting out issues and I haven't given them the best direction. Short of spending a ton of time every release cycle testing every permutation and combination of the game, how should I use them as a resource?

Unit tests seem limited. Since most of the logic is javascript (and I inherited spaghetti code), I can use a front-end suite like Cucumber or selenium to ensure certain features are working.

Is that the best strategy? How do game companies test games?

I have read the question "Test Driven Development for Complex Games" (among others on the site), but it doesn't address what I'm looking for. I'm asking for strategies, not specific examples of how to test.

答:
In the enterprise world, an algorithm always functions the same way. I'll write a unit test for an algorithm, I'll expect the value 42 and it'll error if I don't get that value.

This is not very different in games. The presence of two modes and multiple flags in the game you're working on doesn't change anything: if you take a specific mode with a specific set of flags, you will still get the same value again and again when testing a part of the source code.

With too many modes and flags, the game can quickly become very difficult to test, because of the number of possible variants. In order to mitigate the risk of running into this difficulty early, you should:

Mock/stub severely. Keep the tested parts small, and mock everything they rely on.

If they rely on time, mock the time object to always give a specific result or a set of specific results, independently of the actual time.

If they rely on random(), mock it to provide a constant every time.

Refactor. If tests start to be overly-complicated or if you see that a class, in order to be tested, requires twelve arguments after you implemented Dependency Injection, while it required only two before, you need to refactor the code.

Question the actual business rules of the application. I stopped counting the number of projects which were nearly impossible to test because of the number of different variations required by the functional requirements nobody needed nor understood—not even the stakeholders.

When a small e-commerce website needs ten pages to explain the functional requirements used to determine how shipment prices are computed, one shouldn't start by writing tests or code, but instead, should get back to the stakeholders and work with them to produce sane requirements.

Finally, automate every test. Testers are needed to discover situations where the application fails. Using testers to execute, again and again, the same action at every revision is counter-productive and disrespectful of testers: regression testing should be done by machines, not people. People, on the other hand, are much better at finding possible bugs. "What if I..." is one of the techniques they can use ("What if I enter a few megabytes of binary data containing several \x00 into a field which asks for my age, and see what will happen?"), but more formal approaches can be used as well.

Title: Testing strategy for games


问:
Polymorphic engines in C and/or C++
I stumbled across polymorphic engines and I don't know anything about them. However, I am curious about how they are written. Every example that I've looked up writes them in assembly, my assembly is not good at all; I know just a few instructions here and there but not that well. On the other hand, I am good in C and C++.

I am familiar with the concept of polymorphism in C++ but after reading about polymorphic engines, I am assuming that they are different from the polymorphism in C++.

I'm just looking for simple code that shows encryption/decryption and/or obfuscation of code using C and/or C++

How can techniques such as using virtual keyword in C++ be used to obfuscate or encrypt the code in an application?

NOTE: I was told to transfer this question from stackoverflow.com to this place.

答:
I am familiar with the concept of polymorphism in C++ but after
reading about polymorphic engines, I am assuming that they are
different from the polymorphism in C++.

How can techniques such as using virtual keyword in C++ be used to
obfuscate or encrypt the code in an application?

Your assumption is correct. They are different things.

Typically, neither C nor C++ make use of run-time code generation, nor do they use any self-modifying code.

C and C++ allows function pointers, as well as unchecked type casts between pretty much anything. These two features allow one to make a CPU jump (execution transfer) into any address.

A programmer can write C or C++ code that concatenates byte fragments consisting of meaningful machine code into a byte buffer, and then emit a call to the start of this machine code fragment. Typically, the machine code fragment contains one or more return statements that will return control to the calling C/C++ code.

However, because most C and C++ programs do not make arbitrary jumps, when these programs are executed under an Operating System (OS), the OS may use a CPU feature known as "Execution Disable bit" (NX) to prevent jumps into addresses that were not part of the C/C++ compiler's binary output.

Typically, the "function pointer" feature is used by C programmers to implement a Virtual method table.

C++ provides a more human-understandable mechanism for creating inheritable class objects, which is achieved in part by the virtual method table mechanism.

The difference between the C and C++ approach to virtual method table is that,

In C, the programmer has to take care of all manipulations needed to maintain the virtual method table;

In C, the programmer is allowed to make all kinds of manipulations to the virtual method table, at any time (even in the middle of a method's execution)

Typically, polymorphic engines (code obfuscation) do not make use of virtual method table. This is because a hard-coded virtual method table is highly visible when the machine code is analyzed at run-time (with a debugger attached), because they consist of consecutive pointers into a memory address range consisting of executable code.

Just for learning purpose, though, it might be useful for one to implement an engine using C/C++ function pointers.

I'm just looking for simple code that shows encryption/decryption
and/or obfuscation of code using C and/or C++

Unfortunate this is out-of-topic for Programmers.StackExchange.

If you have questions about these topics with respect to information security:

Encryption and decryption,

Code obfuscation

Try ask at http://security.stackexchange.com

If you are looking for a C++ tool for generating callable fragments of assembly code, try AsmJit. It allows one to learn the basics of programmatically generating assembly code. From this, you can learn how to generate different assembly code fragments that perform functionally equivalent computation.

(Disclaimer: I have not used AsmJit before.)

Title: Polymorphic engines in C and/or C++


答:
EDIT: I misunderstood the original question; although I think generating documentation (i.e. non-code documents) can be extremely valuable (see original answer regarding Doxygen below), auto-generating comments (which is something that GhostDoc actually does) sounds insane to me. I cannot understand why anyone would expect a program to be able to read un-commented source code and write comments that will genuinely clarify it.

It is conceivable to me that an extremely "smart" comment-generation utility could be programmed to recognize certain patterns and generate "how"-style comments; for instance, it could recognize Knuth's variance-calculating algorithm and provide a comment explaining how it works and why the naive algorithm wouldn't be appropriate. Perhaps such a utility could even be programmed to recognize canonical object-oriented design patterns (e.g. Abstract Factory) and insert comments indicating what pattern is being used and which classes are playing what roles.

But in my opinion, the most useful comments don't explain "how" something works, since the code itself should show this, but "why" comments, explaining "why" a particular thing is being done. As noted by David Hammen in the comments below, in order to generate "why" comments, a utility would need to "read the programmer's mind." Obviously this is impossible.

Based on the given examples, however, it appears that GhostDoc doesn't even accomplish the task of creating true "how"-style comments. So it is, in my opinion, worse than useless, since what it does generate can be inane and misleading (as in the second example).

Original answer: why automatic documentation extraction and formatting is a good idea

My software team uses Doxygen. The primary reason for this is that we need non-source-code (i.e. readable by non-programmers) documentation of code features/behavior/etc, but we feel that it is a better practice to integrate this into the source code itself than to maintain it as a second document. This helps us keep the documentation in sync with the source code (though of course that can't ever be completely ensured, much less automated) and minimizes the overhead of writing documentation (since documentation for a piece of code can be trivially incorporated into the file containing the code itself).

So the focus of our Doxygen use is not to extract information from code itself, but to keep documentation of source code as close as possible to the source code itself.

This also allows us to use one single tool to create both a "theory of operations" that describes our entire codebase and several sets of "release notes" that describe the software product but in fact do not contain any actual "code documentation" in the typical sense.

As for why we would need non-source-code documentation of the behavior of our code, there are two reasons:

Our product is not merely software; it's a complex tool that integrates many hardware components, including some fancy lasers and fluidics. We need engineers without much software background to have a good understanding of exactly how the internals of our code behave, and telling them "read the source code" is not going to accomplish this.

We must follow quite a few quality regulations, some internally mandated by the company and others legally mandated by the federal government. Although the quality process is (or at least can be) extremely valuable and helpful, it involves a non-negligible amount of overhead, part of which is the duty of the software team to provide this kind of detailed documentation of the software. Again, integrating this documentation with the code itself minimizes overhead and helps us keep the documentation up-to-date.

Note that the second bullet point is pretty similar to the point a couple other answers have made about managers wanting the reassurance (/bragging rights) of knowing that some documentation (regardless of quality) exists for every piece of source code; that way of framing it, however, ignores the fact that externally-mandated documentation can actually have some legitimate advantages.


答: It's often good to use documentation generators to create boilerplate or "stand-in" comments that are then later revised by actual developers. I often use Eclipse's auto-JavaDoc function to generate the header comment with parameter types and return values already filled in, then simply add the "meat" of the documentation.</p>


问:
Domain model associations that do not required the behaviour of the associated object. How to model?
I've been struggling with this question for a while.

I'm specifically thinking within the object orientated domain model.

Let's say I have two entities. A supplier and a customer. There is a relationship that a supplier can have many customers, and a customer (in this case) can only have one supplier.

The issue I have is that neither object needs any behaviour of the other object i.e. the supplier object does not need to use any behaviour of the customer object and visa versa.

There is however still an association between them. The reason is that the problem domain requires that all a suppliers customers are destroyed if the supplier is destroyed. We also need to be able to retrieve a collection of all customers associated with a supplier.

How is this managed in the OO domain model? Who is responsible for the association?

Some may say that there should be a getCustomers() method on the supplier object and this is where the association lies. I don't really like this as it makes it difficult to close the supplier class (violation of Open Closed Principle). Every time we create a new type of class which has an association to a supplier, we have to add a get method to the supplier.

One thing I think could be used to model the association are repositories (from Eric Evens Domain Driven Design book). I guess it would be the Repository that then cares about this relationship? We could call selectCustomersFor(supplier_id) etc

Edit

The only reason I can see for having the association is for object retrieval criteria or object destruction (i.e. if user is destroyed, all customers will be destroyed). To me, it is not the responsibility of either object to retrieve or destroy itself. You could argue that the supplier should retrieve/destroy a customer, but this surely violates the Single Responsibility rule, and could also lead to Open Closed violation.

Why would we then bother to add the responsibility of association to an object thats doesn't use it? Its useless to the object. The association isn't useless though, I just feel something else should be responsible for it.

答: This would be an example of a transitive association, through an association object like an order or invoice that references both Customers and Suppliers. If you have no such objects then your model is probably incomplete or decomposed beyond the point of usefulness.</p>


答:
There is a relationship that a supplier can have many customers, and a customer (in this case) can only have one supplier.

Surely there's a business-driven reason for you to say that. Why is it necessary for a customer to only have one supplier? Is there some crucial invariant you need to enforce? Is there something you can do to a supplier which will affect all the customers?

Generally a domain expert will come up with a rule like that because of some underlying principle. Your experts may not realise that it's not obvious to you why the rule exists, so you need to communicate with them! When you arrive at the underlying business principle, that is what you should try and represent in your code.

Title: Domain model associations that do not required the behaviour of the associated object. How to model?

Body:
I've been struggling with this question for a while.

I'm specifically thinking within the object orientated domain model.

Let's say I have two entities. A supplier and a customer. There is a relationship that a supplier can have many customers, and a customer (in this case) can only have one supplier.

The issue I have is that neither object needs any behaviour of the other object i.e. the supplier object does not need to use any behaviour of the customer object and visa versa.

There is however still an association between them. The reason is that the problem domain requires that all a suppliers customers are destroyed if the supplier is destroyed. We also need to be able to retrieve a collection of all customers associated with a supplier.

How is this managed in the OO domain model? Who is responsible for the association?

Some may say that there should be a getCustomers() method on the supplier object and this is where the association lies. I don't really like this as it makes it difficult to close the supplier class (violation of Open Closed Principle). Every time we create a new type of class which has an association to a supplier, we have to add a get method to the supplier.

One thing I think could be used to model the association are repositories (from Eric Evens Domain Driven Design book). I guess it would be the Repository that then cares about this relationship? We could call selectCustomersFor(supplier_id) etc

Edit

The only reason I can see for having the association is for object retrieval criteria or object destruction (i.e. if user is destroyed, all customers will be destroyed). To me, it is not the responsibility of either object to retrieve or destroy itself. You could argue that the supplier should retrieve/destroy a customer, but this surely violates the Single Responsibility rule, and could also lead to Open Closed violation.

Why would we then bother to add the responsibility of association to an object thats doesn't use it? Its useless to the object. The association isn't useless though, I just feel something else should be responsible for it.


问:
Machine code JITs and the Execution Disable bit
How is runtime-generated machine-code (such as the output of a JIT), actually executed by the CPU if the CPU/OS has an Execution Disable bit?

As far as I know, many modern processors and Operating Systems include support for an NX bit, (including Intel and ARM), which prevents machine code that is stored at any address other than the code section of a compiled binary from being executed.  Clearly, this is a nice security advantage, because it prevents shell-code injection attacks.

But how do JIT engines, like LLVM, which dynamically generate machine-code, get around this?

答:
On Linux and many Posix systems, an application can change the protection of some range of the process address space in virtual memory using the mmap(2) and mprotect(2) syscalls.

So the JIT engine could use these (probably before emission of the machine code, but perhaps after it).

BTW, on some architectures, you may need to inform the CPU cache about newly available machine code segments, e.g. __builtin_clear_cache of GCC.


问:
Is it correct to keep version numbers of all components always the same?
We are planning to use a setup that uses several modules to complete a whole application, example modules include:

The core (code shared by all other modules)

The server

The client (Windows, OS X, Linux)

The client (iOS)

The client (Android)

Tool #1

Tool #2

And now while we preparing to deliver our first release, it is a good time to think about the numbering scheme. We have defined to use a major.minor.patch format, but we are struggling about one question:

Should every module have the same version number as newest release, and consequently, should we bump version numbers if there has been no update to them?

Example to illustrate:

1) Assume all our components are running on version 0.1.0 (early development), once we do a significant update, should then all components be bumped to version 0.2.0?

It also works the other way around:

2) Assume again every component is running 0.1.0 initially, and now we introduce a signifcant update (could be a GUI rework) on the Android client, should we then release a version 0.2.0 for every component, even though the other versions have not received any update?

And perhaps the most tricky one:

3) Assume that we still run 0.1.0 one very component in the start, and we figure out Tool #2 has a bug and we need to hotfix it to 0.1.1, should we also then update every component to 0.1.1?

I am currently doubting whether we should pursue correct versioning, or should go for compatability? People outside to the development team will most likely expect that all modules run on version 0.3.0 for example, while we as developers are a bit confused and perhaps feel uneasy with bumping a version number up, while the module did not have any change to it.

What is the best way to deal with this?

Edit, something I have forgot to mention, but which may change opinions is that all releases will be done in automated way. On Github/git a specific commit will be tagged being version major.minor.patch and after that the build system (here: Travis CI) will pick up the tag and automatically build every release and publish it somewhere if necessary and/or wanted.

答:
Take a look at semver.org a standard for versioning.

Translating it to your situation, it would probably mean that the major versions would not be compatible with each other, so a 1.0 server can not work with 2.0 clients.
The minor versions would be compatible with each other, so a 1.2 server can work with a 1.1 or a 1.5 client, but personally I would recommend to release all the components when you bump the minor version number.
Bugfix/patch numbers should be bumped when a bug was found, but I wouldn't release all components for this.

As for your question "Is it correct", of course it is. In case of versioning there is basically no right and wrong, the question you should ask yourself is: "is this versioning scheme convenient for us (and does it cost us extra work or saves us work), and is it clear to the user?".


答:
First off, there is no correct way.

However, I have found that keeping all version numbers the same across releases, regardless of whether things have changed or not, makes things much easier down the road. If I want to know what has been going on in a software, all I want is to be able to easily go from a version number to a state in version control, and see whats going on in there. Having a collection of unrelated version numbers makes doing that murky.

The alternative is that ultimately you have to maintain some sort of BOM for your software releases to know what's what, and those invariable end up out of date or incorrect, and everything just becomes a big mess.

There have been situations I've worked on where products did have a mismatch of version numbers for various dlls. It was a medical device software, and the developers rationalized that by not changing certain parts, they could avoid doing testing and verification for those parts. It may have saved work there, but it has created plenty of other work and harmed credibility with distributors when even the company wasn't sure what was what because of the hard to understand versioning scheme.

Title: Is it correct to keep version numbers of all components always the same?

Body:
We are planning to use a setup that uses several modules to complete a whole application, example modules include:

The core (code shared by all other modules)

The server

The client (Windows, OS X, Linux)

The client (iOS)

The client (Android)

Tool #1

Tool #2

And now while we preparing to deliver our first release, it is a good time to think about the numbering scheme. We have defined to use a major.minor.patch format, but we are struggling about one question:

Should every module have the same version number as newest release, and consequently, should we bump version numbers if there has been no update to them?

Example to illustrate:

1) Assume all our components are running on version 0.1.0 (early development), once we do a significant update, should then all components be bumped to version 0.2.0?

It also works the other way around:

2) Assume again every component is running 0.1.0 initially, and now we introduce a signifcant update (could be a GUI rework) on the Android client, should we then release a version 0.2.0 for every component, even though the other versions have not received any update?

And perhaps the most tricky one:

3) Assume that we still run 0.1.0 one very component in the start, and we figure out Tool #2 has a bug and we need to hotfix it to 0.1.1, should we also then update every component to 0.1.1?

I am currently doubting whether we should pursue correct versioning, or should go for compatability? People outside to the development team will most likely expect that all modules run on version 0.3.0 for example, while we as developers are a bit confused and perhaps feel uneasy with bumping a version number up, while the module did not have any change to it.

What is the best way to deal with this?

Edit, something I have forgot to mention, but which may change opinions is that all releases will be done in automated way. On Github/git a specific commit will be tagged being version major.minor.patch and after that the build system (here: Travis CI) will pick up the tag and automatically build every release and publish it somewhere if necessary and/or wanted.


答: No. If there has been no change to a module, it shouldn't get a new version number. Otherwise you're just sowing confusion and making more work for whoever's doing your release work. I think you'll also find it's easier to track down problems when you can see which modules have really changed as opposed to those which have simply had their rev bumped.</p>


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答:
Read Knuth

(corollary: many people have Knuth, but no one reads Knuth)

All the really good programmers I've worked with have some traits in common:

(1) Even though you don't have to be good at maths to do programming, they were anyway (and they liked it)

(2) They appreciate a quality I will call 'elegance' - not to be confused with brevity (!!!)

(3) They are good at designing software (even if none of us can explain what good design actually is)

In addition, I personally find the following traits handy:

(a) enjoying solving puzzles

(b) writing readable code

(c) a good memory

(d) can superficially adapt to other programming languages easily (breadth)

(e) learn your main language in depth (e.g. do the Java certification if Java is your environment (for clueless detractors that never did this but slag off certification since Microsoft's certification is (was?) really bad ... the benefit is not in having the piece of paper, the benefit is in the study))

(f) given the choice of doing something simple and easy and then moving on, or something super complicated that will take weeks/months, I do the simple thing.  I like simple, since it tends towards robustness, also it is more flexible when requirements change in mid stride, and is a lot easier to communicate to other team members

(g) if you do something you consider especially cunning, document the smeg out of it

Someone (Djikstra?) said that debugging is twice as hard as coding, therefore if you write code that is at the limits of your ability, you are by definition not smart enough to debug it.

========

Having said that, becoming a smart/better coder is not the same as advancing your career.

There is really only one 'secret ingredient' required for advancing your career, and it is people skills.

If you really want to progress your career, the best thing to do is to quit, and go sell cars for 6-12 months.


答:
Code documentation, at least the "automatic" kind, represents the least common denominator for people trying to understand the application.

The most sophisticated users would not appreciate automatic code documentation. They would much rather have "targetted" documentation that tells them what (little) they need to be told.

The least sophisticated users would not appreciate it for the opposite reason; they wouldn't understand it anyway.

The most "appreciative" users of automatic code documentation are those for whom "a little knowledge" is a dangerous thing." They may or may not understand the documentation (although they are likely to), but they'll feel good about "being kept in the loop." This audience includes most "managerial" types. If that's your main audience, automatic code documentation might be a good thing.


问:
Providing friendly URLs for a website vs. realities of database IDs
We have a database of resources, be they products, blog posts or something. We need to design a URL scheme to address them, for the public website.

Here are two examples that are database ID bound:

https://www.youtube.com/watch?v=7FPS6llqhXw

http://www.amazon.co.uk/gp/product/B000NHOMSQ

Here's an example that's friendly:

http://en.wikipedia.org/wiki/LED_circuit

(A little glimpse into my browsing life there)

I like the friendly URLs since you have an idea about what's on the end of the URL when you hover or see it in an email or document. It's better for SEO, or it used to be.

What happens when the document or product is renamed? Either because it changed (Wiki may not change but our resources could) or due to a typo, right? Our resources are very technical, long words and error prone.

Also, we have a database ID, which is a number. Let's look at an idea for an address of a video using a pretend rental store:

http://vidsyeah.com/video/sliding-doors/287171

The ID is obvious and is used in the DB look-up. Fine.

The sliding-doors bit is non-unique and just generated from the video title, it could be verified on GET, so if gliding-doors was entered and doesn't match what's really in doc 287171 it responds 404.

Or maybe it could be ignored, allowing humans to stick whatever they like in there, if someone ever cared to. So this URL would also work:

http://vidsyeah.com/video/anything-at_all/287171

The issue with verifying the friendly part is, as mentioned, the problem of renaming or typo correction. If the name changed, and in our domain that does happen, we don't want to break the URLs that are out there, so should we:

Just not verify the friendly part.

Verify, but add a 'history' of friendly parts to the database record so any previous friendly IDs still work!

Your thoughts and ideas are welcome.

Luke

答:
From a RESTful standpoint, URIs should follow a predictable and perphaps hierarchical structure to enhance usability.

This will make them easier to use by consumers.  If your data has relationships, then some sort of hierarchy would be necessary.

It looks like the scheme is :  \video\[name]\[id]

If the name isn't being used for any further classification it could be dropped in favor of \video\[id].

However, if you wish classify the videos then maybe the name is useful.

Examples:

\video\SwingingDoors\123

\video\SwingingDoors\124

\video\SlidingDoors\125

\video\SlidingDoors\126

Its really a design decision on how the access is modeled.


问:
algorithmic problem - Combining overlapping ranges
I'm looking for an idea to efficiently solve following problem:

I have a set of pairs of ranges (range = a pair of numbers), each range is unique (but has same size) e.g.

```<code>[
 [(0,6),(34,40)],
 [(1,7),(35,41)],
 [(3,9),(12,18)],
 [(2,8),(36,42)],
 [(13,19),(22,28)],
 [(23,29),(14,20)]
]
</code>```

Now I'd like to combine pairs of ranges, if ranges are overlapping e.g.

```<code>[(0,6),(34,40)] overlaps with [(1,7),(35,41)] -result-> [(0,7),(34,41)]
</code>```

So as a result for above set I'd like to get (now each pair may have ranges of different size)

```<code>[
 [(0,8),(34,42)],
 [(3,9),(12,18)],
 [(13,20),(22,29)]
]
</code>```

The set might be pretty big, I'd like to avoid quadratic complexity if possible.

EDIT: My best idea so far (in Python) is below. I'd like to know if you know a better(faster) way. Also I'm not sure if my idea of removing already combined pairs is valid:

```<code>def ranges_overlap(range1, range2):
    return range1[0] < range2[1] and range2[0] < range1[1]

def combine_pairs(pair1, pair2):
    return [(min(r1[0], r2[0]), max(r1[1], r2[1])) for r1, r2 in zip(pair1, pair2)]

def combine_overlapping_pairs(pairs):
    combined = []
    while pairs:
        pair1 = pairs.pop()
        already_combined = []
        for pair2 in pairs:
            for pair2_perm in itertools.permutations(pair2):
                does_overlap = True
                for range1, range2 in zip(pair1, pair2_perm):
                    if not ranges_overlap(range1, range2):
                        does_overlap = False
                        break

                if does_overlap:
                    pair1 = combine_pairs(pair1, pair2_perm)
                    already_combined.append(pair2)
                    break

        combined.append(pair1)
        # Not sure if I can do that
        for pair in already_combined:
            pairs.remove(pair)

    return combined
</code>```

答:
Third time's the charm, I hope.  I combined my original idea to sort the list first with Snowman's suggestion of using set theory.  The basic algorithm is:

Sort the pairs in lexicographic order by the first range.

Group adjacent pairs by if just the first ranges overlap.  I prove below that lexicographically sorted ranges will never overlap without being adjacent, which allows this step to be done in O(n).  This creates sets where the first ranges overlap.

Within each of those sets, sort again by the second range, and group by if the second ranges overlap.  This splits sets where the first ranges overlap into sets where the second ranges also overlap.

Within each set of sets, repeatedly combine pairs until you have one merged pair.

Here's an O(n log n) implementation in Haskell:

import Data.List
import Data.Tuple

type Range = (Int, Int)
type RangePair = (Range, Range)

rangesOverlap :: Range -> Range -> Bool
rangesOverlap (a,b) (c,d) =
  c <= a && a <= d ||
  c <= b && b <= d ||
  a <= c && c <= b ||
  a <= d && d <= b

pairsOverlap :: RangePair -> RangePair -> Bool
pairsOverlap (a, b) (c, d) = rangesOverlap a c

combineRanges :: Range -> Range -> Range
combineRanges (a,b) (c,d) = (min a c, max b d)

combinePairs :: RangePair -> RangePair -> RangePair
combinePairs (a, b) (c, d) = (combineRanges a c, combineRanges b d)

combineOverlapping :: [RangePair] -> [RangePair]
combineOverlapping = map swap . concat .
  map (combineSets. makeSet . map swap) . makeSet
  where makeSet = groupBy pairsOverlap . sort
        combineSets = map (foldl1 combinePairs)
```

<p>We wish to prove that if
  the ranges are lexicographically sorted, all the overlapping ranges will
  occur in adjacent rows.  Assume a counterexample exists where overlapping
  ranges are not in adjacent rows.  It will take the form of:</p>

```(a, b)
(c, d)
(e, f)
```

where (a,b) and (e,f) overlap with each other, but (c,d) does not overlap with either.

In order for (c,d) not to overlap with (a,b), d must be less than a or b
  must be less than c. c <= d because it is a range, and a <= c because of
  lexicographical sorting, therefore d >= a.  e <= b because of overlapping,
  and c <= e because of lexicographical sorting, therefore c <= b.  Therefore,
  if (a,b) and (e,f) overlap, then (a,b) and (c,d) always overlap, and no
  counterexample exists.

Body:
Third time's the charm, I hope.  I combined my original idea to sort the list first with Snowman's suggestion of using set theory.  The basic algorithm is:

Sort the pairs in lexicographic order by the first range.

Group adjacent pairs by if just the first ranges overlap.  I prove below that lexicographically sorted ranges will never overlap without being adjacent, which allows this step to be done in O(n).  This creates sets where the first ranges overlap.

Within each of those sets, sort again by the second range, and group by if the second ranges overlap.  This splits sets where the first ranges overlap into sets where the second ranges also overlap.

Within each set of sets, repeatedly combine pairs until you have one merged pair.

Here's an O(n log n) implementation in Haskell:

import Data.List
import Data.Tuple

type Range = (Int, Int)
type RangePair = (Range, Range)

rangesOverlap :: Range -> Range -> Bool
rangesOverlap (a,b) (c,d) =
  c <= a && a <= d ||
  c <= b && b <= d ||
  a <= c && c <= b ||
  a <= d && d <= b

pairsOverlap :: RangePair -> RangePair -> Bool
pairsOverlap (a, b) (c, d) = rangesOverlap a c

combineRanges :: Range -> Range -> Range
combineRanges (a,b) (c,d) = (min a c, max b d)

combinePairs :: RangePair -> RangePair -> RangePair
combinePairs (a, b) (c, d) = (combineRanges a c, combineRanges b d)

combineOverlapping :: [RangePair] -> [RangePair]
combineOverlapping = map swap . concat .
  map (combineSets. makeSet . map swap) . makeSet
  where makeSet = groupBy pairsOverlap . sort
        combineSets = map (foldl1 combinePairs)

We wish to prove that if
  the ranges are lexicographically sorted, all the overlapping ranges will
  occur in adjacent rows.  Assume a counterexample exists where overlapping
  ranges are not in adjacent rows.  It will take the form of:

(a, b)
(c, d)
(e, f)

where (a,b) and (e,f) overlap with each other, but (c,d) does not overlap with either.

In order for (c,d) not to overlap with (a,b), d must be less than a or b
  must be less than c. c <= d because it is a range, and a <= c because of
  lexicographical sorting, therefore d >= a.  e <= b because of overlapping,
  and c <= e because of lexicographical sorting, therefore c <= b.  Therefore,
  if (a,b) and (e,f) overlap, then (a,b) and (c,d) always overlap, and no
  counterexample exists.


答:
Keeping the ID in the URL is the most future proof method and as you demonstrated, the URLs can still look relatively good.

Another option used by multiple projects is to keep an history of previously used slugs. When the title changes, you update the slug and if someone tries looking for an obsolete slug, search in the list of old slugs. That way old slugs can be reused for new content (or not depending on your implementation).

Wordpress did that and so did the friendly_id gem which is probably the most used gem for managing friendly ids for Rails.

Also, while I like good looking URLs, I think it's important to remember that this is most likely a feature used by more tech savvy users. Some browsers are even starting to hide URLs (or part of it).

Title: Providing friendly URLs for a website vs. realities of database IDs

Body:
We have a database of resources, be they products, blog posts or something. We need to design a URL scheme to address them, for the public website.

Here are two examples that are database ID bound:

https://www.youtube.com/watch?v=7FPS6llqhXw

http://www.amazon.co.uk/gp/product/B000NHOMSQ

Here's an example that's friendly:

http://en.wikipedia.org/wiki/LED_circuit

(A little glimpse into my browsing life there)

I like the friendly URLs since you have an idea about what's on the end of the URL when you hover or see it in an email or document. It's better for SEO, or it used to be.

What happens when the document or product is renamed? Either because it changed (Wiki may not change but our resources could) or due to a typo, right? Our resources are very technical, long words and error prone.

Also, we have a database ID, which is a number. Let's look at an idea for an address of a video using a pretend rental store:

http://vidsyeah.com/video/sliding-doors/287171

The ID is obvious and is used in the DB look-up. Fine.

The sliding-doors bit is non-unique and just generated from the video title, it could be verified on GET, so if gliding-doors was entered and doesn't match what's really in doc 287171 it responds 404.

Or maybe it could be ignored, allowing humans to stick whatever they like in there, if someone ever cared to. So this URL would also work:

http://vidsyeah.com/video/anything-at_all/287171

The issue with verifying the friendly part is, as mentioned, the problem of renaming or typo correction. If the name changed, and in our domain that does happen, we don't want to break the URLs that are out there, so should we:

Just not verify the friendly part.

Verify, but add a 'history' of friendly parts to the database record so any previous friendly IDs still work!

Your thoughts and ideas are welcome.

Luke


答:
You could of course store the weight in each object, or store a directory of instances in the class, if you create or control the classes.

If not, you may be interested in the Counter class, a dictionary that maps into numeric values. It can be extended to map objects to weights. Here's a sketch:

```<code>from collections import Counter

class Weights(object):
    def __init__(self):
        self.counts = Counter()
        self.objs = dict()
    def __setitem__(self, item, value):
        _id = id(item)
        self.counts[_id] = value
        self.objs[_id] = item
    def __getitem__(self, item):
        _id = id(item)
        return self.counts[_id]
    def keys(self):
        return [ self.objs[i] for i in self.counts.keys() ]
    def items(self):
        return [ (self.objs[i], c) for (i, c) in self.counts.items() ]
    def most_common(self, n=None):
        return [ (self.objs[i], c) for (i, c) in self.counts.most_common(n) ]

o1, o2, o3 = [ object() for i in range(3) ]

weight = Weights()

weight[o1] = 3
weight[o2] = 4.4
weight[o3] = 1.1
weight[o2] += 1.1
print weight.most_common() # tuples sorted by highest weight first
</code>```

It yields something like:

```<code>[(<object object at 0x106cd30b0>, 5.5), (<object object at 0x106cd30c0>, 3), (<object object at 0x106cd30d0>, 1.1)]
</code>```

(The first item in each tuple is the corresponding object.)

While Counter requires a hashable value as a key, Weights maps each object into its id (which is inherently hashable), internally. While this is just a sketch (some other Counter methods are not provided), it does the sort of object tracking you sought.

Title: Efficient "Object with weights" structure

Body:
I need to find an "efficient" data structure / set of algorithms to do the following things:

I have a list of objects. I need to assign them weights and later on increase or decrease these weights.

For instance:
We have the hashmaps {o1}, {o2}, {o3}. The {o}'s don't have any particullar structure, just random json.

I am looking for a way of saying: Increase the weight of o1 by 1. Increase the weight of o2 by 1. Increase the weight of o1 by 1. Now give me the results sorted by their weight.

I am using Python. So far I have tried using a normal hashmap to store them, but the problem is that I can't just hash the {o}'s. I thought of hashing the pointer of the {o}'s in memory, but it seems I don't have access to it in Python.

Body:
You could of course store the weight in each object, or store a directory of instances in the class, if you create or control the classes.

If not, you may be interested in the Counter class, a dictionary that maps into numeric values. It can be extended to map objects to weights. Here's a sketch:

from collections import Counter

class Weights(object):
    def __init__(self):
        self.counts = Counter()
        self.objs = dict()
    def __setitem__(self, item, value):
        _id = id(item)
        self.counts[_id] = value
        self.objs[_id] = item
    def __getitem__(self, item):
        _id = id(item)
        return self.counts[_id]
    def keys(self):
        return [ self.objs[i] for i in self.counts.keys() ]
    def items(self):
        return [ (self.objs[i], c) for (i, c) in self.counts.items() ]
    def most_common(self, n=None):
        return [ (self.objs[i], c) for (i, c) in self.counts.most_common(n) ]

o1, o2, o3 = [ object() for i in range(3) ]

weight = Weights()

weight[o1] = 3
weight[o2] = 4.4
weight[o3] = 1.1
weight[o2] += 1.1
print weight.most_common() # tuples sorted by highest weight first

It yields something like:

[(<object object at 0x106cd30b0>, 5.5), (<object object at 0x106cd30c0>, 3), (<object object at 0x106cd30d0>, 1.1)]

(The first item in each tuple is the corresponding object.)

While Counter requires a hashable value as a key, Weights maps each object into its id (which is inherently hashable), internally. While this is just a sketch (some other Counter methods are not provided), it does the sort of object tracking you sought.


问:
What is meant by an HTML5 application?
Since HTML5 is still only a markup language, what is meant when people say "HTML5 application"? Please explain.</p>

答:
An HTML5 application is an application that uses HTML5/Javascript/CSS3 as its primary means of achieving a User Interface.

The term is significant, largely because this is considered a platform-independent way to get an application onto as many different mobile devices as possible.  Android and iOS are pretty much completely different, but both platforms will work with applications written in HTML5/Javascript/CSS3.  All you need is an HTML5 compliant browser.

Title: What is meant by an HTML5 application?


问:
How do you track what you and your team are working on day-to-day?
I'm struggling with how to keep track of what myself and people on my team actually do each day. I get a good broad picture by going over completed cards each week and stand-ups help a bit, but I feel like I don't have a good handle on the day-to-day workings of my team. Cards will stay in progress for days on end without an update at the daily stand-up, and some engineers are my team aren't the most communicative.

I've thought about implementing some sort of daily record that everyone fills out (via a mailing list or a shared google doc) but this seems fairly cumbersome and manual.

Monitoring GitHub activity does an ok job but can be a little bit overwhelming with how many emails it sends out everyday. I've thought about trying to build a digest system for it, but don't have the time to spare.

What strategies have you implemented to stay on top of what your team is doing everyday so that you can measure work on "in progress" tasks?

答:
Don't micro-manage your developers!

Productive software development requires long stretches of concentrated mental effort.  It's not realistic to expect them to produce constant output.  If you begin measuring them on a daily basis, they will restructure their work so that they always produce some discernible artifacts for you to see each day.  That may or may not have a positive impact on your software quality.  It will almost certainly have a negative impact on your developers' efficiency.


答:
Create and make good use of various IM chat rooms for the various configurations.  Some may be broad like @engineers and some may be specific such as @newFeatureA

Consider making daily standup include a review of in-flight tickets.

Use a open environment that supports collaboration and make sure that QE and the primary product owner sit in the middle of the developers.  You'll overhear a lot and get an idea from seeing screens around you.

As Robert points out, above all don't be seen to be micro-managing (note the use of 'be seen', i.e. regardless of your actual intent).

Ultimately we track what is accomplished over time and see what our velocity is from that.  Focusing on during-the-day progress is counter-productive as people will become demoralized and/or leave.

Title: How do you track what you and your team are working on day-to-day?

Body:
I'm struggling with how to keep track of what myself and people on my team actually do each day. I get a good broad picture by going over completed cards each week and stand-ups help a bit, but I feel like I don't have a good handle on the day-to-day workings of my team. Cards will stay in progress for days on end without an update at the daily stand-up, and some engineers are my team aren't the most communicative.

I've thought about implementing some sort of daily record that everyone fills out (via a mailing list or a shared google doc) but this seems fairly cumbersome and manual.

Monitoring GitHub activity does an ok job but can be a little bit overwhelming with how many emails it sends out everyday. I've thought about trying to build a digest system for it, but don't have the time to spare.

What strategies have you implemented to stay on top of what your team is doing everyday so that you can measure work on "in progress" tasks?


问:
What do Java developers think of Scala?
I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.</p>

答:
It's an excellent language that is simpler than Java in many ways.

Most people won't like it, Java programmer or not, for the same reasons that most people, programmers or not, don't like learning new programming languages.  I suspect that most people who learned a programming language did not even like learning that.

If you're worried about a language being as complicated as C++, I would avoid Clojure like the plague.  Whining that Scala is more complicated than Clojure has become the fallback argument for people who are completely ignorant regarding one or both languages.

Clojure has macros, which means you can alter the language's syntax as much as you want, giving you not just "a myriad of different ways of doing things" but an almost infinite number of ways of doing things.  And none of this new syntax the programmers are creating with the macros will be documented anywhere in the language specification.

"But we can avoid using macros or regulate which ones are allowed in our code", you say.  Congratulations, you're now having "to artificially limit what language features you're going to use and what not", which is exactly what the babbling idiots who are using Clojure of Scala used as their reason for avoiding Scala to begin with.

Title: What do Java developers think of Scala?


答:
I talk to them.

Technology cannot solve social problems. You have short morning standups. What did you do yesterday? What will you do today? Any impediments?

If something sounds fishy (or I'm curious), I stop and ask questions: "You were working on XYZ yesterday, how'd that turn out?". This forces people to pay attention, and to actually know what's going on. It also keeps you the team lead in the loop (and paying attention, and knowing actually what's going on). This needs to be on time, and short (10 minutes max). Anything else and people won't "shelve" work. They'll stop and wait for the standup and then take time to get started again. Some will do that anyways, but it's largely unavoidable.

Then I stop by everyone's desk in the afternoon. Not every afternoon (though it might be more than every afternoon for new people), not at the same time, but around the same time (so it's both informal, and regular). "Any problems? Any impediments?"

You'll be surprised how often you'll encounter problems when people are one on one.

If people have no problems, great; get back to work. If they don't have problems all week? Problem. You're not challenging them enough, or they're not opening up. Ask how XYZ (that they mentioned in standup) is going. Make them explain things.

This isn't micromanagement. You're not telling them how to do their jobs. You're not babysitting them. You're there to remove impediments from their day to day life. You need information to do that. As long as you keep your team out of meetings, and project managers out of their cubes, then one person stopping by to help once a day isn't going to cause them grief. But all these interactions need to come from the "I am here to help you" vein.

Another thing I will do is review changesets (by myself, informally). I can then see how frequently people check in, how large their changesets are, how that matches what they reported, how often they re-do things, how many bugfixes they have, and so on. A work item changing status to "done" is nearly meaningless. Look at the code. Does it seem done?

note: One extremely serious side point: how big is your team? Is it more than 7 people? Of course you won't be able to keep track of everything going on if your team is too big.


问:
String encoding in string instances from different languages
I recently got a requirement to develop a chat-like application, or rather, a foundation of classes and methods that would allow certain applications to have chat-like features. The framework must be usable in at least two languages: Visual Basic 6 and C#.

If VB6-Application A were to transmit string data to CSharp-Application B, when the data is received by CSharp-Application B and placed into a string, can I assume the string will contain the same information it contained when VB6-Application A sent it? (i.e. it will contain the same sequence of bytes that was sent from the original string instance in the VB6 app.)

答:
Echoing @Neil's comment, you have to make sure the encoding is the same on the sending/receiving ends. Assuming that you can pass a byte array from one language to the other, you will want to think about what encoding to use. UTF-8 is likely the most popular now. If you're not familiar with character encodings, please take a brief moment to check out the basics, courtesy of Joel Spolsky.

Doing a little research, it sounds like VB6 stores strings internally as UTF-16 but tends to convert to ANSI for the outside world. So an approach you could take on the VB side for conversions between UTF-8 and byte arrays is found here. The C# side is a little less convoluted and you can find an MSDN page with nice code samples here.


答:
You can call yourself a Senior when:

You can handle the entire software development life cycle, end to end

You lead others, or others look to you for guidance.

You can self manage your projects

Software development is a curious creature unlike other fields.

Sometimes, a fresh punk out of college can run circles around veterans who have 20+ years of "experience". Programming is a bizarre world where code is king.

Some achieve the above in 2 years or less, others take 10 years.


答:
I don't know about other environments but when it comes to large (often open source) PHP projects that other people have written, phpXRef is an absolute life saver (especially if the doc is placed online and Google can index it).

Even a badly commented project can at least help me track down where things have been defined and where they are used (for example when refactoring).

When well commented, the resultant pages form close to a perfect Bible for the codebase (for my uses anyway).

Furthermore, my prefered IDE will auto-generate the comment block (if I type /**) which does roughly 75% of the commenting work for me. It is amazing how many stupid things I have been stopped from committing over my coder lifetime just because I have had to explain to other people (and future me) what I am doing. When my comment for the doc generator is bigger than the method this usually means I have not had enough coffee and might want to think a bit harder.

Those self-same comment blocks also create the inline completion "help" text so I can see exactly what was expected (by the other coders) as I am writing the function call. This is a massive productivity boost for me (especially in those rare edge cases where some other helpful developer has written "for goodness sake do/do-not X" - which can save a lot of pain.

I cannot stress enough how useful it is to have the expected input types specified in complex (and often badly named) PHP projects and the argument order in less frequently used methods. Even with my own code, I cannot always remember what arguments I specified for something I've not touched in an age.

In one instance it meant that the source of the recurrent problems was that, for some reason that reflects badly on prior developers, some functions and even constants were defined in a huge number of places (with a degree of inconsistency for added "fun"). That was the sign to walk away from the project.

In larger projects which started before I joined in, I can see which developer (assuming they tagged the class file with a name and email) created the class and simply being able to find and talk to the right developer is hugely helpful.

Automatic task lists - using the @todo tag (common in the kind of projects I find myself working in) means that the documentation can keep track of stuff that needs some more work (or features that are acknowledged to be missing). Again my IDE keeps track of this and that alone acts as a good guide as to what needs my attention first.

Lastly (and very important to me) it removes the non-trivial overhead of writing all that out and then trying to keep it up to date when some (read many) coders commit changes and don't talk to the documentation maintainers.

So, the reasons include:

Saving later developers a stack of time,

Keeping track of where functions are called (and defined),

Spotting silly coding,

Finding (as another has pointed out) when something is obviously missing,

Simplifying refactoring (never much fun)

(In many cases) getting an idea what the developer was trying to do (assuming he or she left some notes).

If the project is complex enough to have multiple licenses going on (no fun) I can quickly see which licenses apply to any given section. Admittedly, this is a side bonus.

Getting an idea of who to talk to about a project file.

Automatic task lists

Also, do not underestimate the value of keeping pointy-haired bosses happy at the touch of a button.

In short the "auto documentation comments" are vital to my coding habits. I am sure there are many who think that's lame but I am also just as sure that there are a fair few folks that know exactly what I am saying. I don't know how I survived before discovering phpXRef (and my favourite IDE).

ContentLicense: CC BY-SA 4.0


问:
When to use C over C++, and C++ over C?
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks

答:
C is probably preferable to C++ when the C code is generated (e.g. in implementations of higher-level languages). For example, there are several Lisp-like compilers which emit C code (e.g. Chicken, Scheme48 ...), but I know none which emits genuine C++ code (my MELT tool emits C++ code, but I won't call that code genuine C++ code, it uses very few C++ features).

C code is also easier to prove semi-automatically. Static analyzers like Frama-C (where you annotate your C code with ACSL comments to help the prover reason about your code) are available for C, but not that much for full C++11.

Title: When to use C over C++, and C++ over C?