问:
Should I also mock header files?
So, I am part of a very large project which has, as yet, no unit testing (shudder!) and I want to introduce it.

I plan on using Google Test and Google mocks.

The code is large and unwieldy and suffers from "header spaghetti".

If I wish, for simplicities sake, to test only a.cpp which calls only a single function in b.cpp, then I can use Google Mock to generate a mock for b.cpp.

However, if I #include b.h in a.cpp and in my test suite, I find that b.h #includes a number of other headers, which in turn ... in the end, I am #including hundreds of headers.

There will be no restructuring of header files (any time soon, if ever). I just have to live with that.

Until now, the code has only been built as a complete system, for an ARM processor, and now I want to build a.cpp plus b.cpp plus Google test to run on Linux.

I am having major problems as there are several hundred (!) compiler switches in the system build and I can't easily see which are needed where, which are ARM only, what would replace them for Linux, etc.

Plus, some of them contain #defines which expand to function calls (especially from trace log, but also for others), and I don't know where to find those in order to mock them.

Finally the question: how is this normally handled? Should I make a mock of b.h, which contains only what is needed by a.cpp?

If so, do I have to do it manually, or can Google Mock help in any way?

And, nope, the code won't be restructured; at least not immediately, for fears of destabilizing it.

I really do not like the idea of pulling in the majority of headers in the system, but nor can I find an easy way to mock them :-(

答:
The problem you are going to face is that the style of unit testing you have chosen, where everything outside a single file gets mocked, is actually useless when testing a code base not written to be compatible with it.

Your alternatives are:

exhaustively confirm that conclusion, and tell your team 'I tried, but there is no point in unit testing'.

rewrite the code (which you have said you can't do).

adopt a definition/style of unit testing that does add value given the existing code base

The latter would mean:

no mocking of anything except external hardware or timing interfaces

building tests incrementally upwards from the lowest level standalone components to the top level integrated systems.

using existing build and header files (because if some code doesn't work with a given compiler flag, and that compiler flag is used, the test must fail).

In other words, for a legacy embedded system, there is no such thing as unit testing in the sense you get with higher level languages. Simply because you are always integrating with the compiler, if nothing else. And that compiler is typically such a sketchy mess of bugs, workarounds and undocumented limitations that you really want to be testing the exact code to be used, not an abstraction.

Title: Should I also mock header files?


问:
Should every member of a team use the same IDE?
Do you think it makes sense to enforce that every member of a team must use the same IDE?

For instance all engineers that are already on the team use IDE X. Two new engineers come and want to use IDE Y instead because that's what they have been using for several years now.

Do you have any experience with "mixed IDE" teams? If so what is it?

答:
If everyone wants to, that's fine, but different people might want to use different editors/IDEs.  I wouldn't really want people to force me to use an editor other than my preferred one if I were working on something big with a team, and I doubt I'm alone.  People may be most happy with the situation if you don't force them to use a particular editor.

BTW, Emacs!

ContentLicense: CC BY-SA 2.5


问:
Rebol refinements vs. dialects vs. objects
I occasionally get conflicted when using a language that isn't Rebol (happens from time to time) and get to thinking, hm—would life be easier in Rebol if this thing worked this way?

To illustrate my current instance, in Rebol you send a message as follows:

```<code>send foo@bar.baz "A Message"
</code>```

It's always been one of the killer one-liners, very concise, most elegant. Using refinements, you can start to build up a more complex message:

```<code>send/subject/attach foo@bar.baz "Hi Foo!" "A Message" %me.jpg
</code>```

Still relatively concise, but starting to fill out a little. As you sculpt your message, it starts to get a bit messy:

```<code>send/subject/attach/header
    [foo@bar.baz eric@bar.baz]
    "Hi Folks! – Chris"
    "A Message"
    make object! [X-User-Agent: join "Rebol " system/version]
</code>```

That's the current prescribed way to send an email (line feeds are optional here, but become essential as component parts start to add up).

Rebol is nothing if not versatile though, we can dream of an alternate approach using dialects:

```<code>send [
    ; no delimiters required, we can discern recipients
    ; by the use of the email! datatype:
    foo@bar.baz eric@bar.baz

    ; two string! values indicate the first as the subject
    ; second as the message
    "A Message"
    "Hi Folks!"

    ; a few attachments courtesy of the file! datatype
    %me.jpg %you.jpg %the-world.jpg

    ; and then some set-word!/value headers
    X-User-Agent: "Rebol"
]
</code>```

Sans comments:

```<code>send [
    foo@bar.baz eric@bar.baz
    "A Message"
    "Hi Folks!"
    %me.jpg %you.jpg %the-world.jpg
    X-User-Agent: "Rebol"
]
</code>```

Pretty spiffy, but dialects get a bit tricky as you start to pull in conditional arguments, external data, further customisation. We can build that up somewhat procedurally:

```<code>send collect [
    keep foo@bar.baz
    if "Monday" = pick system/locale/days now/weekday [
        keep eric@bar.baz
    ]
    keep subject ; 'subject defined elsewhere
    keep {A Long Message}
    keep read %photos/
    keep compose [X-User-Agent: (join "Rebol " system/version)]
]
</code>```

Seems reasonable, except we lose a bit of expressivity as the implicit metadata offered by datatypes is obscured by the additional code. Even just the addition of words not of our current domain (collect, keep).

Which brings me to the object-based world (which seemingly covers the way the popular languages out there approach things). In this composite, non-existent Language X, we recover some of the expressivity through the explicit use of named actions:

```<code>message = mailer.new

// pity poor language X, only one string type:
message.addRecipient 'foo@bar.baz'
if (today = 'Monday') { // assumed 'today value
    message.addRecipient 'eric@bar.baz'
}

message.subject = "A Message"
message.body = "Hi Folks!"
message.attach filesystem.read 'photos/'
message.header['X-User-Agent'] = 'Language X'

message.send

// Rebol's SEND function needs a return value with some
// status feedback. For another day...
if (message.isSentOk) {
    print "Hooray!"
}
</code>```

Beauty is in the eye of the beholder: this approach leaves you in no doubt what each line is for, yet simultaneously (to my eyes) appears heavy-handed. We get to our destination procedurally, send happens after we've established the details of the message. In my moments of doubt, I wonder if having send [...] states the intent before we're ready.

You could easily transliterate the Language X approach to Rebol, or have it inform the approach taken by a dialect:

```<code>mailer [
    new message
    add recipient foo@bar.baz
    if today = "Monday" [
        add recipient eric@bar.baz
    ]
    subject: "A Message"
    body: "Hi Folks!"
    attach read %photos/
    send
    probe status
]
</code>```

My question then is: Is the Language X object approach/influence something to covet, or does one or other Rebol approach retain enough expressivity as complexity increases?

PS: Not just mail—I think about this with regard to the <canvas> tag and the idea of a procedural graphic format as opposed to the explicit <svg>.

答:
In c#, it is

```<code>Send("foobar@baz","A Message");
</code>```

or

```<code>Send("foobar@baz, eric@bar.baz", "Hi, folks","A Message", "me.jpg");
</code>```

No need to disambiguate the method names, thanks to overloading.

With named parameters, it becomes

```<code>Send(addresses = "foobar@baz, eric@bar.baz",
    title = "Hi, folks",
    message = "A Message",
    attachment = "me.jpg");
</code>```

Any or all of which can be optional.

The "message" variation looks like this.  It may seem heavy-handed, but each bit of code means something:

```<code>message = mailer.NewMessage();

message.addRecipient("foo@bar.baz");

if (DateTime.Now.DayOfWeek = DayOfWeek.Monday) {
    message.AddRecipient("eric@bar.baz");
}

message.Subject = "A Message";
message.Body = "Hi Folks!";
message.Attach("photos"); // Folder within 'Current" folder
message.Header.Add("X-User-Agent", "Language X");

message.Send();
</code>```

With object initializers, it looks like this.  Note that you can use a factory method for the initial object creation and still take advantage of this syntax:

```<code>message = mailer.NewMessage()
{
    addresses = "foobar@baz, eric@bar.baz",
    title = "Hi, folks",
    message = "A Message",
    attachment = "me.jpg"
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In c#, it is

Send("foobar@baz","A Message");

or

Send("foobar@baz, eric@bar.baz", "Hi, folks","A Message", "me.jpg");

No need to disambiguate the method names, thanks to overloading.

With named parameters, it becomes

Send(addresses = "foobar@baz, eric@bar.baz",
    title = "Hi, folks",
    message = "A Message",
    attachment = "me.jpg");

Any or all of which can be optional.

The "message" variation looks like this.  It may seem heavy-handed, but each bit of code means something:

message = mailer.NewMessage();

message.addRecipient("foo@bar.baz");

if (DateTime.Now.DayOfWeek = DayOfWeek.Monday) {
    message.AddRecipient("eric@bar.baz");
}

message.Subject = "A Message";
message.Body = "Hi Folks!";
message.Attach("photos"); // Folder within 'Current" folder
message.Header.Add("X-User-Agent", "Language X");

message.Send();

With object initializers, it looks like this.  Note that you can use a factory method for the initial object creation and still take advantage of this syntax:

message = mailer.NewMessage()
{
    addresses = "foobar@baz, eric@bar.baz",
    title = "Hi, folks",
    message = "A Message",
    attachment = "me.jpg"
};


问:
How to see Entity Framework code with ASP.NET MVC from a software architecture viewpoint?
Let's say I'm starting a Web Application project that uses
a) ASP.NET MVC
b) Entity Framework

In terms of Software ARchitecture, correct me if I'm wrong,

-1) Could I place all my Entity Framework code in a Data Access Layer folder ( DAL )?

Furthermore,

-2) Would it be correct to say that the Entity Framework code which is within the Data Access Layer Folder (DAL) is part of the Model in the ASP.NET MVC from a software architecture perspective?

答:
In a simple application you can use a single class as EF entity, domain model, and view model.

In more complex applications all these models became different classes. For example, code first entities and ASP.NET MVC models have different annotations (KeyAttribute in EF, DisplayFormatAttribute in MVC), and usually you shouldn't mix them in a single class.

Also, all EF properties should be writeable, but domain properties can be read-only. MVC models can contain specific SelectList, but domain models and entities shouldn't.

So in complex application you have separated models at each application's tier (presentation, domain, data-access), and you should map these models at tier's boundaries.

Lets look the small example of a blog. Each post in a blog has creation date/time and (imaging) a category:

EF

```<code>[TableName("PostCategories")]
public class EfCategory
{
    public int CategoryId { get; set; }

    public string Name { get; set; }
}

public class EfPost
{
    public DateTime Created { get; set; }

    public virtual Category Category { get; set; }

    public int CategoryId { get; set; }

    . . .
}
</code>```

You see, Post.Created is writeable and readable property, and Category has TableName attribute. Can you use these classes in the domain tier?

No. First, the creating date/time property is read-only in the domain, you can't change it. Second, what if you'll want rewrite data-access with NHibernate or ADO.NET? You'll can't cause your domain model Category has the attribute TableName.

So, you can create duplicate domain models:

Domain

```<code>public class DomainCategory
{
    public int Id { get; private set; }

    public string Name { get; private set; }

    public DomainCategory(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

. . .

public EfCategoryRepository : ICategoryRepository
{
    private readonly DbContextFactory dbContextFactory;

    . . .

    public CategoryRepository(DbContextFactory dbContextFactory)
    {
        this.dbContextFactory = dbContextFactory;
    }

    . . .

    public DomainCategory GetById(int id)
    {
        using (var dbContext = dbContextFactory.CreateReadOnlyContext())
        {
            var entity = dbContext.Set<EfCategory>.Single(c => c.Id == id);

            return new DomainCategory(entity.CategoryId, entity.Name);
        }
    }
}
</code>```

Now the domain's interface ICategoryRepository that "knows" about domain models, is implemented by EF data access class EfCategoryRepository. This implementation "knows" about EF models and can map EF to domain.

Domain (continue)

```<code>public class DomainPost
{
    public DomainCategory { get; set; }

    public DateTime Created { get; private set; }

    . . .

    public DomainPost(EfCategory category, DateTime created, ...)
    {
        Category = new DomainCategory(category.CategoryId, category.Name);
        Created = created;
        . . .
    }
}
</code>```

Domain's property Created is read-only dislike the EF's property.

Finally, if we think about view (ASP.NET MVC) edit model, we'll find that this model should contain the list of categories and shouldn't contain Created cause user can't change it:

Presentation

```<code>public MvcEditPost
{
    public int Id { get; set; }

    [Display("Category")]
    public int CategoryId { get; set; }

    public IEnumerable<SelectListItem> Categories { get; set; }
}

public ActionResult Edit(int id)
{
    var domainPost = postRepository.GetById(id);
    var modelPost = new MvcEditPost
    {
        Id = domainPost.Id,
        CategoryId = domainPost.Category.Id,
        Categories = categoryRepository.GetAll()
                                       .Select(c => new SelectListItem
                                       {
                                           Selected = c.Id == domainPost.Category.Id,
                                           Text = c.Name,
                                           Value = c.Id.ToString(),
                                       }),
    };

    return View(modelPost);
}

@model MvsEditPost
@using (Html.BeginForm("Post", "Edit", { Id = Model.Id }))
{
    @Html.DropDownListFor(m => m.CategoryId, Model.Categories)
}
</code>```

So, the presentation code is also "knows" about both presentation and domain models and can map firsts to seconds. This model differentiation let you make all tiers independent. More precisely, a presentation tier and a data-access tier are depending on a domain tier now. So you can simple rewrite data-access (SQL Server to Oracle, EF to NHibernate, Single data-server to cloud), or you can simple rewrite presentation (MVC to Desktop, MVC to Console). You wouldn't be able to do it without models' differentiation.

Body:
In a simple application you can use a single class as EF entity, domain model, and view model.

In more complex applications all these models became different classes. For example, code first entities and ASP.NET MVC models have different annotations (KeyAttribute in EF, DisplayFormatAttribute in MVC), and usually you shouldn't mix them in a single class.

Also, all EF properties should be writeable, but domain properties can be read-only. MVC models can contain specific SelectList, but domain models and entities shouldn't.

So in complex application you have separated models at each application's tier (presentation, domain, data-access), and you should map these models at tier's boundaries.

Lets look the small example of a blog. Each post in a blog has creation date/time and (imaging) a category:

EF

[TableName("PostCategories")]
public class EfCategory
{
    public int CategoryId { get; set; }

    public string Name { get; set; }
}

public class EfPost
{
    public DateTime Created { get; set; }

    public virtual Category Category { get; set; }

    public int CategoryId { get; set; }

    . . .
}

You see, Post.Created is writeable and readable property, and Category has TableName attribute. Can you use these classes in the domain tier?

No. First, the creating date/time property is read-only in the domain, you can't change it. Second, what if you'll want rewrite data-access with NHibernate or ADO.NET? You'll can't cause your domain model Category has the attribute TableName.

So, you can create duplicate domain models:

Domain

public class DomainCategory
{
    public int Id { get; private set; }

    public string Name { get; private set; }

    public DomainCategory(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

. . .

public EfCategoryRepository : ICategoryRepository
{
    private readonly DbContextFactory dbContextFactory;

    . . .

    public CategoryRepository(DbContextFactory dbContextFactory)
    {
        this.dbContextFactory = dbContextFactory;
    }

    . . .

    public DomainCategory GetById(int id)
    {
        using (var dbContext = dbContextFactory.CreateReadOnlyContext())
        {
            var entity = dbContext.Set<EfCategory>.Single(c => c.Id == id);

            return new DomainCategory(entity.CategoryId, entity.Name);
        }
    }
}

Now the domain's interface ICategoryRepository that "knows" about domain models, is implemented by EF data access class EfCategoryRepository. This implementation "knows" about EF models and can map EF to domain.

Domain (continue)

public class DomainPost
{
    public DomainCategory { get; set; }

    public DateTime Created { get; private set; }

    . . .

    public DomainPost(EfCategory category, DateTime created, ...)
    {
        Category = new DomainCategory(category.CategoryId, category.Name);
        Created = created;
        . . .
    }
}

Domain's property Created is read-only dislike the EF's property.

Finally, if we think about view (ASP.NET MVC) edit model, we'll find that this model should contain the list of categories and shouldn't contain Created cause user can't change it:

Presentation

public MvcEditPost
{
    public int Id { get; set; }

    [Display("Category")]
    public int CategoryId { get; set; }

    public IEnumerable<SelectListItem> Categories { get; set; }
}

public ActionResult Edit(int id)
{
    var domainPost = postRepository.GetById(id);
    var modelPost = new MvcEditPost
    {
        Id = domainPost.Id,
        CategoryId = domainPost.Category.Id,
        Categories = categoryRepository.GetAll()
                                       .Select(c => new SelectListItem
                                       {
                                           Selected = c.Id == domainPost.Category.Id,
                                           Text = c.Name,
                                           Value = c.Id.ToString(),
                                       }),
    };

    return View(modelPost);
}

@model MvsEditPost
@using (Html.BeginForm("Post", "Edit", { Id = Model.Id }))
{
    @Html.DropDownListFor(m => m.CategoryId, Model.Categories)
}

So, the presentation code is also "knows" about both presentation and domain models and can map firsts to seconds. This model differentiation let you make all tiers independent. More precisely, a presentation tier and a data-access tier are depending on a domain tier now. So you can simple rewrite data-access (SQL Server to Oracle, EF to NHibernate, Single data-server to cloud), or you can simple rewrite presentation (MVC to Desktop, MVC to Console). You wouldn't be able to do it without models' differentiation.


答:
I guess you are talking about a single asp .net MVC website?

I think the intention of Microsoft is the EF is the M in MVC, your entities are you models, you map them into views and persist them to a db which is automagically created for you.

However. This tends to fall down on larger projects. Conceptually EF is part of the data access layer, in the same way as SqlConnections and DataReaders etc. Ideally you should put wrap it in a repository of some kind, make sure it only calls Stored Procedures and hide it away from your domain models.

Of course if you do this a lot of the time saving features of EF are made redundant. so you have to make a call about where to draw the line.

Title: How to see Entity Framework code with ASP.NET MVC from a software architecture viewpoint?

Body:
Let's say I'm starting a Web Application project that uses
a) ASP.NET MVC
b) Entity Framework

In terms of Software ARchitecture, correct me if I'm wrong,

-1) Could I place all my Entity Framework code in a Data Access Layer folder ( DAL )?

Furthermore,

-2) Would it be correct to say that the Entity Framework code which is within the Data Access Layer Folder (DAL) is part of the Model in the ASP.NET MVC from a software architecture perspective?


问:
What is the usefulness of private variables?
While I've never used a language that had built-in variable privacy, a book I'm reading by Douglas Crockford explains a way to create privacy in JavaScript, however it doesn't make sense to me so. The term "private" isn't something I think of as even being possible in a programming environment, since everyone working on the code can potentially change any mutable object or method right?

So the two things that don't make sense to me are

how privacy is helpful

how privacy is defined - fundamentally one developer can't keep something in source code absolutely private ("untouchable", as I understand it) from another developer, so where does one consider the variable "private"? When it's hard to reach?

Can someone explain this, possibly with a "real-world" example?

答:
Sure, a developer with access to the source code could start manipulating whatever they want. And in the process make something very fragile and unmaintainable.

By making as much private as possible, and respecting that, and only exposing well defined interfaces, you can make it simple to change things behind the scene to, for example, fix bugs or improve performance. If other code is messing around with variables, then changes are quite difficult, because they will cause that other code to break.

I'm unsure exactly how Javascript handles privacy, but in languages like Java and C++, there is some compiler support for enforcing privacy.

Consider a class representing an IP address:

```<code>public class IpAddress {

  public string ipAddress;

}
</code>```

Right now, anyone can put whatever they want into ipAddress (it's a public field).

```<code>IpAddress ia = new IpAddress();
ia.ipAddress = "weeeee!";
</code>```

Last I checked, weeeee! was not a valid IP address. But, by making it private, we can make sure invalid addresses are thrown out. Of, course, we'll still need a way of accessing it and updating it. So we make public methods:

```<code>public class IpAddress {

  private string ipAddress;

  public string toString() {
    return ipAddress;
  }

  public boolean setipAddress(string newIp) {

    if (isValid(newIp)) {
      ipAddress = newIp;

      return true;

    } else {
      return false;
    }
  }

}
</code>```

Note that now we still have access to the IP address's value, and we can update it, but now we can be sure that when it is updated, the new value is a valid value, instead of something like weeeee!.

```<code>ia.ipAddress = "this won't compile";
ia.setipAddress("This won't update the address");
ia.setipAddress("192.168.0.1"); // works
</code>```

Similarly, what if we decide that a string is a poor way of storing an IP address? Maybe a quartet of ints would be better. Before, when the ipAddress field was public, any code that used it, either to simply view it, or to change it, would break if we tried to change our storage scheme. But since we're using public methods for access instead of directly accessing the field, we can do this without breaking anything:

```<code>public class IpAddress {

  private int part1;
  private int part2;
  private int part3;
  private int part4;

  public string toString() {
    return "" + part1 "." + part2 + "." + part3 + "." + part4;
  }

  public boolean setipAddress(string newIp) {

    if (isValid(newIp)) {
      part1 = extractOct(newIp,1);
      part2 = extractOct(newIp,2);
      part3 = extractOct(newIp,3);
      part4 = extractOct(newIp,4);

      return true;

    } else {
      return false;
    }
  }

}
</code>```

From the point of view of anyone using this class, it looks like this whether storing the IP address as a string or four ints:

```<code>public class IpAddress {

  public string toString()

  public boolean setIpAddress(string newIp)

}
</code>```

and they don't need to know, or care that things changed behind the scenes.*

*In general. Some rare cases might care. E.g. realtime systems can be sensitive to performance changes, whether faster or slower.

Body:
Sure, a developer with access to the source code could start manipulating whatever they want. And in the process make something very fragile and unmaintainable.

By making as much private as possible, and respecting that, and only exposing well defined interfaces, you can make it simple to change things behind the scene to, for example, fix bugs or improve performance. If other code is messing around with variables, then changes are quite difficult, because they will cause that other code to break.

I'm unsure exactly how Javascript handles privacy, but in languages like Java and C++, there is some compiler support for enforcing privacy.

Consider a class representing an IP address:

public class IpAddress {

  public string ipAddress;

}

Right now, anyone can put whatever they want into ipAddress (it's a public field).

IpAddress ia = new IpAddress();
ia.ipAddress = "weeeee!";

Last I checked, weeeee! was not a valid IP address. But, by making it private, we can make sure invalid addresses are thrown out. Of, course, we'll still need a way of accessing it and updating it. So we make public methods:

public class IpAddress {

  private string ipAddress;

  public string toString() {
    return ipAddress;
  }

  public boolean setipAddress(string newIp) {

    if (isValid(newIp)) {
      ipAddress = newIp;

      return true;

    } else {
      return false;
    }
  }

}

Note that now we still have access to the IP address's value, and we can update it, but now we can be sure that when it is updated, the new value is a valid value, instead of something like weeeee!.

ia.ipAddress = "this won't compile";
ia.setipAddress("This won't update the address");
ia.setipAddress("192.168.0.1"); // works

Similarly, what if we decide that a string is a poor way of storing an IP address? Maybe a quartet of ints would be better. Before, when the ipAddress field was public, any code that used it, either to simply view it, or to change it, would break if we tried to change our storage scheme. But since we're using public methods for access instead of directly accessing the field, we can do this without breaking anything:

public class IpAddress {

  private int part1;
  private int part2;
  private int part3;
  private int part4;

  public string toString() {
    return "" + part1 "." + part2 + "." + part3 + "." + part4;
  }

  public boolean setipAddress(string newIp) {

    if (isValid(newIp)) {
      part1 = extractOct(newIp,1);
      part2 = extractOct(newIp,2);
      part3 = extractOct(newIp,3);
      part4 = extractOct(newIp,4);

      return true;

    } else {
      return false;
    }
  }

}

From the point of view of anyone using this class, it looks like this whether storing the IP address as a string or four ints:

public class IpAddress {

  public string toString()

  public boolean setIpAddress(string newIp)

}

and they don't need to know, or care that things changed behind the scenes.*

*In general. Some rare cases might care. E.g. realtime systems can be sensitive to performance changes, whether faster or slower.


问:
C++ Header files design : just like defining an API?
I'm kind of new to large scale software development in C++, and I was wondering on the design side of things.

I was reading this question, and I thought that, overall, once we get past constant definitions and other trivial matters, C++ header files are just API definitions :

They define what other programmers (or yourself from other modules) will be able to use (classes, public functions), but no private class or function should be defined in it.
It's like the header file defines the abstractions (interfaces ...) and the source file implements it. Once the source file is compiled, the implementation details are hidden away, and remain the publicly available headers defining what the module can do.

I felt this view of header/source file separation was a lot easier to understand and follow than the usual explanations, since you can just think "would XXX be publicly available API material, or is it a sausage-making detail to be hidden away in an undisclosed source file ?"

Is my mental model of header files roughly correct ?
What did I miss ?

答:
It's not a bad mental model to use as a guide but unfortunately for historical / technical reasons C++ headers conflate interface and implementation in ways that this simple mental model doesn't fully capture.

In order to make good physical design decisions when things get a little more complex, it is generally necessary to understand the way headers work in C++ at a more detailed level.

To give an example: from your API view, a header file should not include the definition of a private implementation class. In practice however, such class definitions will often appear in a header file since the compiler will need to know their size if they are contained in any public classes. Techniques exist to break this kind of dependency but they generally impose a cost in terms of code complexity, performance or both. Understanding when it's appropriate to use one of these techniques requires a deeper understanding of how headers work in C++.


答:
Suppose that you're modeling a person, and as part of that you want to track the person's age.  You might use an integer to represent the person's age.  Would you want client code to be able to change the age of a person to a negative value?

In this example, making age something that is private, and providing public functions that operate on that value let you make certain guarantees about the variable's value.

Generally, private variables let you decouple client code from the solution representation, so that the representation can change without forcing the client to change.

Title: What is the usefulness of private variables?

Body:
While I've never used a language that had built-in variable privacy, a book I'm reading by Douglas Crockford explains a way to create privacy in JavaScript, however it doesn't make sense to me so. The term "private" isn't something I think of as even being possible in a programming environment, since everyone working on the code can potentially change any mutable object or method right?

So the two things that don't make sense to me are

how privacy is helpful

how privacy is defined - fundamentally one developer can't keep something in source code absolutely private ("untouchable", as I understand it) from another developer, so where does one consider the variable "private"? When it's hard to reach?

Can someone explain this, possibly with a "real-world" example?


答:
Imagine that you're writing a javascript library, and you have defined a variable size that you store some size in.  Since you don't encapsulate it, it goes into the global namespace.

Now someone comes along and assigns a value to size, not knowing that you've already defined it.  Oh, dear.  He just broke your library.  And when you assign to size again, you break his code.

Now drink a toast to encapsulation.


答: It would make no sense at all to force every developer of Linux kernel to use the same IDE (or use any IDE at all).</p>

Title: Should every member of a team use the same IDE?

Body:
Do you think it makes sense to enforce that every member of a team must use the same IDE?

For instance all engineers that are already on the team use IDE X. Two new engineers come and want to use IDE Y instead because that's what they have been using for several years now.

Do you have any experience with "mixed IDE" teams? If so what is it?


答:
Within software development, privacy (of software entities) is usually defined as restricting access to that variable/function/method.
If a variable is private, then only functions or methods that belong to the same class or module are allowed/supposed to access that variable.

As you see, privacy here is completely unrelated to which developer is writing the code, but rather is is about which parts of the code have access to which other parts of the code.

The advantage of private variables or functions is that, by restricting which parts of the code have access, you can more easily reason about how the variable gets used and who will be affected if you change it.


问:
MVC .NET APP Program Structure
I am just building a MVC .NET application, eventually this will use entity framework and the repository pattern to structure the program. The first release however will only be calling other jobs that run reports.

For this I was going to make the interface iReport of which another project (that can call Matlab) will implement and this way I have abstracted this report and can take away Matlab and replace it if need be with another system that can produce the report in question.

My question therefore is, presuming this is a good architecture, how to structure this, where to put this interface? Do I simply put it in a separate folder on the web app project?

This seems like a simple question but I tend to struggle with project layout as I want to make sure it is correct.

答:
It's good to put the interface with the domain objects it references.

So if you have Report, ReportLine, ReportType... etc and IReportGenerator I would stick them all in a class library project, with a 'Interfaces' folder/namespace for the interface.

This way, everything can reference the domain project and implement stuff using the objects and interfaces, but can then choose the implementation of the interface they would like to use without having to reference anything extra.

If you end up having lots of separate services, say IReportGenerator, IReportEmailer etc etc at some point you might want to split these out from the domain model class lib, just because they have such differing responsibilities, or perhaps they have to reference other libraries (although you should try and avoid this in your interfaces)

In this case, I would put the interface with the first implementation you write. say you have ReportGenerator_MatLab, you can stick it in that class lib. As you only have the one implementation (plus a mock!!) your projects are going to be referencing it anyway.

Title: MVC .NET APP Program Structure


答:
It's important not to conflate two different things. You can't guarantee that nobody will change the source of your class, and you can't guarantee that it will still work as intended if somebody changes it. But what you can do is make it a lot easier for you to write code which works as expected right now, under all possible use cases.

For example, let's say you want to create a Fraction. It needs some functionality. Let's say it needs to be able to check for equality with another fraction. (Realistically it'd probably need to to a lot more, but let's keep it simple). We also want a rule: a fraction can always be reduced (2/4 = 1/2).

Let's try (I'm going to use C#-ish syntax rather than javascript but it should be readable enough):

```<code>public class Fraction
{
    public int Numerator;
    public int Denominator;

    public Fraction(int numerator, int denominator)
    {
        Numerator = numerator;
        Denominator = denominator;
        Reduce();
    }

    public void Reduce()
    {
        //Some implementation here to reduce this fraction
    }

    public bool Equals(Fraction other)
    {
        return Numerator == other.Numerator && Denominator == other.Denominator;
    }
}
</code>```

Does this work? Well, no. What if somebody does this:

```<code>var aHalf = new Fraction(1,2);
var anotherHalf = new Fraction(2,4);
var same = aHalf.Equals(anotherHalf);  // This is true

anotherHalf.Numerator = 2;
anotherHalf.Denominator = 4;
same = aHalf.Equals(anotherHalf);  // This is false!
</code>```

Maybe you might try to put a call to Reduce() inside Equals. But then what if you do this:

```<code>var aHalf = new Fraction(1,2);
var anotherHalf = new Fraction(2,4);
anotherHalf.Denominator = 2;
anotherHalf.Equals(aHalf);

anotherHalf.Numerator = 1;
var same = anotherHalf.Equals(aHalf); // This is false!
</code>```

Because of the unexpected modification inside Equals, this code that looks like it should result in anotherHalf being 1/2, it's actually 1/1. Even more expected, if you'd done aHalf.Equals(anotherHalf), you'd have the opposite result.

What a confusing and complicated situation we've created for ourselves! And why? If you look back, the only functionality we decided Fraction needs is to expose Equals. So why did we also expose Numerator and Denominator and make it so hard to correctly implement the behaviour we actually need? All you need to do is make those private and our initial implementation works with no further issue.

Body:
It's important not to conflate two different things. You can't guarantee that nobody will change the source of your class, and you can't guarantee that it will still work as intended if somebody changes it. But what you can do is make it a lot easier for you to write code which works as expected right now, under all possible use cases.

For example, let's say you want to create a Fraction. It needs some functionality. Let's say it needs to be able to check for equality with another fraction. (Realistically it'd probably need to to a lot more, but let's keep it simple). We also want a rule: a fraction can always be reduced (2/4 = 1/2).

Let's try (I'm going to use C#-ish syntax rather than javascript but it should be readable enough):

public class Fraction
{
    public int Numerator;
    public int Denominator;

    public Fraction(int numerator, int denominator)
    {
        Numerator = numerator;
        Denominator = denominator;
        Reduce();
    }

    public void Reduce()
    {
        //Some implementation here to reduce this fraction
    }

    public bool Equals(Fraction other)
    {
        return Numerator == other.Numerator && Denominator == other.Denominator;
    }
}

Does this work? Well, no. What if somebody does this:

var aHalf = new Fraction(1,2);
var anotherHalf = new Fraction(2,4);
var same = aHalf.Equals(anotherHalf);  // This is true

anotherHalf.Numerator = 2;
anotherHalf.Denominator = 4;
same = aHalf.Equals(anotherHalf);  // This is false!

Maybe you might try to put a call to Reduce() inside Equals. But then what if you do this:

var aHalf = new Fraction(1,2);
var anotherHalf = new Fraction(2,4);
anotherHalf.Denominator = 2;
anotherHalf.Equals(aHalf);

anotherHalf.Numerator = 1;
var same = anotherHalf.Equals(aHalf); // This is false!

Because of the unexpected modification inside Equals, this code that looks like it should result in anotherHalf being 1/2, it's actually 1/1. Even more expected, if you'd done aHalf.Equals(anotherHalf), you'd have the opposite result.

What a confusing and complicated situation we've created for ourselves! And why? If you look back, the only functionality we decided Fraction needs is to expose Equals. So why did we also expose Numerator and Denominator and make it so hard to correctly implement the behaviour we actually need? All you need to do is make those private and our initial implementation works with no further issue.


问:
How to test a REST service without being excessive
So I have a REST backend (in node.js or Java doesn't matter but the example is in js).

I try to have a service for each endpoint so that the /users endpoint has two files:

usersRouter.js which includes the router endpoints with example code:

```<code>router.get('/users/:username',function(req,res,next){
    return userService.find(username);
}
</code>```

userService.js

```<code>function find(username) { //do some database stuff here }
</code>```

I think best practices call for testing all methods in your app with both unit testing the service and integration testing the endpoint.

Is it really necessary in this case? If the endpoint only calls one method then I could test only this one with all the available scenarios.

A downside would be that the function has more options that are not used by the endpoint and could be used by another endpoint/function but is it too much to test almost the same thing twice?

答:
When unit-testing the service layer, those tests should only verify the logic in the service layer itself and they should be fast and isolated from possible failures that lie outside the service layer.
This means that in the unit-tests of the service layer, dependencies of the service layer that can't be "guaranteed" to be error free or that might cause a slowdown of the tests. In particular, the database access should be mocked in the unit tests, because databases cause a lot of trouble in unit tests (in part due to slowness of the connection, and in part because they persist state between tests, which makes it hard to keep the tests independent).

In the integration tests of the endpoint, you would test all code that is involved when the end-point gets used, including the database.

If there is little logic in a particular function in the session layer, then you might forego unit-testing that function. This could be based on a risk assessment on how big the chance is that something will be wrong in that function that wouldn't be caught in another way.


问:
Is Model-View-Presenter (MVP) scheme useful for Android?
How to separate View and Presenter in Android, while the reactions on the user actions (Presenter part of MVP) are set into the same activities that shows GUI elements (View part of MVP).

"In model view presenter just as Martin Fowler  or Michael Feathers  [2] say, the logic of the UI is separated into a class called presenter, that handles all the input from the user and that tells the "dumb" view what and when to display" (cited from here).

Till now I thought that one of the main features of Android is the smart Activity that takes actions, reacts to them and shows the results. Is MVP scheme in contradiction with Android philosophy? Has it sense to try to realize it on Android? If yes, how could it be done?

答:
MVP is definitely useful for Android. It helps to organise and unit test your code. And the best part is new people reading your code will be able to understand the code and will start contributing soon as they know what should go where. Here is a very helpful link to understand MVP with examples.

Here is a brief explanation of all the three components of MVP

View

In android MVP, a view contains two things
Activity – android resource
View – java interface
Activity Implements the View and it injects itself(View interface) in the presenter so that presenter can talk to activity using view interface. First three blocks of the diagram shows the communication between View and The Presenter.

Presenter

Presenter acts as a middle layer between View and Data/Model. View(Activity) commands presenter to present something and presenter then takes data from the database/Model and gives back the presentable form of data to the View. View then takes care of displaying that data on the screen. And remember that Presenter is a plain java class it should not include any of the android components otherwise it will make the unit testing of the presenter hard.

If you wish to use database in the presenter then make activity create a database instance and inject it in the presenter. This will help you to mock the database while unit testing and will enable you to test the business logic.

Model

Model in MVP is nothing but your data source. View does not talk to data directly instead it commands Presenter to handle data for it and give the information back which can be displayed without any further modification.


问:
Is the `<table>` tag and `display:table` a functional or a layout directive?

Background

I've always disliked the idea of using the CSS property of display:table. Using it feels like an ugly hack and I always prefer to use a direct
 tag instead. Of course, I use it only when necessary and always prefer a non-
 based layout when possible. But for those occasions when a table is the only choice, I prefer the tag not the CSS. Naturally I've been reproached several times about this. In a recent discussion with Toni Leigh I finally managed to define my feelings about this issue well enough to make an argument out of it, so I'd like to present it here and hear what you guys think.

Crucial definitions

In HTML every tag can be thought of containing three distinct properties - functionality, layout and semantics.

Functionality is what the tag does. An href=""> redirects the user when clicked. An <input type="text"> creates a textbox. A
 wraps a block of content so that it can be manipulated further as a whole. An  shows a picture. Etc.

Layout is what the tag looks like (and sounds like, if you're using a screen reader). This contains things like colors, borders, spacings, fonts, etc.

Semantics is what the tag means (or represents). It could be a menu item, a blog post, a photograph, a design element, etc.

The meat of the issue

In modern HTML the layout is the province of CSS, while both functionality and semantics are dependent of the tag name and occasionally a few attributes, which has the side effect of intertwining them. People try very hard to keep these two domains (layout and functionality/semantics) separated, so that the necessities of one would not affect the other. For that reason using a
 for layout is scoffed, because that imposes a semantic change where only a layout change should be. And the preferred workaround is to use display: table as an alternative for achieving table-like layout effects but without the semantic changes that come along with the
 tag. (Preemptive retort: no, a
 doesn't make a bigger tag soup. You get all the same tags with display:table too, they're just all called
 now)

The reason this feels so "wrong" to me is because I see the display:table as a CSS property which changes the functionality of a tag. It's like using CSS to change an  to a <form> or an <input type="text"> into a <button> or something (well, if it was possible). As far as I'm aware it's the only CSS property with such an effect. Everything else really does affect only layout, but display:table does more. For this reason it feels like it shouldn't even be in CSS. In particular:

New kind of relationships between tag sizes are created. In non-tabular layouts, only parent-child relationships between tags are able to affect each other. In a table, other tags in the same row/column can affect a cell's size, as well as the total width/height of the entire table.

To make it worse, you get colspans/rowspans (CSS browser support flaky at the moment, but it's getting there)

The display:table-header element will be printed on every page, when printing the document.

You get vertical alignment of text and border collapse.

And probably others I haven't thought of. Well, I guess they are sort of layout features, but they are a whole world apart from anything else that CSS can do. Treating some markup like a table switches the browser into a completely different mode, which is why I think it's a different functionality, not just layout.

The question

What do you think? Can all the changes that display:table brings be counted only as layout, or is it a change of functionality as well?

答:
I'm not quite sure what you mean by "functionality", but display is surely a special property. display changes the relationship between how elements interact with each other. The display property can change a block element (act like box) to become inline element (act like text), or vice versa.

AFAICT, display is the only CSS property that actually change not just how the element looks, but the entire algorithm used to render the element, how the element interact with other elements during layout, and how all other properties are interpreted.

When you look at what the other values for display, then display: table is not really very special at all.


问:
What's the name for the 'spec' of a function/method?
I'm pretty sure there is a special name for the 'spec' of a function/method.  It's a word that refers to

how many arguments it takes

the order of arguments

which arguments are optional

Is there a name for that?

答:
TL;DR  You're probably talking about a function signature (or method signature), part of which is a type signature.

But really depends on what you consider a function "spec".  I interpret it as "all the information required for a programmer to call a function".  This includes the function name, the parameter type, order, and necessity, probably the return type, and probably even that function's namespace.

But whether or not all those things are required (or even well defined) depends on the language/environment you're using.  Also, if you change the definition to "all the information required for a machine to call a function", the spec is likely different1.

Strictly speaking, a function (or method) signature is not a consistent term,2, 3 even within the same language.4, 5, 6, 7  But it's almost certainly the word you're looking for, because it'll be understood by almost any programmer.

C++ Spec Draft n337, definition 1.3.17, signature does not include return type, because it is not necessary to resolve the function.

"signature" does not include namespace information

"signature" includes exceptions and modifiers like public, static, etc

C++ "signatures" do not include return type

C++ "signatures" do include return type.

C++ "signatures" do not include return type, unless the function is the specialization of a template.

C++ "signatures" include namespace (scope) information and "other miscellaneous" stuff...


问:
Debug function input vs expecting code users to read the documentation - How far do I go?
I could write an endless amount of debugging code to handle the various components of input for a function, check that the correct data types are used, make sure things are decendants of the proper prototype objects, the data is within a certain value range or set... The list could go on and on.

But also of course I can use documentation comment APIs to generate good documentation on the expected input and usage.

My question is, how far/in-depth should I go as far as debugging/checking input for code users versus expecting them to read the funtion / method's documentation for proper use?

We could say "That's up to whoever's in charge" but I'm interested in best  practice for maximum efficiency.

答:
For a public-facing API, here's my rule(s) of thumb:

Validate all inputs that can cause unexpected behavior.

Validate inputs when you first see them.

Don't re-validate inputs in internal helper functions.

For inputs that could conceivably come from user input, return helpful error codes / messages.

if (date < today) return err_NEED_FUTURE_DATE;

note that it's not just err_INVALID_DATE, that doesn't provide enough help.

For inputs that likely come from the programmer, raise Assertions/exceptions:

if (buffer_size < 1) RAISE("Buffer must be at least one byte");


问:
What are you telling yourself if you can't understand new concept, paradigm, feature ...?
Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before.

I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!"

What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ?

How do you handle your self-esteem in such situations ?

答: Practice makes perfect. Read more, practice more until you understand. It's okay to take longer than others.</p>


问:
Service oriented web architecture speed
Imagine a simple service architecture setup: single server where I have one service acting as a REST API (PHP), another service for rendering frontend (nodejs), and maybe a database service.

They all communicate through localhost requests, so for example frontend gets data from API by calling http://localhost:{API PORT}/v1/products. Now the request flow would be frontend -> rest api -> database -> rest api -> frontend -> response to client.

Is there a performance penalty when using this approach vs using one monolithic application, where everything is together? Or is it better to utilize something like RabbitMQ for this kind of setup?

答:
Why not build out a few simple services that communicate in a chain to test it out?  The big thing you'd want to test is how many users it can support before it starts to get bogged down.

I personally think that tripling the http traffic on a single server is a bigger performance penalty than a lot of people may think, but it comes down to what your SLA is and whether the architecture meets it.  If this is users making web requests to view a web page, chances are it will meet SLA for a pretty high user load.  If this is an automated service making thousands of requests in a short amount of time, chances are much better that it'll become a bottleneck before other layers.  But chances are also high that you can then toss it into a web farm and remove that bottleneck with basically no additional effort, too.

Title: Service oriented web architecture speed


问:
Object creation: when should I expose a factory vs wrapping class?
I am having some problems trying to figure out when to use a factory or to wrapper class. This question is slightly geared towards C# I guess, so I'm not sure if this is the correct place to ask.

Say there is a library that exposes an interface called IStackExchangeClient, and multiple differing implementations of that interface (private implementations that clients will not know about), HttpStackExchangeClient, UdpStackExchangeClient.

We can allow the object creation of the interface through a factory, like StackExchangeClientFactory.Create(), or we can wrap it up in another class like StackExchangeClient that internally does the same thing, but simply proxies.

In the second instance, clients can write new StackExchangeClient() which feels much more natural to me. So my question is, when do I choose one or the other? What are some of the considerations that I should be taking in?

I've thought hard about it and I can't choose between one style or the other, but clearly some parts of the .NET framework use factories, and some parts don't, even when there are multiple underlying implementations of its interface.

Thank you!

答:
I do not quite understand your question. And I think there are some misconceptions:

I) A factory is a design pattern used to separate object creation from object consumption. There are two possible ways to deal with that:

1) You delegate instance creation to a separate object

2) A static method is used to create instances

The advantage: Dependencies are no longer created. The object in need asks for its dependencies. Factories allow dependency injection. But instead of managing a dozen factories and all the wiring up, you leave that for an abstraction called (DI-) container.

II) An Interface is the C#/Java way of dealing with multiple inheritance. Instead of letting object inherit implementations from multiple objects, you only inherit an API so to say. An interface is a contract that defines an API and leaves the implementation to the object. Objects define families of somehow related objects via an is-a-relationship, you could say, interfaces define a relationship of different objects sharing common behaviour.

What does that mean for (I)?

If you have a factory for different objects who follow the same API, the return-type of the factory is the common interface ( think of ILogging with FileLogger, DatabaseLogger, EventlogLogger and so on).

The consuming object only gets something that behaves like a Logger. It doesn't need to know which kind of logger it is using - even if it is a NullLogger.

III) A Proxy could be any object mimicing another object. A common usecase is mock objects. You wrap one functionality with another.

Which one you want to implement depends on your intention:

If you are designing an object which needs somehow to use a common API for HttpStackExchangeClient and UdpStackExchangeClient you would imlement it via IStackExchangeClient and a factory

Say HttpStackExchangeClient and UdpStackExchangeClient have a different API and you want one behave like the other you would use a proxy wrapping up the other.

If you have IStackExchangeClient as an interface and HttpStackExchangeClient and UdpStackExchangeClient implement it as well, using a proxy makes no sense, since the consuming object does not know which one it is going to use.

I've thought hard about it and I can't choose between one style or the other, but clearly some parts of the .NET framework use factories, and some parts don't, even when there are multiple underlying implementations of its interface.

Note, that the framework has a history and was not always designed thoroughly (I would bet), which might be the reason for some inconsistencies.


问:
How to accomplish a task of evaluating editable variables and formulas, using PHP?
Task as defined:

User needs to be able to define their own variables and formulas to operate on those variables, to get output based on their inputs.  Since formulas and variables and their inputs change often, user needs to have control.

Example

```<code>//inputs (may be entered directly or provided by database)
$a = 4;
$b = 6;

//formulas:
$c = $a + $b * 5.35;

//outputs
print $c;
</code>```

This is to be entered by a user into i.e. a textbox on a website, and have that be saved as "master template" to be used to compute the author's computations.

Thought #1

Use PHP Eval:   (function that runs arbitrary source code)

But ...

If eval() is the answer, you're almost certainly asking the wrong question.

  -- Rasmus Lerdorf, BDFL of PHP

but eval() may actually work well for this, but that means

sanitizing inputs

filtering outputs

allowing expected user and unexpected (malicious) users free run of eval

teaching users subset of PHP

Thought #2

Implement a simple parser for a simple language (i.e capable of processing the above example).  It is a tad more work, or a bit more work depending on what functionality users will ask for and how the project will develop in the future.

Question

Are there any other ways to solve this problem?  In effect, I am designing a module that is supposed to work like a mini-Excel spreadsheet, with power of using arbitrary user-modifiable formulas and variables, and outputs.

答:
One reason "you're almost certainly asking the wrong question" is that properly sanitizing and filtering requires parsing.  In other words, you have to implement thought #2 in order to implement thought #1 safely for untrusted input.  Most people don't realize that and so end up doing a very poor job of it.  Trust me (and trust Rasmus Lerdorf for that matter), you're better off biting the bullet and going with a proper parser from the beginning.

Google "PHP parser generator" for lots of resources to get you started.  There's a bit of a learning curve, but luckily for you, mathematical expression evaluation is the "hello world" of these kinds of libraries.


问:
OAuth2 ROPC vs Basic Auth for public REST APIs?
The specific use case I'm interested in here is authenticating REST clients against publicly-available server endpoints (such as a public REST API).

The simplest solution here is Basic Auth. But I often hear OAuth2 touted as a superior auth solution in almost all circumstances.

The thing is, the only OAuth2 grant type that is feasible for a REST client authenticating against a REST server is Resource Owner Password Credentials (ROPC), because Code Grants and Implicit Grants require a UI/webpage (hosted by the Auth Server) for the user to login to and manually authorize the client app.

The way ROPC works is, by sending the resource owner's username/password, and the client ID as query string params?!? This is even less secure (IMHO) then Basic Auth, which at least base-64 encodes the credentials and sends them inside a header which can be encrypted by TLS!

So I ask: in the context of public REST APIs, is OAuth2 ROPC really any better than Basic Auth? What is more secure than OAuth2 ROPC?

Update

I just read this excellent article which explains Amazon's non-OAuth2 based REST security for AWS. It is essentially a private key-based solution where hashes of each REST request are generated and sent as sidecars along-side the normal (un-encrypted) request. Only the client and the server know the private key, so when the server receives the request (again, containing the normal request + the hashed request), the server looks up the client's private key, applies the same hash to the normal request, and then compares the two hashes.

This sounds way more complicated, complex and secure than OAuth2's ROPC! Unless I'm missing something major here, OAuth2 ROPC is just sending client_id, username and password as query string params...totally and utterly unsecure! This HMAC/hashed-based solution seems to be much more impressive and secure.

The thing is, even the author of that article goes on to say:

You [will] also slowly realize and accept that at some point you will have to implement OAuth...

Ba-ba-bwhat?!?! If OAuth2 is less secure than this clever HMAC/hash-based solution, why does the author of this article feel OAuth needs to be embraced at some point. I'm so confused.

答:
I think you need to understand the terminologies first. You are comparing- Authorization and Digital signature

OAuth is open standard for Authorization, where as what amazon is doing (as per the article and details provided in your question) is creating a valid digital signature which gives a recipient (here Amazon) reason to believe that the message was created by a known sender, that the sender cannot deny having sent the message (authentication and non-repudiation)

For which authorization mechanism to use, it more or less depends on your use-case.

Below is what can be found on StackOverflow here:

Basic authentication which requires a very simple hashing in order to calculate the single required header - OAuth is without a doubt a more expensive authentication. The important thing to realize is that the two authentication mechanisms serve entirely different purposes. Basic Auth is for authenticating a client to a primary application. OAuth is for authorizing a third party to access client data from a primary application. Both have their place and selecting one over the other should be driven by the particular use case of the implementation.

And here is another interesting article comparing the two.

Basic Authentication over SSL is actually fairly responsible, from a simplistic security standpoint. When we’re contending with usernames and passwords, Basic auth is a prevalent solution as it’s so easy to implement. The transmission of credentials is encrypted over SSL, and use of the “Authorization” header is ubiquitous in HTTP clients and systems.


答:
As far as I understand it, 'encapsulation' is primarily about protecting the internal state of the system that you're developing.

Say you're developing a class with a few fields and methods:

```<code>class Arithmetic
{
    private int j;
    private int k;

    public Arithmetic(int j, int k)
    {
        this.j = j;
        this.k = k;
    }

    public int returnProduct()
    {
        return this.j * this.k;
    }

    public int returnSum()
    {
        return this.j + this.k
    }
}
</code>```

In this example the only entry-point to change state within the class is through the constructor. So when you create an object of type Arithmetic you know beyond a shadow of a doubt what j and k are when you go to call returnProduct and returnSum.

Now let's look at it again but with a setter on one of the variables:

```<code>class Arithmetic
{
    private int j;
    private int k;

    public Arithmetic(int j, int k)
    {
        this.j = j;
        this.k = k;
    }

    public setj(int j)
    {
        this.j = j;
    }

    public int returnProduct()
    {
        return this.j * this.k;
    }

    public int returnSum()
    {
        return this.j + this.k
    }
}
</code>```

Now if somebody instantiates an object of type Arithmetic, and then someone later takes that same object and updates one of it's fields with the setter, the object may return unexpected behavior.

So to generalize the purpose of privatization or 'encapsulation' (one of the three pillars of OO programming), in the first example what we're doing is minimizing a programmer's ability to mutate the state of the object.

The more we code in that style the more certain we are of the state of our system at any given time, and the less error prone our code will be.

So the general rule of thumb is this:

When you're coding only allow a programmer or user the minimum amount of visibility into the system that still allows them to either use the system or continue developing the system.

Body:
As far as I understand it, 'encapsulation' is primarily about protecting the internal state of the system that you're developing.

Say you're developing a class with a few fields and methods:

class Arithmetic
{
    private int j;
    private int k;

    public Arithmetic(int j, int k)
    {
        this.j = j;
        this.k = k;
    }

    public int returnProduct()
    {
        return this.j * this.k;
    }

    public int returnSum()
    {
        return this.j + this.k
    }
}

In this example the only entry-point to change state within the class is through the constructor. So when you create an object of type Arithmetic you know beyond a shadow of a doubt what j and k are when you go to call returnProduct and returnSum.

Now let's look at it again but with a setter on one of the variables:

class Arithmetic
{
    private int j;
    private int k;

    public Arithmetic(int j, int k)
    {
        this.j = j;
        this.k = k;
    }

    public setj(int j)
    {
        this.j = j;
    }

    public int returnProduct()
    {
        return this.j * this.k;
    }

    public int returnSum()
    {
        return this.j + this.k
    }
}

Now if somebody instantiates an object of type Arithmetic, and then someone later takes that same object and updates one of it's fields with the setter, the object may return unexpected behavior.

So to generalize the purpose of privatization or 'encapsulation' (one of the three pillars of OO programming), in the first example what we're doing is minimizing a programmer's ability to mutate the state of the object.

The more we code in that style the more certain we are of the state of our system at any given time, and the less error prone our code will be.

So the general rule of thumb is this:

When you're coding only allow a programmer or user the minimum amount of visibility into the system that still allows them to either use the system or continue developing the system.


问:
JavaScript extend vs mixin
After having read Eric Elliott's Fluent JavaScript article, I was and still am toughtful about the way to play with instance prototypes.

On one side, you have the extending inheritance...

```<code>var B = function() {} ;
B.prototype = new A() ;
</code>```

Or the new way of doing it...

```<code>B.prototype = Object.create(A.prototype) ;
</code>```

And on the other side, you have the mixin, creating a mix of multiple prototypes that will be inherited to instances.

```<code>var B = function() {} ;
// Basic mixin from A
for (var m in A.prototype) B.prototype[m] = A.prototype[m] ;
</code>```

In his article, Eric Elliott encourages us to avoid extending types but to compose (mixin) sort of components objects/prototypes instead (see also Stampit on github). I totally agree with that.

However, it seems to break one major feature (and philosophy) in JavaScript : Modularity. What I mean is the fact that altering prototypes will be automatically available for all instances by references.

Here is a basic example of the prototype inheritance :

```<code>var A = function() {} ;
A.prototype.fn = function() { return 1 ; } ;

var a = new A() ;
a.fn() ; // 1

A.prototype.fn = function() { return 2 ; } ;
a.fn() ; // 2
</code>```

And now with an extended prototype :

```<code>var B = function() {} ;
B.prototype = Object.create(A.prototype) ;

var b = new B() ;
b.fn() ; // 2, inherited from A.prototype
</code>```

Okay this is working well, however we can't inherit from multiple prototypes ; plus classical inheritance is generally avoided.

The other solution would be mixin then :

```<code>var D = function() {} ;
// Let's imagine a mixin function mixing D with some prototypes...
mixin(D, A.prototype, C.prototype, R.prototype) ;

var d = new D() ;
d.fn() ; // 2, inherited from A.prototype ? Let's see...

A.prototype.fn = function() { return 3 ; } ;
d.fn() ; // 2, what a shame...
</code>```

Indeed, mixin only copy all functions from a prototype to another. This means there is no more references between those types, and thus modularity looks broken here (also tested with Stampit).

I'm now thinking of a tweaky solution to keep references to original prototype objects and not only the functions inside.

What about cascading inheritances ?

Not like D <- C <- B <- A, as it will alter B and C and looks restrictive.

But like D <- (((p <- A) <- B) <- C), where p is a private prototype reserved for D only. Neither B nor C will be altered, only p will be a straight cascade inheritance. D will have all methods from the listed prototypes, and if we want to inherit from another one, just restart the process from zero, like D <- ((((p <- A) <- B) <- C) <- R).

The only drawback I see would be around performances. Each time we add a new inheritance, we'll have to restart the whole process : Indeed, after inheriting, we add new functions to the prototype (or override some), and this must be always at the end of the process, thus after R inheritance :

Before : D <- ((((p <- A) <- B) <- C) <- {}) where {} is the set of new/overriding functions.

After : D <- (((((p <- A) <- B) <- C) <- R) <- {}), and not ... <- {}) <- R).

Would it be interesting to have a little library for that ? I would be up for doing this, allowing multiple prototype inheritances.

So... what do you think about this all ?

答:
With Stampit, there is intentionally no link between prototype mixins and the original source, and that's by design, because altering the prototype of any instance could then alter the original prototype.

In your post, you seem to think that's a bad thing, but in practice, mutating prototypes after object instantiation has a myriad of wide-ranging side effects that can significantly impact both the robustness of the app (it's much harder to understand what changes will impact which objects. i.e., you think you're fixing a bug in your sprite animations, and suddenly your particle rendering engine breaks, because they share a common prototype), and performance (altering prototypes causes JS engines to throw away all their cached object property optimizations, including optimizations that impact the perf of every piece of code that uses any descendent object).

In other words, what you're trying to do is widely considered an anti-pattern in the JavaScript community.

Another interesting point: The new Stamp specification allows you to pass an instance into the stamp. If you do so, the stamp will not alter the original prototype, and the original prototype will actually appear in the prototype chain, meaning that what you're suggesting will be possible in the next version of Stampit -- but my warning that altering prototypes after instantiation is an anti-pattern still stands.

Title: JavaScript extend vs mixin


问:
The present and future of programming in local languages
Can programming become language-independent? Will we always program in English? Will we ever be able to program in our local languages? Is there any research that addresses the matter? Are there any such developments?</p>

答:
There have been attempts to introduce programming language flavors translated into a local spoken language around the globe. They however never came to be more than experiments.

Some customer-oriented languages are localized like Excel macros language. But these are really end-user oriented.

Programmers will always need something universally understood. For now it is English.

Will we ever be able to program in a language other than English?

Unlikely. For a simple reason there is no advantage to it. The programming language itself, there is not that much linguistic content within so it's possible for everyone to learn a few English keywords.

But the rest has to be understood worldwide non-ambiguously. Compiler output, error messages, documentation for tools and libraries. It's important for worldwide knowledge sharing and exchange.

Additionally, in the times of globalization and distributed teams there has to be the one and only language for comments in code, documentation and collaboration.  Tech articles, blogs, books. International conferences. People need to understand each other otherwise things get unnecessarily complicated.


答: Header file as a pure interface works more or less fine with classes. As soon as templates come into picture, this model stops working whatsoever. Templates are not compilable, and the whole template implementation must appear in the header.</p>

Title: C++ Header files design : just like defining an API?

Body:
I'm kind of new to large scale software development in C++, and I was wondering on the design side of things.

I was reading this question, and I thought that, overall, once we get past constant definitions and other trivial matters, C++ header files are just API definitions :

They define what other programmers (or yourself from other modules) will be able to use (classes, public functions), but no private class or function should be defined in it.
It's like the header file defines the abstractions (interfaces ...) and the source file implements it. Once the source file is compiled, the implementation details are hidden away, and remain the publicly available headers defining what the module can do.

I felt this view of header/source file separation was a lot easier to understand and follow than the usual explanations, since you can just think "would XXX be publicly available API material, or is it a sausage-making detail to be hidden away in an undisclosed source file ?"

Is my mental model of header files roughly correct ?
What did I miss ?


问:
Deploying and maintaining a script on customer's domains
I am trying to figure the best way (or just the pros and cons of various options) for delivering a service via a script which runs on the customer's site (think Google Analytics).

Unlike Google Analytics, the script needs to be deployed from the customer's domain so I cannot just ask customers to insert a link to get the script from my site.  The obvious solution is to just let customers download a copy of the script and host it on their own domain but the downsides are

Monitoring and controling usage of the service

Ensuring customers are using the latest updates of the script.

Are there any ways to address this issue or perhaps even other methods of deploying the service altogether.

答:
To take care of downside #2 the script itself can be stamped with a version, check at a specific URL that you control which is the latest version that should be used and warn that it needs to be updated, eventually with a grace period, after which it simply refuses to work. Of course, this would only work after deploying everywhere a script version which includes such version check, so you'd want to add it ASAP.

It might be possible to also offer a trigger for automatic downloading and deploying of script updates on the customer sites from the script itself. Customers would have to be willing to use such trigger, but that can be difficult in terms of support as different customers may have different deployment requirements, processes, strategies. Might be worthy for select (well paying or "friendlier") customers.

To address downside #1 the script can similarly check at a specific URL that you control their service level config (based on some sort of client or licence ID) and act accordingly. On your server side you can use the accesses to that URL to monitor usage and provide customized configurations.

You can even merge the #1 and #2 checks to one well-crafted URL and obtain both version and client ID check in a single request/reply exchange (with a side effect that you can even allow different per-client script versions out there if needed, which may come handy occasionally - no need to churn new versions to all clients for updates relevant to only a few clients).

I'm assuming here no malicious intent (i.e. customers hacking the script to mislead/avoid these checks), otherwise a more solid/secure enforcing approach would be needed.


答:
There's an XY problem floating around in this question. I'll try to answer both parts of it.

From comments, the core problem:

I am trying to ease the job of the people in my company who came to me requesting to find a better solution than using Excel spreadsheets to do various custom-product computations, that change frequently. They want to move away from Excel, and onto the web, and they want to be able to update formulas and variables themselves. Excel is not on the web and they have to pass excel sheets to each other each time they make a change, creating tons of outdated excel sheets in the process that linger on people's machines. I am to try and make this process better.

This is a content management problem - not a programming one. You are looking for solutions that involve the use of Excel on the web.  One option is a enterprise content management solution such as Sharepoint.  Another is the Excel Web App. This is the problem you are really trying to solve - having a consistent single source of the data and calculation.

Now, the "lets try to implement this in another language."  Your options are:

Unsafe full language with eval

Writing a domain specific language that is as powerful as Excel

One should realize that the spreadsheet is, at its heart, a functional language with equations and data mapped onto a cartesian plane of rows and columns.

You are going to run headlong into Greenspun's tenth rule

Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

You are writing another functional language in php (if you're lucky - thats to help users retain as much of their skills from Excel to this language). You are going to try to make it so that it is 'safe', and 'easily understood by someone who has no more programing experience than writing Excel equations' (and lacking the useful checking that excel provides you).

You are going to persist this information (the code is data) into a database (if you are lucky - some other data store if you aren't) somehow, pull it out of the persistence, evaluate it all on the fly, allow someone to make a change, content management on top of that (who made the change?), and possible versioning too once you're done with the project.

The thing you are going to end up building to try to support the core problem is not going to be small.  Ever time you turn around users are going to be asking for another function to be added.  Could you add ACCRINT? How about LINEST? How do I do a LOOKUP or VLOOKUP in this language?

This is a wonderful idea to have a team of talented coders to be working on as a product to sell. It is an impossible task for a side project for a single programmer (or even small team) with other priorities and fires going.

I'm not saying you can't do it. But the problem that you are trying to solve with this solution isn't even going to be a suitable duct tape solution for any duration of time... and the support of the hypothetical application will be a full time job of its own.

Use an existing tool that solves your problem. Its price is likely a small fraction of a FTE.

Title: How to accomplish a task of evaluating editable variables and formulas, using PHP?

Body:
Task as defined:

User needs to be able to define their own variables and formulas to operate on those variables, to get output based on their inputs.  Since formulas and variables and their inputs change often, user needs to have control.

Example

```<code>//inputs (may be entered directly or provided by database)
$a = 4;
$b = 6;

//formulas:
$c = $a + $b * 5.35;

//outputs
print $c;
</code>```

This is to be entered by a user into i.e. a textbox on a website, and have that be saved as "master template" to be used to compute the author's computations.

Thought #1

Use PHP Eval:   (function that runs arbitrary source code)

But ...

If eval() is the answer, you're almost certainly asking the wrong question.

  -- Rasmus Lerdorf, BDFL of PHP

but eval() may actually work well for this, but that means

sanitizing inputs

filtering outputs

allowing expected user and unexpected (malicious) users free run of eval

teaching users subset of PHP

Thought #2

Implement a simple parser for a simple language (i.e capable of processing the above example).  It is a tad more work, or a bit more work depending on what functionality users will ask for and how the project will develop in the future.

Question

Are there any other ways to solve this problem?  In effect, I am designing a module that is supposed to work like a mini-Excel spreadsheet, with power of using arbitrary user-modifiable formulas and variables, and outputs.


问:
How to structure a SaaS application?

The Problem

I need to develop a Software-as-a-Service application, that will be used from our clients. The application contains a lot of forms (Company Application) using a step-by-step forms. They users will fill these forms, and see some progress.

The Company (our client), can have a view of they dashboard, showing they users, products and other informations, including company information and some customizations.

One thing that I'm trying to solve, it's: I need a subdomain for each of my client, and each User in Company, need to have a subdomain in Company.

For example, using the first approach (above), for example, what I'll have:
API: .myapp.com/api/v1
Client Base Page (rendered by my application): .com (CNAME to somewhere)
User Base Page (rendered by my application): ..com (CNAME to somewhere)

The things I can't figure how to do are:

It's better to develop a REST API, use the standards for that, and create a separate Front-end application (using Angular, Ember or other frameworks). Then I deploy the API, get the link, and setup it on my Angular application. This is a good approach?

Develop a Standard Application, where the same application connects to database and render the views, where the logic will be on Models and Controllers.

Other approach? (I think using microservices in this stage, will be cumbersome.

Based on that approaches, I've some questions.

In 1st case:

I think the best way for the API is to use a subdomain based on my startup domain, like: .mycompany.com/api/. This way, I can buy a wildcard SSL and secure the endpoint of each client. But what I see in applications like Stripe, it's using single endpoint, like: api.stripe.com with an EV SSL. So, both approaches are good and secure?

What it's a good approach to render the Front-end? Based on fact that on the front-end will be wildcard subdomains for each user.

So, what it's a good way to develop that?

Background

I'm using Rails 4, and Postgres (for multi-tenancy database), and if needed, I can develop using Angular.js or "static views".

答: Have you looked at the 'apartment' gem? I've never used it but I just watched a video on gorails.com that I think might help you. There's one using the gem and another one building it out from scratch. </p>

Title: How to structure a SaaS application?


答:
The answer to your question can be at the code level, protocol level or architecture level. I will attempt to summarize here most of the protocol level issues since that is usually critical in pros and cons analysis. Keep in mind that OAuth2 is much more than Resource Owner Password Credentials which, according to the specification, exists for "legacy or migration reasons", is considered "higher risk than other grant types" and the specification explicitly states that the clients and authorization servers "SHOULD minimize use of this grant type and utilize other grant types whenever possible".

There are still many advantages of using ROPC over basic authentication but before we get into that, let's understand the basic protocol difference between OAuth2 and basic authentication. Please bear with me as I explain these and will come to ROPC later.

User authentication flows

There are four roles defined in OAuth2 specification. With examples, they are:

Resource owner: The user who has access to some resource, e.g. in your case, different users may have different access level to the REST API;

The client: usually the application the user is using, and needs access to the resource to provide services to the user;

Resource server: the REST API in your case; and

Authorization server: the server to which user's credentials are presented and which will authenticate the user.

When a client application runs, it is granted access to the resources based on the user. If a user has administrator privileges, the resources and operations available to the user in REST API may be far more than a user without administrator privileges.

OAuth2 also allows the possibility of using a single authorization server with multiple clients and for multiple resources. As an example, a resource server can accept user's authentication with Facebook (which can act as authorization server in such a case). So when the user runs an application (i.e. the client), it sends the user to Facebook. User types their credentials in Facebook, and the client gets back a "token" which it can present to the resource server. Resource server looks at the token and accepts it after verifying that Facebook in fact issued it and allow the user access to the resource. In this case, the client never sees user's credentials (i.e. their Facebook credentials).

But let's say you are managing your user's identities (and have an authorization server) instead of Facebook, which grants tokens to your client already. Now, let's say you also have a partner and you want to allow their application (i.e. client) to access your REST API. With basic authentication (or even ROPC), the user will provide credentials to that client which will send it to the authorization server. Authorization server will then provide a token that can be used by the client to access the resources. Unfortunately, this means that user's credentials are now visible to that client too. However, you would not want a partner's application (who could be external to your organization) to even know a user's password. That's a security issue now. In order to achieve that goal, you would want to use another flow (such as the authorization code grant) in which the user directly provides credentials to the authorization server.

Thus, with OAuth2, one would ideally not use ROPC in such cases rather use a different one, such as authorization code flow. This protects any application from knowing the user's credentials which are presented only to the authorization server. Thus, a user's credentials are not leaked. The same issues apply with basic authentication, but in the next section, I will explain how ROPC is still better because the user's credentials still do not need to be stored by the client in ROPC for persistent access by the clients.

Note that when the user goes to the authorization server, the authorization server can also ask user to confirm that they want to allow the client to access the resources on their behalf or not. That is why it is called the  authorization server because the process of authorizing a client to access resources is entailed in the process. If the user does not authorize the client, it will not get access to the resources. Likewise, if the user themselves do not have access to the resources, the authorization server can still deny access and not issue a token.

In basic authentication, even the authorization server and resource server are combined into a single entity. Thus, the resource server wants to authorize the user, so asks the credentials from client. The client furnishes those credentials which are used by the resource server to authenticate the user. This means that multiple resource servers will essentially be requiring credentials from the user.

Token issuance

The clients get tokens from authorization server, keep them around and use those to access the resources (more details on tokens themselves below). The clients never know the user's password (in flows other than ROPC) and do not need to store it. In ROPC, even though the clients do know the user's password, they still do not need to store it because they use these tokens to access resources. By contrast, in basic authentication, if a client does not want to have user to provide credentials in every session, then the client has to store the user's password so they can furnish it the next time around. This is a major drawback to using basic authentication unless the client is only a web application in which case, cookies can address some of these concerns. With native applications, that's usually not an option.

There is another aspect of OAuth2 which is entailed in how tokens are issued and they work. When a user furnishes credentials to the authorization server (even in ROPC), the authorization server can give one or more of the two types of tokens: 1) access token, and 2) refresh token.

Access tokens are sent to the resource server which will grant access to the resources after validating it, and usually they have a short lifetime, e.g. 1hr. Refresh tokens are sent to the authorization server by the client to get another access token when it expires, and usually have a large lifetime (e.g. a few days to months or even years).

When the client provides the access token to the resource server, it looks at the token and after validating, looks inside the token to determine whether to allow access or not. As long as access token is valid, the client can keep using it. Let's say the user closes the application and starts it the next day, and the access token is expired. Now the client will make a call to the authorization server and present the refresh token assuming it's not expired. Authorization server, since it already issued the token, verifies it and can determine that the user does not need to provide the credentials again and thus gives another access token to the client. The client now has access to the resource server again. This is how typically the client applications for Facebook and Twitter ask for credentials one time and then do not require the user to provide credentials again. These applications never need to know the users credentials and yet can access resources every time user starts the application.

Now the user can go into the authorization server (e.g. in their Facebook user profile), change password without impacting any client applications. They will all continue to function properly. If the user loses a device on which they already had an application with refresh tokens, they can tell authorization server (e.g. Facebook) to "log them out" of those applications which the authorization server (i.e. Facebook) will accomplish by not honoring any existing refresh tokens and forcing the user to provide credentials again when they try to access resources through those applications.

JWT is simply the token format that is usually used with OAuth2 and OpenID Connect. The methods of signing the token and validating it is also standardized with libraries available for those instead of every resource server implementing yet another solution. Thus, the advantage lies in reusability of code that has been vetted and continues to be supported.

Security implications

Basic authentication will be weaker when any of the above scenarios are in the picture. There is also an extensive threat model for OAuth2 available for developers who can use the suggestions in it to avoid common vulnerabilities in their implementations. If you go through the threat model, you will see that many implementation related vulnerabilities (such as open redirector and CSRF) are also covered in it. I did not go through comparison of those against basic authentication in this response.

The last major advantage of OAuth2 is that the protocol is standardized and multiple authorization servers, clients and resource servers honor it. Numerous libraries are available to developers, which are maintained so as security issues are found in implementations, the libraries are updated while allowing interoperability.

Conclusion

If you are writing a new application, IMO, the ideal case would be to avoid both the basic authentication and ROPC because of the issues inherent in them. However, each application has different needs, timelines, developer proficiency etc. so the decision is case-by-case. But even if you did not have any more need than basic authentication, by choosing it, you could lock yourself into an architecture that may not be easy to extend (e.g. if you have multiple servers in the future, you would not necessarily want to have the user provide credentials to each one of them rather just provide to authorization server once, which can hand out tokens, etc.)

Note that I did not address your comment about how the credentials are sent over the wire because those can be secured using TLS or a similar protocol, or proof of possession etc. As someone already suggested, base 64 encoding is 0 security, please do not be deluded by that. The differences mentioned above are usually at the architectural level and thus that is where I focused because architecture is the hardest to change once implemented.

Azure Active Directory B2C Basic, a service which I work on and was recently released for public preview, allows third party application to use AAD as the authorization server with interoperability with social IDPs (such as Facebook, Google, etc.). It also allows users to create their own accounts instead of using social IDPs and those can later be used for authentication purposes. There are a few other services also like that (e.g. another one I know of is auth0) which can be used by developers to completely outsource authentication and user management for their applications and resources. The same protocols characteristics that I mentioned above is used by developers to decouple authorization server (AAD), a resource (e.g. their REST APIs), the client (e.g. their mobile applications), and users. I hope this explanation helps somewhat.

Title: OAuth2 ROPC vs Basic Auth for public REST APIs?

Body:
The specific use case I'm interested in here is authenticating REST clients against publicly-available server endpoints (such as a public REST API).

The simplest solution here is Basic Auth. But I often hear OAuth2 touted as a superior auth solution in almost all circumstances.

The thing is, the only OAuth2 grant type that is feasible for a REST client authenticating against a REST server is Resource Owner Password Credentials (ROPC), because Code Grants and Implicit Grants require a UI/webpage (hosted by the Auth Server) for the user to login to and manually authorize the client app.

The way ROPC works is, by sending the resource owner's username/password, and the client ID as query string params?!? This is even less secure (IMHO) then Basic Auth, which at least base-64 encodes the credentials and sends them inside a header which can be encrypted by TLS!

So I ask: in the context of public REST APIs, is OAuth2 ROPC really any better than Basic Auth? What is more secure than OAuth2 ROPC?

Update

I just read this excellent article which explains Amazon's non-OAuth2 based REST security for AWS. It is essentially a private key-based solution where hashes of each REST request are generated and sent as sidecars along-side the normal (un-encrypted) request. Only the client and the server know the private key, so when the server receives the request (again, containing the normal request + the hashed request), the server looks up the client's private key, applies the same hash to the normal request, and then compares the two hashes.

This sounds way more complicated, complex and secure than OAuth2's ROPC! Unless I'm missing something major here, OAuth2 ROPC is just sending client_id, username and password as query string params...totally and utterly unsecure! This HMAC/hashed-based solution seems to be much more impressive and secure.

The thing is, even the author of that article goes on to say:

You [will] also slowly realize and accept that at some point you will have to implement OAuth...

Ba-ba-bwhat?!?! If OAuth2 is less secure than this clever HMAC/hash-based solution, why does the author of this article feel OAuth needs to be embraced at some point. I'm so confused.